Rate this Page

torch.random#

Created On: Aug 07, 2019 | Last Updated On: Jun 18, 2025

torch.random.fork_rng(devices=None,enabled=True,_caller='fork_rng',_devices_kw='devices',device_type='cuda')[source]#

Forks the RNG, so that when you return, the RNG is resetto the state that it was previously in.

Parameters:
  • devices (iterable ofDevice IDs) – devices for which to forkthe RNG. CPU RNG state is always forked. By default,fork_rng() operateson all devices, but will emit a warning if your machine has a lotof devices, since this function will run very slowly in that case.If you explicitly specify devices, this warning will be suppressed

  • enabled (bool) – ifFalse, the RNG is not forked. This is a convenienceargument for easily disabling the context manager without havingto delete it and unindent your Python code under it.

  • device_type (str) – device type str, default iscuda. As for supported device,see details inaccelerator

Return type:

Generator

torch.random.get_rng_state()[source]#

Returns the random number generator state as atorch.ByteTensor.

Note

The returned state is for the default generator on CPU only.

See also:torch.random.fork_rng().

Return type:

Tensor

torch.random.initial_seed()[source]#

Returns the initial seed for generating random numbers as aPythonlong.

Note

The returned seed is for the default generator on CPU only.

Return type:

int

torch.random.manual_seed(seed)[source]#

Sets the seed for generating random numbers on all devices. Returns atorch.Generator object.

Parameters:

seed (int) – The desired seed. Value must be within the inclusive range[-0x8000_0000_0000_0000, 0xffff_ffff_ffff_ffff]. Otherwise, a RuntimeErroris raised. Negative inputs are remapped to positive values with the formula0xffff_ffff_ffff_ffff + seed.

Return type:

Generator

torch.random.seed()[source]#

Sets the seed for generating random numbers to a non-deterministicrandom number on all devices. Returns a 64 bit number used to seed the RNG.

Return type:

int

torch.random.set_rng_state(new_state)[source]#

Sets the random number generator state.

Note

This function only works for CPU. For CUDA, please usetorch.manual_seed(), which works for both CPU and CUDA.

Parameters:

new_state (torch.ByteTensor) – The desired state