Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add oneflow.cuda.get_rng_state and oneflow.cuda.get_rng_state_all api #9760

Merged
merged 6 commits into from
Jan 16, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/source/cuda.rst
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ Random Number Generator

manual_seed_all
manual_seed
get_rng_state
get_rng_state_all


GPU tensor
Expand Down
2 changes: 2 additions & 0 deletions python/oneflow/cuda/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,3 +191,5 @@ def empty_cache() -> None:

"""
return flow._oneflow_internal.EmptyCache()

from .random import * # noqa: F403
32 changes: 32 additions & 0 deletions python/oneflow/cuda/random.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import oneflow as flow
from oneflow import Tensor
from typing import Union, List
from . import current_device, device_count

def get_rng_state(device: Union[int, str, flow.device] = 'cuda') -> Tensor:
r"""Returns the random number generator state of the specified GPU as a ByteTensor.

Args:
device (flow.device or int, optional): The device to return the RNG state of.
Default: ``'cuda'`` (i.e., ``flow.device('cuda')``, the current CUDA device).
"""
# TODO (add lazy initialization mechanism in OneFlow)
# _lazy_init()
if isinstance(device, str):
device = flow.device(device)
elif isinstance(device, int):
device = flow.device('cuda', device)
idx = device.index
if idx is None:
idx = current_device()
default_generator = flow.cuda.default_generators[idx]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lightning 适配中发现代码运行到这里会报错,因为 flow.cuda 下并没有 default_generators 😂

return default_generator.get_state()


def get_rng_state_all() -> List[Tensor]:
r"""Returns a list of ByteTensor representing the random number states of all devices."""

results = []
for i in range(device_count()):
results.append(get_rng_state(i))
return results