Sub topic 15
Seeds and nondeterministic operations
This chapter assumes you can train a model in PyTorch, know what a lock file and a container image do, and have read the earlier chapters on pinning the environment. A locked environment removes one cause of different results. The program can still behave differently from run to run, because it uses random numbers and because some operations do not return the same bits every time. This chapter covers both.
Two kinds of randomness
Run-to-run variation has two sources:
- Intentional randomness. Weight initialization, data shuffling, dropout and augmentation draw from pseudo-random number generators (PRNGs). A PRNG produces the same sequence from the same seed, so you can control it.
- Accidental nondeterminism. Some operations give slightly different results even with identical inputs and seeds. The usual cause is floating-point addition, which is not associative:
(a + b) + ccan differ froma + (b + c)in the last bits. If a parallel GPU kernel adds numbers in whatever order its threads finish, the sum changes from run to run. Seeds cannot fix this.
Small last-bit differences can grow over thousands of training steps into visibly different metrics. A seed fixes the first kind of variation only. The second kind needs deterministic algorithms, and sometimes a slower code path.
Seeding every generator
A typical ML program uses at least three independent PRNGs: Python's random, NumPy's global generator, and PyTorch's. Seeding one does not affect the others.
import random
import numpy as np
import torch
def seed_everything(seed: int) -> None:
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
seed_everything(42)
torch.use_deterministic_algorithms(True)torch.manual_seed also seeds the CUDA generators on all devices. Call seed_everything once at the start, before you create the model, so initialization is reproducible.
Two details are easy to miss:
PYTHONHASHSEED. Python randomizes string hashing per process, which changes the iteration order of sets and of anything built from them. The variable is read when the interpreter starts, so setting it inside the script is too late. Set it in the Dockerfile withENV PYTHONHASHSEED=0or in the launch command.- Newer NumPy generators. If you use
np.random.default_rng(seed), pass that generator object to the code that needs it. It is not affected bynp.random.seed.
Deterministic mode in PyTorch
torch.use_deterministic_algorithms(True) changes PyTorch's behavior in two ways. It selects deterministic implementations where they exist. Where an operation has no deterministic version, it raises a RuntimeError instead of silently running a nondeterministic kernel. Some scatter and index operations on CUDA are common causes of this error.
On CUDA, cuBLAS matrix multiplication also needs a fixed workspace configuration. Without it, PyTorch raises an error under deterministic mode. Set the variable to :4096:8 (or :16:8) before the first CUDA call.
Related cuDNN flags matter for convolutions:
torch.backends.cudnn.benchmark = Falsestops cuDNN from timing several algorithms and picking the fastest. That choice can differ between runs.torch.backends.cudnn.deterministic = Truerestricts cuDNN to deterministic algorithms.use_deterministic_algorithms(True)already implies this.
Deterministic kernels are often slower. Measure the cost and decide whether you need strict determinism for every run, or only for debugging and for the CI check described in a later chapter.
If you need to find which operations are the problem without stopping the run, use torch.use_deterministic_algorithms(True, warn_only=True). PyTorch then emits a warning instead of raising an error.
Data loading
A DataLoader with num_workers > 0 starts separate processes. Each worker gets its own copy of the Python and NumPy generators, so augmentation code that uses them needs explicit seeding. Shuffling uses a generator that you can pass in directly.
The following script trains a tiny model twice with the same seed and checks that the final weights are identical. It runs on CPU or GPU.
import os
# Must be set before the first CUDA call; harmless on CPU.
os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8")
import random
import numpy as np
import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset
def seed_everything(seed: int) -> None:
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.use_deterministic_algorithms(True)
torch.backends.cudnn.benchmark = False
def seed_worker(worker_id: int) -> None:
worker_seed = torch.initial_seed() % 2**32
np.random.seed(worker_seed)
random.seed(worker_seed)
def train_once(seed: int) -> torch.Tensor:
seed_everything(seed)
device = "cuda" if torch.cuda.is_available() else "cpu"
generator = torch.Generator()
generator.manual_seed(seed)
x = torch.randn(256, 10)
y = torch.randn(256, 1)
loader = DataLoader(
TensorDataset(x, y),
batch_size=32,
shuffle=True,
num_workers=2,
worker_init_fn=seed_worker,
generator=generator,
)
model = nn.Linear(10, 1).to(device)
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
for xb, yb in loader:
xb, yb = xb.to(device), yb.to(device)
optimizer.zero_grad()
loss = nn.functional.mse_loss(model(xb), yb)
loss.backward()
optimizer.step()
return model.weight.detach().cpu().clone()
if __name__ == "__main__":
first = train_once(42)
second = train_once(42)
print("identical:", torch.equal(first, second))Inside a worker, torch.initial_seed() returns a value derived from the base seed and the worker id, so each worker gets a different but repeatable seed. The if __name__ == "__main__" guard is required on platforms that start workers by spawning new processes.
What stays nondeterministic
Even with all of the above, results can differ in these cases:
| Cause | Why it differs | Mitigation |
|---|---|---|
| Different GPU model | Kernels, tile sizes and instruction sets differ between architectures | Record the GPU type; compare only on the same hardware |
| Different CUDA, cuDNN or driver build | Library versions pick different algorithms | Pin the image by digest |
| Different number of GPUs or processes | Gradient reduction order changes in distributed training | Fix the world size for comparisons |
| Mixed precision | Lower precision magnifies rounding differences | Keep the same dtype settings |
| Unversioned data | The input itself changed | Version data alongside the code |
| CPU vs GPU | Different arithmetic implementations | Treat them as separate baselines |
The practical consequence is that "reproducible" has levels. Bitwise identical results are achievable on the same hardware, image and seed. Across different hardware, the realistic target is metrics that agree within a stated tolerance.
Exercise
A training script calls torch.manual_seed(0) and random.seed(0), runs on one GPU in a pinned container, and still gives different final weights on two runs. Name three things you would check or change.
Show answer
Check whether NumPy is seeded (np.random.seed or the passed-in defaultrng), since torch.manualseed does not affect it. Enable torch.usedeterministicalgorithms(True), set CUBLASWORKSPACECONFIG=:4096:8, and set cudnn.benchmark to False so GPU kernels do not vary between runs. Also check DataLoader workers: pass a seeded Generator and a workerinitfn. Setting PYTHONHASHSEED in the container is a further option if set ordering affects the data.
Exercise
Why does setting os.environ["PYTHONHASHSEED"] = "0" at the top of a script not make string hashing deterministic?
Show answer
Python reads PYTHONHASHSEED once, when the interpreter starts. By the time the script runs, the hash seed is already fixed for that process, so the variable must be set in the environment before launch, for example with ENV in the Dockerfile.