random.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. # mypy: allow-untyped-defs
  2. import contextlib
  3. import warnings
  4. from collections.abc import Generator
  5. import torch
  6. from torch._C import default_generator
  7. def set_rng_state(new_state: torch.Tensor) -> None:
  8. r"""Sets the random number generator state.
  9. .. note:: This function only works for CPU. For CUDA, please use
  10. :func:`torch.manual_seed`, which works for both CPU and CUDA.
  11. Args:
  12. new_state (torch.ByteTensor): The desired state
  13. """
  14. default_generator.set_state(new_state)
  15. def get_rng_state() -> torch.Tensor:
  16. r"""Returns the random number generator state as a `torch.ByteTensor`.
  17. .. note:: The returned state is for the default generator on CPU only.
  18. See also: :func:`torch.random.fork_rng`.
  19. """
  20. return default_generator.get_state()
  21. def manual_seed(seed) -> torch._C.Generator:
  22. r"""Sets the seed for generating random numbers on all devices. Returns a
  23. `torch.Generator` object.
  24. Args:
  25. seed (int): The desired seed. Value must be within the inclusive range
  26. `[-0x8000_0000_0000_0000, 0xffff_ffff_ffff_ffff]`. Otherwise, a RuntimeError
  27. is raised. Negative inputs are remapped to positive values with the formula
  28. `0xffff_ffff_ffff_ffff + seed`.
  29. """
  30. seed = int(seed)
  31. import torch.cuda
  32. if not torch.cuda._is_in_bad_fork():
  33. torch.cuda.manual_seed_all(seed)
  34. import torch.mps
  35. if not torch.mps._is_in_bad_fork():
  36. torch.mps.manual_seed(seed)
  37. import torch.xpu
  38. if not torch.xpu._is_in_bad_fork():
  39. torch.xpu.manual_seed_all(seed)
  40. _seed_custom_device(seed)
  41. return default_generator.manual_seed(seed)
  42. def seed() -> int:
  43. r"""Sets the seed for generating random numbers to a non-deterministic
  44. random number on all devices. Returns a 64 bit number used to seed the RNG.
  45. """
  46. seed = default_generator.seed()
  47. import torch.cuda
  48. if not torch.cuda._is_in_bad_fork():
  49. torch.cuda.manual_seed_all(seed)
  50. import torch.mps
  51. if not torch.mps._is_in_bad_fork():
  52. torch.mps.manual_seed(seed)
  53. import torch.xpu
  54. if not torch.xpu._is_in_bad_fork():
  55. torch.xpu.manual_seed_all(seed)
  56. _seed_custom_device(seed)
  57. return seed
  58. def _seed_custom_device(seed) -> None:
  59. r"""Sets the seed to generate random numbers for custom device.
  60. Args:
  61. seed (int): The desired seed.
  62. See [Note: support the custom device with privateuse1]
  63. """
  64. seed = int(seed)
  65. custom_backend_name = torch._C._get_privateuse1_backend_name()
  66. if hasattr(torch, custom_backend_name):
  67. custom_device_mod = getattr(torch, custom_backend_name)
  68. _bad_fork_name = "_is_in_bad_fork"
  69. _seed_all_name = "manual_seed_all"
  70. if hasattr(custom_device_mod, _bad_fork_name) and hasattr(
  71. custom_device_mod, _seed_all_name
  72. ):
  73. if not getattr(custom_device_mod, _bad_fork_name)():
  74. getattr(custom_device_mod, _seed_all_name)(seed)
  75. else:
  76. message = f"Set seed for `{custom_backend_name}` device does not take effect, please add API's "
  77. message += f"`{_bad_fork_name}` and `{_seed_all_name}` to `{custom_backend_name}` device module."
  78. warnings.warn(message, UserWarning, stacklevel=3)
  79. def initial_seed() -> int:
  80. r"""Returns the initial seed for generating random numbers as a
  81. Python `long`.
  82. .. note:: The returned seed is for the default generator on CPU only.
  83. """
  84. return default_generator.initial_seed()
  85. _fork_rng_warned_already = False
  86. @contextlib.contextmanager
  87. def fork_rng(
  88. devices=None,
  89. enabled=True,
  90. _caller="fork_rng",
  91. _devices_kw="devices",
  92. device_type="cuda",
  93. ) -> Generator:
  94. """
  95. Forks the RNG, so that when you return, the RNG is reset
  96. to the state that it was previously in.
  97. Args:
  98. devices (iterable of Device IDs): devices for which to fork
  99. the RNG. CPU RNG state is always forked. By default, :meth:`fork_rng` operates
  100. on all devices, but will emit a warning if your machine has a lot
  101. of devices, since this function will run very slowly in that case.
  102. If you explicitly specify devices, this warning will be suppressed
  103. enabled (bool): if ``False``, the RNG is not forked. This is a convenience
  104. argument for easily disabling the context manager without having
  105. to delete it and unindent your Python code under it.
  106. device_type (str): device type str, default is `cuda`. As for supported device,
  107. see details in :ref:`accelerator<accelerators>`
  108. """
  109. if device_type == "meta":
  110. yield
  111. return
  112. device_type = torch.device(device_type).type
  113. device_mod = getattr(torch, device_type, None)
  114. if device_mod is None:
  115. raise RuntimeError(
  116. f"torch has no module of `{device_type}`, you should register "
  117. + "a module by `torch._register_device_module`."
  118. )
  119. global _fork_rng_warned_already
  120. # Internal arguments:
  121. # _caller: the function which called fork_rng, which the user used
  122. # _devices_kw: the devices keyword of _caller
  123. if not enabled:
  124. yield
  125. return
  126. if devices is None:
  127. num_devices = device_mod.device_count()
  128. if num_devices > 1 and not _fork_rng_warned_already:
  129. message = (
  130. f"{device_type.upper()} reports that you have {num_devices} available devices, and "
  131. f"you have used {_caller} without explicitly specifying which devices are being used. "
  132. f"For safety, we initialize *every* {device_type.upper()} device by default, which can "
  133. f"be quite slow if you have a lot of {device_type.upper()}s. If you know that you are only"
  134. f" making use of a few {device_type.upper()} devices, set the environment variable "
  135. f"{device_type.upper()}_VISIBLE_DEVICES or the '{_devices_kw}' keyword argument of {_caller} "
  136. "with the set of devices you are actually using. For example, if you are using CPU only, "
  137. "set device.upper()_VISIBLE_DEVICES= or devices=[]; if you are using device 0 only, "
  138. f"set {device_type.upper()}_VISIBLE_DEVICES=0 or devices=[0]. To initialize all devices "
  139. f"and suppress this warning, set the '{_devices_kw}' keyword argument to "
  140. f"`range(torch.{device_type}.device_count())`."
  141. )
  142. warnings.warn(message)
  143. _fork_rng_warned_already = True
  144. devices = list(range(num_devices))
  145. else:
  146. # Protect against user passing us a generator; we need to traverse this
  147. # multiple times but a generator will be exhausted upon first traversal
  148. devices = list(devices)
  149. cpu_rng_state = torch.get_rng_state()
  150. device_rng_states = [device_mod.get_rng_state(device) for device in devices]
  151. try:
  152. yield
  153. finally:
  154. torch.set_rng_state(cpu_rng_state)
  155. for device, device_rng_state in zip(devices, device_rng_states):
  156. device_mod.set_rng_state(device_rng_state, device)