Sub topic 15
Seeds and nondeterministic operations
Assume you know basic Python, can run a PyTorch training script, and understand that a random seed is an input to a pseudorandom number generator. This chapter focuses on PyTorch, but the same ideas apply to other ML frameworks.
A seed makes a pseudorandom sequence repeatable. It does not make every operation deterministic. Reproducibility requires controlling several sources of variation:
| Source | Example | Typical control |
|---|---|---|
| Python | Random data split | `random.seed()` |
| NumPy | Random augmentation | `numpy.random.seed()` |
| PyTorch | Parameter initialization | `torch.manual_seed()` |
| Data loading | Worker-specific shuffling | A seeded `Generator` |
| GPU kernels | Parallel reduction order | Deterministic algorithms |
| Process environment | Hash iteration order | `PYTHONHASHSEED` |
Seed every generator
Set environment variables that affect process startup before importing libraries. Then seed each random-number generator used by the program.
import os
# Set this before starting Python for complete process-level control.
# In a shell: PYTHONHASHSEED=42 python train.py
os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8")
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)
torch.cuda.manual_seed_all(seed)
seed_everything(42)
torch.use_deterministic_algorithms(True)
# cuDNN may otherwise select different convolution algorithms.
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True
print(torch.rand(3))torch.use_deterministic_algorithms(True) asks PyTorch to raise an error when it encounters an operation without a deterministic implementation. This is useful in tests and reproducibility checks because silent variation becomes an explicit failure.
DataLoader workers need care. Each worker is a separate process and can have its own random state. Pass a seeded generator to the loader and initialize NumPy and Python using the worker's PyTorch seed.
def seed_worker(worker_id: int) -> None:
worker_seed = torch.initial_seed() % (2**32)
np.random.seed(worker_seed)
random.seed(worker_seed)
loader_generator = torch.Generator()
loader_generator.manual_seed(42)
loader = torch.utils.data.DataLoader(
dataset,
batch_size=32,
shuffle=True,
num_workers=2,
worker_init_fn=seed_worker,
generator=loader_generator,
)What can still vary
Deterministic mode does not guarantee identical results across every machine, PyTorch version, GPU model, or driver. Some operations have no deterministic implementation. Distributed training can also vary because the order and timing of collective operations affect floating-point rounding.
Floating-point addition is not perfectly associative. For example, (a + b) + c can differ slightly from a + (b + c). Parallel GPU reductions may choose different orders, producing small changes that can accumulate during training.
Determinism also has a cost. Deterministic kernels can be slower, use more memory, or fail when an operation is unsupported. Use strict deterministic mode for debugging, regression tests, and controlled experiments. For production training, document whether exact repetition is required or whether a numerical tolerance is sufficient.
Exercise
Why can two runs with the same seed still produce different model weights?
Show answer
The seed controls pseudorandom generators, but nondeterministic GPU kernels, worker behavior, floating-point reduction order, software versions, hardware, or data differences can still change the computation.