This document is relevant for: Trn2, Trn3
Random number generation#
This page explains how torch-neuronx generates random numbers, which
seeding and state APIs are available in the torch.neuron namespace, and
what reproducibility you can expect from random operations that run on the
device.
Applies to#
torch-neuronx(native TorchNeuron), eager mode andtorch.compileTrn2 and Trn3 Trainium instances
How random number generation works#
torch-neuronx keeps random number state in two places:
Neuron generators. Each Neuron device has a default
torch.Generator. Its state is 16 bytes: an 8-byte seed followed by an 8-byte offset. Thetorch.Generatormethods (manual_seed,seed,initial_seed,get_state,set_state) work on it and run on the host only.On-device RNG. Random values for operations that run on the device come from a NKI kernel on the GPSIMD engine.
torch.neuron.manual_seed()andtorch.neuron.manual_seed_all()also update the on-device RNG state on the current Neuron device.
A default generator is created the first time it is requested. A generator that you have not seeded explicitly starts from a nondeterministic seed.
The number of per-device generators is fixed the first time one is accessed.
torch.neuron.manual_seed_all() and torch.neuron.seed_all() iterate
over that fixed set, which can differ from a later
torch.neuron.device_count().
Seeding#
torch.manual_seed() seeds the CPU generator and every accessible Neuron
generator. The torch.neuron namespace gives you device-level control.
API |
Behavior |
|---|---|
|
Seeds the CPU generator and every accessible Neuron generator (through
|
|
Seeds the current device’s generator and resets its offset to 0. |
|
Seeds every accessible Neuron generator and resets each offset to 0. |
|
Assigns a nondeterministic seed to the current device’s generator and resets its offset to 0. Does not reseed the on-device RNG. See Limitations. |
|
The first generator produces a nondeterministic seed, which is copied to every other accessible generator; every offset is reset to 0. Does not reseed the on-device RNG. See Limitations. |
|
Returns the initial seed of the current Neuron device generator. |
torch.seed() assigns a nondeterministic seed to the CPU generator and
copies it to every accessible Neuron generator and the on-device RNG.
torch.initial_seed() reads the CPU generator only.
import torch
import torch_neuronx
torch.manual_seed(42) # CPU + all Neuron generators
x = torch.rand(4, 4, device="neuron")
torch.neuron.manual_seed(7) # current Neuron device only
print(torch.neuron.initial_seed()) # 7
In a single-process script, a seed that you set before the Neuron runtime is initialized does not reach the on-device RNG. See Limitations.
Saving and restoring generator state#
Use the torch.neuron functions. The generic torch.get_rng_state() and
torch.set_rng_state() read and write the CPU generator only.
state = torch.neuron.get_rng_state() # 16-element CPU uint8 tensor
# ... run random operations ...
torch.neuron.set_rng_state(state) # restore
# a specific device
state0 = torch.neuron.get_rng_state(device=0)
torch.neuron.set_rng_state(state0, device="neuron:0")
get_rng_statereturns a 16-element CPUuint8tensor: the 8-byte seed, then the 8-byte offset.set_rng_stateaccepts a 16-byte seed-and-offset state or an 8-byte seed-only state. An 8-byte state resets the offset to 0. Any other length raisesRuntimeError.When the (seed, offset) pair differs from the state that
set_rng_statelast applied, it also reseeds the CPU default generator and the on-device RNG withseed XOR offset. Operations that run on the device then restart their stream from that seed instead of continuing the earlier stream, and operations that fall back to the CPU draw from the reseeded CPU generator. Restoring the same state a second time skips both reseeds, so neither on-device values nor CPU fallback values repeat. See Limitations.
Forking generator state#
torch.random.fork_rng() works with Neuron devices. On PyTorch 2.12 and
earlier, fork_rng defaults device_type to "cuda"; torch-neuronx
patches it at import to infer the device type from the devices argument.
PyTorch 2.13 and later infer the device type natively and the patch does
nothing.
with torch.random.fork_rng(devices=["neuron:0"]):
noise = torch.randn(8, device="neuron") # generator state is restored on exit
fork_rng restores the generator state on exit through
torch.neuron.set_rng_state(), so forking from the same state more than
once does not rewind the on-device RNG. See Limitations.
Reproducibility#
The on-device RNG guarantees the following:
The same seed and the same number of elements produce identical values, run to run and process to process.
Eager mode and
torch.compileproduce identical values for the same seed.Requesting a
bfloat16orfloat16result rounds the samefloat32values element by element; it does not draw a different sequence. For a uniform draw, a value that would round up to the upper bound of the range is clamped just below it.
A draw produces its values in a flat order and then takes the requested shape,
so drawing shape (N,) and reshaping it to (A, B) gives the same values
as drawing (A, B) directly. The values depend on the total number of
elements, though: the first 100 values of a 200-element draw are not the same
as a 100-element draw. The same seed does not give the same values on Neuron
and on CPU.
Different seeds give different values, but seeds that are close together give strongly correlated values. See Limitations.
Stochastic rounding uses its own RNG in the Neuron runtime, not the
generators described on this page. NEURON_RT_STOCHASTIC_ROUNDING_EN
enables it and NEURON_RT_STOCHASTIC_ROUNDING_SEED seeds the stochastic
rounding RNG, making an otherwise nondeterministic run reproducible. See
Neuron Rounding Modes and Reference: Neuron Runtime environment variables.
Dropout#
torch.nn.Dropout and torch.nn.functional.dropout build the mask on the
device from the on-device RNG, so they follow the seed you set.
In eager mode, Dropout1d, Dropout2d, Dropout3d, AlphaDropout
and FeatureAlphaDropout draw their mask on the CPU in training mode (the
bernoulli_ call falls back); the rest of the operation runs on the device.
Under torch.compile, Dropout1d, Dropout2d and Dropout3d draw
the mask on the device.
Supported random operations#
Which operations run on the device and which fall back to the CPU is tracked in the operator compatibility table. Summary at the time of writing, for eager mode:
Runs on the device |
Falls back to the CPU |
|---|---|
|
|
Under torch.compile, torch.bernoulli, multinomial, and normal
with a tensor mean or std also run on the device.
Operations that fall back to the CPU use the CPU generator. Because
torch.manual_seed() and torch.neuron.set_rng_state() both update the
CPU generator, fallback operations are still reproducible, but their values
differ from what the on-device RNG would produce. The exception is restoring
the same state more than once, which skips the CPU reseed. See Limitations.
Limitations#
A custom Neuron generator is unsupported for on-device operations. Passing a
generator=argument torand,randn,randint,Tensor.uniform_,Tensor.normal_orTensor.random_on a Neuron tensor raisesRuntimeError. Call the operation without thegeneratorargument, or seed the default generator instead.Fixed generator count. See How random number generation works.
Nearby seeds give correlated values. Numerically close seeds (for example, 0, 1, 2 or 1000) produce strongly correlated values on the device. A small draw, such as a dropout mask with a few hundred elements, can be nearly identical across such seeds, so seeds derived as
base + rankcan give each rank almost the same mask.Seeding before the runtime is initialized. In a single-process script, if you call
torch.manual_seed()ortorch.neuron.manual_seed()before the Neuron runtime is initialized, the on-device RNG ignores that seed. Calltorch.neuron.init()before seeding. Distributed scripts that create the process group withtorch.distributed.init_process_group()before using the device are not affected.torch.neuron.seed() and torch.neuron.seed_all() do not reseed the on-device RNG. They reseed the host generators only, so operations that run on the device continue from the previous on-device RNG state. To reseed the on-device RNG, call
torch.neuron.manual_seed()ortorch.neuron.manual_seed_all().Restoring the same state more than once.
torch.neuron.set_rng_state()reseeds the CPU default generator and the on-device RNG only when the seed and offset differ from the state it last applied. Operations that run on the device do not advance the generator offset, so restoring a saved state a second time skips both reseeds. The on-device RNG is not rewound and the CPU generator is not reseeded, so the values that follow, both on the device and from operations that fall back to the CPU, differ from the values that followed the first restore. For on-device values,torch.random.fork_rng()is affected in the same way. To repeat values, calltorch.manual_seed()with the same seed before each run. It reseeds the CPU generator, every Neuron generator and the on-device RNG, so operations that fall back to the CPU repeat too.Integer ranges.
Tensor.random_bounds are clamped to the signed 32-bit range on the device;int64outputs fall back to the CPU.