.. meta::
   :description: How random number generation works with TorchNeuron on AWS Trainium. Covers the per-device generators, the on-device RNG, seeding, saving and restoring generator state, reproducibility, and which random operations run on the device.
   :keywords: TorchNeuron, torch-neuronx, random number generation, RNG, seed, manual_seed, reproducibility, generator, dropout, AWS Neuron, Trainium
   :date-modified: 2026-10-26

.. _torchneuron-random-number-generation:

====================================
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 and ``torch.compile``
- Trn2 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. The
  ``torch.Generator`` methods (``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()`` and
  ``torch.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.

.. list-table::
   :header-rows: 1
   :widths: 40 60

   * - API
     - Behavior
   * - ``torch.manual_seed(seed)``
     - Seeds the CPU generator and every accessible Neuron generator (through
       ``torch.neuron.manual_seed_all``).
   * - ``torch.neuron.manual_seed(seed)``
     - Seeds the current device's generator and resets its offset to 0.
   * - ``torch.neuron.manual_seed_all(seed)``
     - Seeds every accessible Neuron generator and resets each offset to 0.
   * - ``torch.neuron.seed()``
     - 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`_.
   * - ``torch.neuron.seed_all()``
     - 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`_.
   * - ``torch.neuron.initial_seed()``
     - 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.

.. code-block:: python

   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.

.. code-block:: python

   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_state`` returns a 16-element CPU ``uint8`` tensor: the 8-byte seed,
  then the 8-byte offset.
- ``set_rng_state`` accepts 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
  raises ``RuntimeError``.
- When the (seed, offset) pair differs from the state that ``set_rng_state``
  last applied, it also reseeds the CPU default generator and the on-device
  RNG with ``seed 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.

.. code-block:: python

   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.compile`` produce identical values for the same seed.
- Requesting a ``bfloat16`` or ``float16`` result rounds the same ``float32``
  values 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
:ref:`neuron-rounding-modes` and :ref:`nrt-env-var-reference`.

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
<https://github.com/aws-neuron/torch-neuronx/blob/main/docs/torch_api_compatibility.md>`__.
Summary at the time of writing, for eager mode:

.. list-table::
   :header-rows: 1
   :widths: 50 50

   * - Runs on the device
     - Falls back to the CPU
   * - ``torch.rand``, ``rand_like``, ``randn``, ``randn_like``, ``randint``
       and ``randint_like`` (non-``int64`` output), ``Tensor.uniform_``,
       ``Tensor.normal_`` (scalar mean and std), ``Tensor.random_``,
       ``torch.nn.Dropout``
     - ``torch.bernoulli``, ``multinomial``, ``normal`` (tensor mean or std),
       ``poisson``, ``randperm``, ``randint`` with ``int64`` output,
       ``Dropout1d``, ``Dropout2d``, ``Dropout3d``, ``AlphaDropout``,
       ``FeatureAlphaDropout`` (training mode)

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 to ``rand``, ``randn``, ``randint``,
  ``Tensor.uniform_``, ``Tensor.normal_`` or ``Tensor.random_`` on a Neuron
  tensor raises ``RuntimeError``. Call the operation without the ``generator``
  argument, 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 + rank`` can
  give each rank almost the same mask.
- **Seeding before the runtime is initialized.** In a single-process script,
  if you call ``torch.manual_seed()`` or ``torch.neuron.manual_seed()`` before
  the Neuron runtime is initialized, the on-device RNG ignores that seed. Call
  ``torch.neuron.init()`` before seeding. Distributed scripts that create the
  process group with ``torch.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()`` or
  ``torch.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, call ``torch.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; ``int64`` outputs fall back to the CPU.

Related topics
----------------------------------------

- :ref:`torchneuron-torch-neuron-module-ref`: signatures and return values of
  the ``torch.neuron`` RNG functions
- :doc:`/torch/reference/api/index`
- :ref:`neuron-rounding-modes`
- :ref:`nrt-env-var-reference`
- :doc:`/torch/about-pytorch-neuron`
