Reproducibility & Determinism

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Two training runs with the same code can give different numbers for several unrelated reasons: random initialisation and shuffling, non-associative floating-point summation in parallel kernels, GPU algorithms that use atomic operations, background auto-tuning, and different hardware or library versions. PyTorch offers switches to remove most of them, at some cost in speed. This page explains which sources of randomness exist, what each switch controls, how to seed data-loader workers, and where the official guarantees stop. The statistical reason to care (comparing experiments, reporting variance across seeds) is discussed in Experiment Tracking & MLOps and Deep Learning Tuning Playbook.

Examples were run on Python 3.13 with PyTorch 2.15 (CPU) on 2026-10-31.

What can and cannot be reproduced

The official notes state that completely reproducible results are not guaranteed across PyTorch releases, individual commits, or different platforms, and that results may not be reproducible between CPU and GPU executions even with identical seeds. Realistic goals are therefore:

  • Same machine, same software versions, same code: bitwise repeatable runs (needs all the steps below).

  • Different GPUs or library versions: statistically equivalent results (compare across several seeds instead of trusting one).

Record the software versions with the results: torch.__version__, torch.version.cuda, the GPU model and the driver, and the commit of your code (see Installation & Versions).

Seeding the random number generators

Several generators are independent:

Source Seed with

PyTorch (CPU and all CUDA devices)

torch.manual_seed(seed)

Python’s random module

random.seed(seed)

NumPy

np.random.seed(seed) (global state) or an explicit np.random.default_rng(seed)

DataLoader shuffling and worker seeds

the generator argument and a worker_init_fn

Library-specific RNGs (augmentation libraries, Hugging Face set_seed)

their own seed functions

torch.manual_seed seeds the generator for the CPU and for CUDA, so a separate torch.cuda.manual_seed_all call is normally not needed. Reseeding to the same value reproduces the results of operations that draw random numbers.

import random

import numpy as np
import torch


def set_seed(seed: int) -> None:
    random.seed(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)


set_seed(0)
a = torch.randn(3)
set_seed(0)
b = torch.randn(3)
assert torch.equal(a, b)

For code that must not disturb the global state (a data augmentation, a test) use an explicit torch.Generator:

g = torch.Generator(device="cpu").manual_seed(123)
noise = torch.randn(4, generator=g)
perm = torch.randperm(10, generator=g)

The same stream of numbers is not guaranteed between the CPU and a GPU generator, so a seed controls only the device it is applied to.

Deterministic algorithms

Some GPU kernels accumulate results with atomic additions in whatever order threads finish, and since floating-point addition is not associative, the sum differs in the last bits from run to run. Small differences amplify during training. torch.use_deterministic_algorithms(mode, *, warn_only=False) tells PyTorch to use deterministic implementations where they exist and to raise a RuntimeError for operations that are known to be non-deterministic and have no deterministic alternative. With warn_only=True the error becomes a warning, which is a good first step to discover which operations in a model are affected.

The reference lists examples. With the mode on, these operations raise an error: differentiating nn.AvgPool3d on a CUDA tensor, nn.MaxUnpool1d/2d/3d, nn.NLLLoss on a CUDA tensor, torch.histc on CUDA, torch.bincount on CUDA when weights is given, torch.Tensor.put_ with accumulate=False. And these switch to deterministic implementations: convolutions on CUDA (Conv1d/2d/3d and transposes), torch.cumsum on CUDA floating-point tensors, torch.index_add on CUDA, torch.Tensor.scatter_add_ on CUDA, nn.Embedding backward on CUDA, and nn.MaxPool3d backward on CUDA. The lists change between releases; check the reference of your version.

import torch

torch.use_deterministic_algorithms(True)          # raise on non-deterministic ops

# Alternatively, find out which ops are a problem without stopping:
torch.use_deterministic_algorithms(True, warn_only=True)

Scaled dot-product attention deserves a special note: the notes say its fused Flash, Efficient and cuDNN backends are made deterministic only with warn_only=False; with warn_only=True they emit a one-time warning but still run their non-deterministic paths (see Attention, SDPA, FlexAttention & Transformers).

cuBLAS workspace configuration

On CUDA, some cuBLAS operations are only deterministic when the workspace configuration is fixed through an environment variable, and PyTorch raises an error with the mode enabled if it is not set. The variable has the form :[SIZE]:[COUNT] (the CUDA notes describe the format and give :4096:2:16:8 as an example of a total workspace of 2 x 4096 KiB plus 8 x 16 KiB). The values most often given for reproducibility are :4096:8 and :16:8; confirm which your CUDA version requires in the current notes. It must be set before CUDA is initialised, so put it in the launch command or at the top of the script before importing code that touches the GPU.

CUBLAS_WORKSPACE_CONFIG=:4096:8 python train.py

cuDNN flags

Flag Meaning

torch.backends.cudnn.deterministic = True

Makes cuDNN convolution algorithms deterministic. It controls only cuDNN convolutions; use_deterministic_algorithms is broader.

torch.backends.cudnn.benchmark = False

cuDNN picks an algorithm deterministically (possibly slower). With True, PyTorch benchmarks several algorithms on the first call for each new input shape, which may be faster but can select different algorithms on different runs, and is separate from the deterministic flag.

With torch.use_deterministic_algorithms(True) the convolution determinism is already enforced; setting benchmark = False as well removes the run-to-run algorithm selection.

Uninitialised memory

When deterministic mode is on, torch.utils.deterministic.fill_uninitialized_memory (default True) makes operations that return uninitialised memory, such as torch.empty and Tensor.resize_, fill it with a known value, so that code which accidentally reads uninitialised memory becomes repeatable (and visibly wrong). It costs time; set it to False only if your program never uses uninitialised memory as input and you need the speed.

DataLoader workers

Randomness inside data-loading workers is a frequent leak. Each worker receives its own seed derived from the loader’s base seed, and PyTorch seeds its own generator accordingly. NumPy and Python’s random are not seeded in a way you can rely on, and different workers or epochs can produce the same augmentation values or, worse, differing ones between runs. The documented recipe passes a seeded generator to the loader and a worker_init_fn that derives the NumPy and random seeds from torch.initial_seed():

import random

import numpy as np
import torch
from torch.utils.data import DataLoader


def seed_worker(worker_id: int) -> None:
    worker_seed = torch.initial_seed() % 2**32
    np.random.seed(worker_seed)
    random.seed(worker_seed)


g = torch.Generator()
g.manual_seed(0)

loader = DataLoader(
    train_dataset,
    batch_size=64,
    shuffle=True,
    num_workers=4,
    worker_init_fn=seed_worker,
    generator=g,
)

The loader option in_order=False and a changing num_workers both make the order or the random streams depend on timing or worker count, so keep them fixed for reproducible runs. persistent_workers=True carries a worker-side random state across epochs, which is deterministic but different from re-creating workers each epoch. Details of these options are in Workers, Pinned Memory & Samplers. In distributed training, seed each rank (usually seed plus rank for augmentations, the same seed for model initialisation so replicas start identical) and call set_epoch on the DistributedSampler.

A reproducible-run template

import os
import random

import numpy as np
import torch


def make_reproducible(seed: int = 0, strict: bool = True) -> torch.Generator:
    os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8")  # before any CUDA use
    random.seed(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    torch.backends.cudnn.benchmark = False
    torch.backends.cudnn.deterministic = True
    torch.use_deterministic_algorithms(True, warn_only=not strict)
    g = torch.Generator()
    g.manual_seed(seed)
    return g            # pass as generator= to DataLoader


generator = make_reproducible(42, strict=False)
x = torch.randn(1000, 1000)
w = torch.randn(1000, 1000)
assert torch.equal(x @ w, x @ w)     # same inputs, same kernel: bitwise equal on one machine

Run the loop twice and compare losses of the first iterations with torch.equal or by printing them with many digits; if they differ, bisect: disable augmentation, set num_workers=0, then disable torch.compile (torch.compile) and mixed precision (Mixed Precision with torch.amp), whose kernels can also change numerics.

The cost of determinism

Deterministic implementations can be slower, sometimes by a large factor for specific operations, and cudnn.benchmark = False forgoes auto-tuning. Use the strict settings for debugging, regression tests and published results, and the fast settings for large production runs. The related principles for data science projects (fixed seeds in notebooks, pinned environments, recorded data versions) are in Reproducibility & MLOps Basics; hardware and numerical-format effects are in Hardware, Memory & Mixed Precision.

Pitfalls, summarised:

  • Seeding only torch while NumPy-based augmentation keeps its own state.

  • Setting CUBLAS_WORKSPACE_CONFIG after CUDA has been initialised.

  • Treating one lucky seed as evidence: report the mean and spread over several seeds.

  • Expecting identical numbers on CPU and GPU, on another GPU model or after upgrading PyTorch.

  • Comparing a compiled model with an eager one bit for bit; use tolerances (torch.testing.assert_close).

  • Multi-GPU reductions (all-reduce) can depend on the number of devices, so changing the world size changes numerics.