Reproducibility: random generators, seeds and determinism
Reproducibility at bitwise and statistical levels: modern pseudorandom generators, PCG64, Philox and SeedSequence; seeding PyTorch training including DataLoader workers; GPU nondeterminism and its control; and reporting results across seeds.
After this lesson you can
- Distinguish portable bitwise, same-environment bitwise and statistical reproducibility and choose the appropriate level.
- Use np.random.Generator and SeedSequence.spawn to create independent streams without global state.
- Seed PyTorch training completely, including DataLoader workers and component generators.
- Identify GPU nondeterminism and enable deterministic mode while measuring its cost.
- Design multi-seed experiments and report variability without selecting the best run.
Before you start
Motivation: the result nobody can repeat
You train a model, obtain 92.8% accuracy and record it. A week later you rerun the same script with the same data and configuration and get 89.2%. You have changed nothing. Which number is “the result”? What if 92.8% was precisely the figure making your idea look better than the baseline?
This is no exaggeration. In this lesson’s lab, a small MLP trained ten times with the same code and ten different seeds gives accuracies between 89.2% and 92.8%: three and a half points of difference without changing a line. In reinforcement learning it is much worse. Henderson et al. (2018) showed that two groups of five seeds for the same algorithm with identical hyperparameters produce average learning curves so far apart they appear to come from different methods. And Bouthillier et al. (2021) measured how much each source of randomness (data split, initialization, augmentation, batch order) contributes to benchmark variance, concluding that one run per method supports almost no comparison.
There are two different problems often mixed together:
- Repeat one run exactly. To debug a failure, compare code versions or resume interrupted training, you need the same configuration to produce the same bits. This requires controlling every random generator and every operation whose result depends on GPU execution order.
- Make a claim others can reproduce. To say “method B is better than A” the conclusion must survive changes of seed, machine or library version. That is achieved not by fixing one seed but by measuring variability among seeds.
This lesson addresses both: what a pseudorandom generator is and how it is split among processes, how to seed real PyTorch training, why GPU results vary between runs and the cost of avoiding it, and how to report a randomness-dependent result honestly.
Three levels of reproducibility
Each level breaks for different reasons, worth knowing before making promises:
| Change | Break level 2? | Why |
|---|---|---|
| Different seed | yes | another experiment: another point in the distribution |
| Different GPU model | yes, generally | a different number of multiprocessors changes reduction distribution; different heuristics choose different kernels |
| Different CUDA, cuDNN or PyTorch version | yes | different algorithms and summation orders |
| Different batch size | yes | changes the calculation itself: different gradients, different number of steps |
cudnn.benchmark = True | yes | convolution algorithm is chosen by timing, and the clock has noise |
| GPU atomic operations | yes | addition order changes each run |
| CPU versus GPU | yes | same operations, different addition order |
Level 1 is almost never attainable with a GPU and is not necessary. Level 2 is an engineering tool: useful for debugging, regression tests and exact resumption in the next lesson. Achieving it requires fixing the environment (the module’s first lesson’s lockfile), seeds and algorithms. Level 3 is the only one that matters for a scientific claim and is achieved not with seeds alone but with multiple runs and statistics.
Pseudorandom generators
Everything random in training, from initialization to dropout, comes from a deterministic generator imitating randomness.
Three immediate consequences. The entire stream is determined by state: two generators in the same state produce the same numbers forever. Because is finite, the state sequence is eventually periodic, with period at most . And seed is not state: it is information from which state is constructed, and how that construction happens matters as much as the generator. These three ideas—state determining stream, period and seed-to-state mapping—are what we call generators and streams. All distribution samples you will see in the course come from transforming these uniform values (the probability integral transform, Box–Muller…).
Linear congruential generators: fast, small and structured
The oldest, simplest generator is the linear congruential generator (LCG):
With , and this is MINSTD, the “minimal standard” proposed by Park and Miller (1988) and still in the C++ standard library as std::minstd_rand0. It is fast and fits in a 32-bit word, but has two structural defects.
Marsaglia (1968) discovered the first: points from any congruential generator fall on a small number of parallel hyperplanes. His paper’s title summarizes it: random numbers fall mainly in the planes. The second affects congruential generators with , the fastest because the modulus is free:
Proof
Since divides , reducing modulo commutes with the recurrence (congruences): . Thus , the low bits, is itself a congruential generator with states, and its period cannot exceed . For with odd, .
∎A generator whose least significant bit alternates is useless if someone uses x % 2 to flip a coin. But a congruential state modulo has excellent high bits, and PCG exploits that.
PCG: a congruential generator with output permutation
O’Neill (2014) proposed the PCG family (permuted congruential generator): the transition is a 64- or 128-bit congruential generator, and output function is a permutation using high state bits to decide how to mix the rest. In PCG32 (64-bit state, 32-bit output), output shifts the state with a xorshift, keeps 32 bits and rotates them by a number of positions given by the state’s top 5 bits. Those high bits have full period, so rotation (one of 32 possibilities) changes from step to step without a short pattern, and output’s low bits inherit the quality of state high bits. The result passes the most demanding statistical batteries (TestU01 BigCrush), occupies 16 bytes and costs one multiplication per number.
np.random.default_rng uses PCG64: 128-bit state, 64-bit output (XSL RR), period , and an odd increment selecting one of streams. It supports advance(n), advancing steps in because composing congruential generators produces another, and jumped(), jumping steps. NumPy also offers PCG64DXSM, a variant with a stronger output function, designed for launching enormous numbers of parallel streams.
Philox: counter-based generators
Salmon et al. (2011) reversed the design: instead of a complicated transition and simple output, use the simplest possible transition, , and put all complexity in output:
where is a bijection keyed by built like a simplified block cipher: ten rounds of multiplications and mixing in Philox4x32-10. State is the pair (counter, key). The consequences are what parallel computation needs: the th number is calculated without generating preceding ones, each GPU thread can use its own counter segment, and different keys give unrelated streams. Philox is the generator of PyTorch CUDA kernels (its state is 16 bytes: seed and offset), one of cuRAND’s generators, and the family, with Threefry, underpins JAX’s explicit generator.
Generator versus global state
NumPy has two interfaces. The legacy one, np.random.seed with np.random.rand and company, stores one global Mersenne Twister (MT19937, 2.5 KB state, period ) shared by the whole process. The modern one, np.random.Generator, is an object with its own state explicitly passed to whoever needs it. The difference is control, not quality:
import numpy as np
# 1. El estado global heredado: un único flujo compartido por todo el programa
np.random.seed(0)
a = np.random.rand(3)
np.random.seed(0)
np.random.shuffle([1, 2, 3]) # una llamada «inocente» en cualquier otro sitio...
b = np.random.rand(3) # ...cambia lo que recibe el resto
print("estado global:", a.round(4), "frente a", b.round(4))
# 2. Generadores explícitos: el estado viaja con el objeto
g = np.random.default_rng(0)
print("default_rng(0):", g.bit_generator.__class__.__name__, g.random(3).round(4))
st = g.bit_generator.state["state"]
print("estado de PCG64: state =", hex(st["state"])[:14] + "...", " inc =", hex(st["inc"])[:14] + "...")
# 3. SeedSequence: una raíz, un árbol de flujos independientes
raiz = np.random.SeedSequence(0)
replicas = raiz.spawn(2)
hijos = replicas[1].spawn(5) # principal y cuatro trabajadores de la réplica 1
print("spawn_key:", hijos[3].spawn_key, " primeros números:", np.random.default_rng(hijos[3]).random(4).round(6))
print("lo mismo, sin recorrer el árbol:", np.random.default_rng(np.random.SeedSequence(0, spawn_key=(1, 3))).random(4).round(6))
print("Generator.spawn:", [round(r.random(), 4) for r in np.random.default_rng(0).spawn(3)])
# 4. Saltos: PCG64 avanza n pasos en O(log n)
p, q = np.random.PCG64(0), np.random.PCG64(0)
q.advance(5)
print("advance(5) = descartar 5 salidas:", np.random.Generator(p).integers(0, 2**63, 6)[5] == np.random.Generator(q).integers(0, 2**63, 1)[0])
# 5. Philox: contador y clave. Cada valor del contador da 4 salidas de 64 bits.
x = np.random.Generator(np.random.Philox(key=7)).random(8)
y = np.random.Generator(np.random.Philox(key=7, counter=1)).random(4)
print("Philox, contador 1 = salidas 4 a 7 del contador 0:", np.allclose(x[4:], y))
print("otra clave, otro flujo:", np.random.Generator(np.random.Philox(key=8)).random(4).round(4))The first line is the global-state problem in miniature: the second vector is the first shifted one position because shuffle consumed a number. In a real program that call might be in a library you update, a debugging print you add, or a function someone calls once more, and a “fixed seed” stops reproducing anything without any failure. With Generator, each component receives its object and only it consumes it. And Philox confirms the counter design’s promise: placing the counter at 1 equals skipping the first four outputs without generating them.
Many streams from one seed
Training has not one generator but a tree: the main process (initialization and shuffling), each DataLoader worker (augmentations), each sweep replica or distributed-training process. All need distinct, repeatable, unrelated streams derived from one seed you can record.
The naive solution is seed + i. It has two defects. The first is bookkeeping: if replica uses seed and its worker uses , replica 0 worker 1 and replica 1 worker 0 share a seed and thus a stream. The second depends on the generator: if seed becomes state without mixing, as in MINSTD, consecutive seeds give consecutive states and “tied” streams. With , a one-line induction (one exercise) shows
a sequence independent of : given one stream, the other is determined. With MINSTD and , term divided by is , so the first outputs of consecutive seeds are almost identical.
The correct solution separates the seed’s two functions: identify the experiment and produce states. np.random.SeedSequence(entropía, spawn_key) passes entropy (the root seed, up to 128 bits or more) and tree path (spawn_key, a tuple of integers) through an avalanche hash, so changing one input bit changes on average half the resulting state bits. spawn(n) creates children with keys (..., 0), …, (..., n-1), and each child can create its own. Resulting states behave like randomly chosen starting points in the generator cycle, allowing overlap risk to be bounded (in PCG64 the seed also fixes increment , so two streams generally do not even traverse the same sequence; a single-cycle model is the standard analysis, also used in NumPy documentation).
Proof
Fix two streams and . Stream shares a state with if and only if its starting point is fewer than positions from in either direction: there are such positions among the cycle’s , and since ‘s point is uniform and independent of , probability is . By the union bound over pairs, probability of any overlap is at most .
∎With PCG64, . An absurd sweep of a million streams consuming numbers each gives a bound of . The real risk lies not in period but seed: if root seeds are selected randomly with only 32 bits, like integers from 0 to accepted by np.random.seed, the birthday paradox makes at least one matching pair expected in a sweep of runs (another exercise). That is why SeedSequence() without arguments takes 128 bits from the operating system, and the right practice is to print SeedSequence().entropy in the experiment log and reuse it.
One nuance visible in the figure: with PCG64, “seed + index” no longer produces tied streams because NumPy passes any integer through SeedSequence before constructing state, so seeds 3 and 4 give unrelated states. What it does not fix is bookkeeping: four of replica 1’s five components still repeat replica 0’s streams, and worker 0 is still a copy of the main process. No statistical test detects this kind of failure, because each stream separately is impeccable.
Implementation from scratch: PCG and a seed mixer
Now PCG32 as O’Neill defines it, a SplitMix64-based seed mixer (the 64-bit finalizer of Steele, Lea and Flood, 2014) and three checks: implementation matches the reference, output is uniform, and consecutive seeds yield unrelated streams when mixed and highly related ones when not.
import numpy as np
M32, M64 = 2**32 - 1, 2**64 - 1
class PCG32:
"""PCG-XSH-RR 64/32 (O'Neill, 2014): congruencial de 64 bits y permutación de salida."""
MULT = 6364136223846793005
def __init__(self, estado_inicial, secuencia=0):
self.inc = ((secuencia << 1) | 1) & M64 # el incremento debe ser impar: elige el flujo
self.estado = 0
self.siguiente()
self.estado = (self.estado + estado_inicial) & M64
self.siguiente()
def siguiente(self):
viejo = self.estado
self.estado = (viejo * self.MULT + self.inc) & M64 # transición: congruencial módulo 2^64
xs = (((viejo >> 18) ^ viejo) >> 27) & M32 # xorshift de los bits altos
rot = viejo >> 59 # los 5 bits más altos eligen la rotación
return ((xs >> rot) | (xs << (-rot & 31))) & M32
def uniforme(self):
return self.siguiente() / 2**32
def splitmix64(x):
"""Mezclador de 64 bits: biyectivo y con avalancha."""
x = (x + 0x9E3779B97F4A7C15) & M64
x = ((x ^ (x >> 30)) * 0xBF58476D1CE4E5B9) & M64
x = ((x ^ (x >> 27)) * 0x94D049BB133111EB) & M64
return x ^ (x >> 31)
def derivar(semilla, *claves):
"""Semilla de un componente a partir de la raíz y de su ruta en el árbol (réplica, trabajador...)."""
h = splitmix64(semilla)
for c in claves:
h = splitmix64(h ^ splitmix64(c))
return h
# 1. Comprobación contra la implementación de referencia (pcg32-demo: estado 42, secuencia 54)
g = PCG32(42, 54)
print("PCG32(42, 54):", [hex(g.siguiente()) for _ in range(4)])
# 2. Uniformidad básica: chi cuadrado con 20 casillas
g = PCG32(derivar(2024))
u = np.array([g.uniforme() for _ in range(100_000)])
obs = np.bincount((u * 20).astype(int), minlength=20)
chi2 = ((obs - 5000) ** 2 / 5000).sum()
print(f"chi cuadrado con 19 grados de libertad: {chi2:.1f} (media 19, desviación típica 6.2)")
# 3. Semillas consecutivas: MINSTD frente a PCG32 con la semilla mezclada
def minstd(semilla, n):
x, out = semilla, []
for _ in range(n):
x = 16807 * x % (2**31 - 1)
out.append(x / (2**31 - 1))
return out
S, n = 1000, 6
U_lcg = np.array([minstd(s, n) for s in range(1, S + 1)])
U_pcg = np.array([[g.uniforme() for _ in range(n)] for g in (PCG32(derivar(s)) for s in range(1, S + 1))])
for nombre, U in (("MINSTD, semilla s ", U_lcg), ("PCG32, derivar(s) ", U_pcg)):
corr = [np.corrcoef(U[:-1, j], U[1:, j])[0, 1] for j in range(n)]
print(nombre, "corr(u_n de s, u_n de s+1), n = 1..6:", np.round(corr, 3))
print("primera salida de MINSTD para s = 1..1000: mínimo", U_lcg[:, 0].min().round(6), " máximo", U_lcg[:, 0].max().round(6))
c2 = 16807**2 % (2**31 - 1) / (2**31 - 1)
print(f"teoría para n = 2: 1 - 6c(1 - c) con c = {c2:.4f}: {1 - 6 * c2 * (1 - c2):.3f}")
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 2, figsize=(8, 2.6), sharey=True)
for a, U, t in ((ax[0], U_lcg, "MINSTD, semillas 1 a 1000"), (ax[1], U_pcg, "PCG32 con semilla mezclada")):
a.hist(U[:, 0], bins=20, range=(0, 1), color="C0")
a.set_title(t, fontsize=10)
a.set_xlabel("primera salida $u_1$")
ax[0].set_ylabel("semillas")
plt.tight_layout()
plt.show()The first four numbers match O’Neill’s reference implementation (0xa15c02b7, 0x7b47f409…), the only serious way to know a hand-written generator is correct: an error in a shift produces numbers that look equally random. Chi-square comes out near 19, expected for uniform output.
The third test is interesting. At each stream position , compare output from seed with seed across a thousand seeds. With MINSTD, correlation at is exactly 1: first outputs are , a straight line, and for the thousand seeds do not exceed (the left histogram has one bar). At , with , and for uniform the correlation between and is exactly , what is measured. With mixed seeds, all correlations are noise of size . The moral is not “do not use congruential generators” but “never convert a seed to a state without mixing”.
Seeding PyTorch training
PyTorch has one generator per device: a Mersenne Twister for CPU and a Philox per GPU. torch.manual_seed(s) seeds them all, and every random operation not given an explicit generator (layer initialization, torch.randn, dropout, RandomSampler without generator) consumes from them. Add the other two global states Python programs often touch unwittingly, random and np.random.
DataLoader workers add the real complication. Every time a DataLoader iterator is created (at each epoch start, except with persistent_workers=True), the main process draws a base_seed from the DataLoader generator or the global one if none was supplied. Reading torch/utils/data/_utils/worker.py source, each worker on startup does:
random.seed(base_seed + worker_id)andtorch.manual_seed(base_seed + worker_id);np.random.seed(...)with state derived from(base_seed, worker_id)using a SeedSequence-like hash (older versions did not seed NumPy, a frequent failure in public code for years);- then your
worker_init_fn(worker_id), if present. Inside the worker,get_worker_info().seedandtorch.initial_seed()equalbase_seed + worker_id.
What PyTorch cannot seed is what it cannot see: a np.random.Generator or random.Random saved as a dataset attribute. The dataset is serialized and copied into each worker with its state, so if the generator was created in __init__ the workers start from identical state and apply identical augmentations to different samples. The remedy is creating the generator inside the worker, in worker_init_fn, from its seed. A Windows and macOS trap, where workers use spawn: worker_init_fn is serialized by name, so it cannot be a lambda or nested function. The clean form is functools.partial over a module-level function, as the next cell does. As in the data lesson, worker code lives in an importable module and the experiment runs in a separate process.
import os, subprocess, sys, tempfile, textwrap, time
from pathlib import Path
DIR = Path(tempfile.gettempdir()) / "atlas_l20"
DIR.mkdir(exist_ok=True)
(DIR / "siembra_l20.py").write_text(textwrap.dedent('''
import functools
import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader, get_worker_info
class AumentaMal(Dataset):
"""El generador se crea en __init__: cada trabajador recibe una copia idéntica."""
def __init__(self, n=8):
self.n = n
self.rng = np.random.default_rng(0)
def __len__(self):
return self.n
def __getitem__(self, i):
return get_worker_info().id, i, round(float(self.rng.uniform(-30, 30)), 2)
class AumentaBien(AumentaMal):
"""El generador lo crea worker_init_fn a partir de la semilla del trabajador."""
def __getitem__(self, i):
return get_worker_info().id, i, round(float(self.rng.uniform(-30, 30)), 2), round(float(np.random.rand()), 4)
def _init(seed, worker_id):
info = get_worker_info()
info.dataset.rng = np.random.default_rng([seed, info.seed % 2**32])
def make_worker_init_fn(seed):
return functools.partial(_init, seed) # serializable por nombre; una lambda no lo es
def epoca(loader):
filas = [tuple(t.item() for t in muestra) for lote in loader for muestra in zip(*lote)]
return sorted(filas, key=lambda f: f[1])
'''), encoding="utf-8")
script = '''
import torch, numpy as np
from torch.utils.data import DataLoader
from siembra_l20 import AumentaMal, AumentaBien, make_worker_init_fn, epoca
if __name__ == "__main__":
print("generador de CPU:", torch.Generator().get_state().numel(), "bytes de estado (MT19937)")
if torch.cuda.is_available():
torch.cuda.init()
print("generador de CUDA:", torch.cuda.default_generators[0].get_state().numel(), "bytes (Philox: semilla y desplazamiento)")
g_init, g_datos = torch.Generator().manual_seed(10), torch.Generator().manual_seed(11)
w = torch.randn(3, generator=g_init)
_ = torch.randperm(5, generator=g_datos) # consumir números de datos no cambia los de la inicialización
print("inicialización con su propio generador:", w, torch.randn(3, generator=torch.Generator().manual_seed(10)))
mal = DataLoader(AumentaMal(), batch_size=2, num_workers=4)
print()
print("generador creado en __init__: (trabajador, índice, ángulo)")
for f in epoca(mal):
print(" ", f)
def cargador(semilla):
return DataLoader(AumentaBien(), batch_size=2, num_workers=4, generator=torch.Generator().manual_seed(semilla),
worker_init_fn=make_worker_init_fn(semilla))
a = cargador(0)
e1, e2 = epoca(a), epoca(a)
print()
print("generador creado en worker_init_fn: (trabajador, índice, ángulo, np.random global)")
for f in e1:
print(" ", f)
print("época 2 distinta de la 1:", [f[2] for f in e1] != [f[2] for f in e2])
b = cargador(0)
print("otro cargador con la misma semilla repite las dos épocas:", epoca(b) == e1 and epoca(b) == e2)
'''
t = time.perf_counter()
r = subprocess.run([sys.executable, "-c", script], cwd=DIR, capture_output=True, text=True, encoding="utf-8",
timeout=300, env={**os.environ, "PYTHONUTF8": "1"})
print(r.stdout if r.returncode == 0 else r.stderr[-2000:])
print(f"({time.perf_counter() - t:.0f} s, casi todo en arrancar los trabajadores)")npm run lab and open the connection link.On the lab machine, CPU generator state occupies 5056 bytes and GPU state 16: the two families above. The dataset with a generator in __init__ gives angles 8.22 and −13.81 in all four workers: identical copies, exactly as in the figure with “same seed”. With the generator created in worker_init_fn, the eight angles differ, global np.random also differs among workers (PyTorch seeds it), the second epoch changes because base_seed changes, and a new loader with the same seed repeats both epochs.
Rule 3 has an even more robust variant: derive each sample’s randomness from (raíz, época, índice), for example with np.random.default_rng([raíz, época, i]) in __getitem__. Then a sample’s augmentation does not depend on which worker processes it, and results are identical with 0, 2 or 8 workers, exactly what one generator per worker loses.
GPU nondeterminism
With all seeds fixed, two runs on the same GPU can still differ. The cause is arithmetic: floating-point addition is not associative. By the standard floating-point model, with ( in float32), and error depends on what is added to what. In float32, because 1 is lost to rounding, whereas .
Proof
Reorder summands so the order is . Computed partial sums satisfy and with . Expanding, , and each product has at most factors. Higham’s classical lemma says if , so each summand has relative error at most and . The second claim follows by the triangle inequality on both orders.
∎The bound is pessimistic worst case; typical error with randomly signed rounding grows as . What matters is the result depends on order, and GPU order is not always fixed. A well-written reduction (torch.sum, mean, matrix multiplication) assigns each thread block a fixed data segment and combines them in a fixed tree: the result is always the same on that GPU, though different from CPU or another GPU with a different distribution (GPU reductions are studied in numerical methods). But scatter operations, like index_add_, scatter_add_ or index_put_(..., accumulate=True), have many threads adding to the same memory location with an atomic operation: addition is indivisible, but thread arrival order is decided by the scheduler each run.
import math
import numpy as np
a, b, c = np.float32(1e8), np.float32(1.0), np.float32(-1e8)
print("(a + b) + c =", (a + b) + c, " a + (b + c) =", a + (b + c), " (a + c) + b =", (a + c) + b)
rng = np.random.default_rng(7)
n = 4096
x = (rng.standard_normal(n) * 10.0 ** (-3 * rng.random(n))).astype(np.float32)
exacto = math.fsum(x.astype(np.float64)) # suma exacta de los float32
ulp = np.spacing(np.float32(exacto))
# Una atómica por elemento = suma secuencial en float32 en el orden en que llegan los hilos
res = np.array([np.cumsum(x[rng.permutation(n)], dtype=np.float32)[-1] for _ in range(300)])
dist = np.round((res.astype(np.float64) - np.float64(np.float32(exacto))) / ulp).astype(int)
print(f"exacto {exacto:.9g} 300 órdenes: {len(np.unique(res))} resultados distintos, de {dist.min()} a {dist.max()} ulp")
# Cota del error de la suma recursiva en cualquier orden: gamma_(n-1) * sum |x_i|
u = 2.0**-24
gamma = (n - 1) * u / (1 - (n - 1) * u)
print(f"cota gamma_(n-1) * sum|x| = {gamma * np.abs(x.astype(np.float64)).sum():.2e} "
f"error máximo observado = {np.abs(res - exacto).max():.2e}")
# Orden fijo: la suma por pares de NumPy (np.sum) da siempre lo mismo, y con menos error
print(f"np.sum (por pares): {np.sum(x):.9g} a {round((np.float64(np.sum(x)) - np.float64(np.float32(exacto))) / ulp)} ulp, "
f"igual en 10 llamadas: {len({np.sum(x).item() for _ in range(10)}) == 1}")Three hundred orders of the same 4096 numbers produce 191 distinct results spanning more than 600 ulps around the exact value: the sum is small compared to because signs cancel, amplifying relative error. Observed error is three orders of magnitude below the bound, as expected. Pairwise summation in np.sum, by contrast, is always the same and substantially more accurate (pairwise summation, with error ).
Do a few ulps matter? That depends on what happens next, as the figure shows.
The training below teaches the essential point. With dynamics are stable: descent contracts perturbations, distance between runs remains at accumulated rounding level (), and all five losses agree in every digit. Between 0.5 and 0.7 distance jumps at some point above and ends between and : final parameters differ, but final losses differ by only a few relative hundredths (up to 8% with ) and all five models have similar quality. Sensitivity does not grow monotonically with (with 0.8 and 0.9 distance returns below ), because it depends on whether the trajectory crosses a loss peak, but from 1, near gradient descent’s stability limit, loss has peaks and dynamics amplify any difference: five runs end with clearly different losses (0.013 to 0.045 with ). Real deep networks train in the sensitive regime. Summers and Dinneen (2021) showed changing a single bit of one initial weight produces, at training’s end, variability between models comparable to changing all randomness sources at once. GPU nondeterminism is therefore not a last-bit detail: after thousands of steps, it is another seed.
Control consists of three switches. torch.use_deterministic_algorithms(True) makes all operations with a deterministic alternative use it (including cuDNN convolutions and CUDA index_add_ and scatter_add_, switching to an implementation without atomics) and those without one raise RuntimeError. torch.backends.cudnn.benchmark = False fixes algorithm selection. And environment variable CUBLAS_WORKSPACE_CONFIG=:4096:8 (or :16:8), set before the first cuBLAS call, is requested by PyTorch’s reproducibility note for CUDA 10.2 or later; in older PyTorch versions deterministic mode raised an error on the first matrix product if absent. The next cell checks the lab version.
import time, warnings
import torch
import torch.nn.functional as F
dev = "cuda"
torch.manual_seed(0)
src = torch.randn(1_000_000, device=dev)
idx = torch.randint(0, 1000, (1_000_000,), device=dev) # mil celdas, unas mil sumas atómicas en cada una
def suma_por_celda():
return torch.zeros(1000, device=dev).index_add_(0, idx, src)
def medir_us(f, reps=50):
for _ in range(5):
f()
torch.cuda.synchronize()
t0 = time.perf_counter()
for _ in range(reps):
f()
torch.cuda.synchronize()
return (time.perf_counter() - t0) / reps * 1e6
for det in (False, True):
torch.use_deterministic_algorithms(det)
salidas = [suma_por_celda() for _ in range(20)]
distintas = len({s.cpu().numpy().tobytes() for s in salidas})
dif = max((s - salidas[0]).abs().max().item() for s in salidas)
print(f"determinista={det!s:5} salidas distintas en 20 ejecuciones: {distintas:2d} "
f"diferencia máxima: {dif:.1e} tiempo: {medir_us(suma_por_celda):6.0f} µs")
torch.use_deterministic_algorithms(False)
# Las reducciones de PyTorch (sum, mean, matmul) ya usan un orden fijo en la GPU...
x = torch.randn(4096, 4096, device=dev)
print("x.sum() en 20 ejecuciones:", len({x.sum().item() for _ in range(20)}), "valor distinto")
# ...pero el orden de la GPU no es el de la CPU: mismos datos, otros bits
print(f"CPU {x.cpu().sum().item():.9g} GPU {x.sum().item():.9g}")
# Operaciones sin versión determinista: error, o aviso con warn_only=True
torch.use_deterministic_algorithms(True)
casos = {
"histc": lambda: torch.histc(x, bins=10),
"adaptive_avg_pool2d (backward)": lambda: F.adaptive_avg_pool2d(torch.randn(1, 3, 9, 9, device=dev, requires_grad=True), 4).sum().backward(),
"matmul (cuBLAS)": lambda: (x @ x)[0, 0].item(),
}
for nombre, f in casos.items():
try:
f()
print(f"{nombre}: sin error")
except RuntimeError as e:
print(f"{nombre}: RuntimeError: {str(e).split(',')[0]}")
torch.use_deterministic_algorithms(True, warn_only=True)
with warnings.catch_warnings(record=True) as avisos:
warnings.simplefilter("always")
torch.histc(x, bins=10)
print("con warn_only=True:", str(avisos[0].message).split(",")[0] if avisos else "sin aviso")
torch.use_deterministic_algorithms(False)
print("cudnn.benchmark =", torch.backends.cudnn.benchmark, " cudnn.deterministic =", torch.backends.cudnn.deterministic)npm run lab and open the connection link.On the lab RTX 4060 (PyTorch 2.11 with CUDA 12.8), 20 index_add_ runs produce 20 distinct results, differing by up to in sums of about a thousand values, and deterministic mode turns them into one at the cost of about ten times longer (just over 0.1 ms to just over 1 ms). x.sum() is stable on GPU but differs from CPU sum starting at the seventh significant digit ( versus ): reproducibility level 2 is per device. histc and adaptive_avg_pool2d backward have no deterministic version and fail; with warn_only=True they only warn, and the program remains nondeterministic for that operation. Matrix multiplication does not fail without CUBLAS_WORKSPACE_CONFIG: this version no longer checks. Setting the variable remains harmless and necessary for older versions.
When an operation raises the error there are three honest options: replace it with a deterministic equivalent (an adaptive_avg_pool2d whose output divides its input is an avg_pool2d with fixed kernel and stride), run only that operation on CPU, or disable the mode around it, accepting and documenting nondeterminism. torch.backends.cudnn.deterministic = True is not a solution: it only affects cuDNN convolutions.
The cost of determinism
Deterministic mode is not free, and its price depends on the model. For index_add_ over a million values the factor is 10, because the deterministic version cannot use atomics and must group contributions per position before adding in fixed order. For the complete lab model, with one such scatter in forward, a training step with data already on GPU costs 30% more: about 2.3 to about 3.0 ms in one lab run. Absolute times change with GPU load (another run gave 3.7 and 4.8 ms), but the ratio remains 1.3. In a model without scatters cost can be almost zero, and in one full of indexing backward operations (huge embeddings, graph networks, point clouds), very high. The only way to know is measure, using the profiling lesson’s benchmarking methodology.
The decision follows the required reproducibility level:
| Situation | Level | Deterministic mode |
|---|---|---|
| Debugging a NaN or intermittent failure | 2 | yes: without it, each run is another program |
| Comparing code versions or bisecting a regression | 2 | yes |
| Regression test of a short training run | 2 | yes |
| Checking exact resumption from checkpoint | 2 | yes |
| Hyperparameter sweep, multiple seeds, final training | 3 | no: pay in time for what you already pay in seeds |
In the final row, GPU nondeterminism is another source of variability, like seed, and the seed distribution is reported. Enabling it there makes the result slower, not more correct.
Lab: bitwise reproducible training
Now bring everything together on a variant of the spiral MLP from the reference training loop: a context block averages each cell’s features in an grid with index_add_, the same scatter as before, and the dataset applies augmentation (small rotation and noise) with one generator per worker. The module applies the complete seeding strategy. The script trains twice without deterministic mode and twice with it, compares losses step by step and a SHA-256 fingerprint of final weights, measures cost per step and runs ten seeds.
import os, subprocess, sys, tempfile, textwrap, time
from pathlib import Path
DIR = Path(tempfile.gettempdir()) / "atlas_l20"
DIR.mkdir(exist_ok=True)
(DIR / "repro_l20.py").write_text(textwrap.dedent('''
import functools, hashlib, math, random, time
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader, get_worker_info
def seed_everything(seed):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed) # CPU y todas las GPU
def _worker_init(seed, worker_id):
info = get_worker_info() # info.seed = base_seed + worker_id
ss = np.random.SeedSequence([seed, info.seed % 2**32])
info.dataset.rng = np.random.default_rng(ss) # un generador propio por trabajador (con persistent_workers, uno para todo el entrenamiento)
random.seed(int(ss.generate_state(1)[0]))
def make_worker_init_fn(seed):
return functools.partial(_worker_init, seed) # serializable: spawn no admite cierres
def make_data(n, seed=1234):
g = np.random.default_rng(seed) # los datos son fijos: no dependen de la semilla del experimento
z = g.standard_normal((n, 2)) * 1.6
r, a = np.hypot(z[:, 0], z[:, 1]), np.arctan2(z[:, 1], z[:, 0])
y = ((r + a / math.pi * 0.9 + 3) % 3).astype(np.int64)
return z.astype(np.float32), y
class Espiral(Dataset):
"""Puntos 2D con aumentación (rotación pequeña y ruido) sorteada en cada acceso."""
def __init__(self, x, y, sigma=0.05):
self.x, self.y, self.sigma = x, y, sigma
self.rng = None # lo crea worker_init_fn; nunca en __init__
def __len__(self):
return len(self.x)
def __getitem__(self, i):
if self.rng is None: # num_workers=0: se deriva del estado global sembrado
self.rng = np.random.default_rng(np.random.randint(2**31))
t, e0, e1 = self.rng.normal(0, 0.1), *self.rng.normal(0, self.sigma, 2)
c, s = math.cos(t), math.sin(t)
x0, x1 = self.x[i]
return np.array([c * x0 - s * x1 + e0, s * x0 + c * x1 + e1], dtype=np.float32), self.y[i]
class CeldaMLP(nn.Module):
"""MLP con contexto local: media de las características de cada celda de una rejilla 8x8, con index_add_."""
def __init__(self, d=128, celdas=8):
super().__init__()
self.celdas = celdas
self.inp = nn.Linear(2, d)
self.mix = nn.Linear(2 * d, d)
self.body = nn.Sequential(nn.GELU(), nn.Linear(d, d), nn.GELU())
self.head = nn.Linear(d, 3)
def forward(self, x):
h = F.gelu(self.inp(x))
q = ((x.clamp(-4, 3.999) + 4) / 8 * self.celdas).long()
celda = q[:, 0] * self.celdas + q[:, 1]
K = self.celdas ** 2
suma = h.new_zeros(K, h.shape[1]).index_add_(0, celda, h) # suma por celda: atómicas en la GPU
cuenta = h.new_zeros(K).index_add_(0, celda, torch.ones_like(h[:, 0]))
ctx = (suma / cuenta.clamp(min=1)[:, None])[celda]
return self.head(self.body(self.mix(torch.cat([h, ctx], 1))))
def huella(model):
h = hashlib.sha256()
for v in model.state_dict().values():
h.update(v.detach().cpu().numpy().tobytes())
return h.hexdigest()[:12]
def entrenar(seed, determinista, epochs=3, workers=2, n=8000, B=128, device="cuda"):
torch.use_deterministic_algorithms(determinista)
torch.backends.cudnn.benchmark = False
seed_everything(seed)
Xtr, ytr = make_data(n)
Xva, yva = make_data(4000, seed=99)
loader = DataLoader(Espiral(Xtr, ytr), batch_size=B, shuffle=True, num_workers=workers,
generator=torch.Generator().manual_seed(seed),
worker_init_fn=make_worker_init_fn(seed), persistent_workers=workers > 0)
model = CeldaMLP().to(device)
opt = torch.optim.AdamW(model.parameters(), lr=3e-3, weight_decay=0.01)
perdidas = []
for ep in range(epochs):
model.train()
for x, y in loader:
x, y = x.to(device, non_blocking=True), y.to(device, non_blocking=True)
loss = F.cross_entropy(model(x), y)
opt.zero_grad(set_to_none=True)
loss.backward()
opt.step()
perdidas.append(loss.detach())
model.eval()
with torch.no_grad():
acc = (model(torch.from_numpy(Xva).to(device)).argmax(1).cpu().numpy() == yva).mean()
torch.use_deterministic_algorithms(False)
return torch.stack(perdidas).cpu().numpy(), huella(model), float(acc)
def coste_paso(determinista, pasos=200, B=4096, device="cuda"):
"""Tiempo medio de un paso de entrenamiento con los datos ya en la GPU (sin DataLoader)."""
torch.use_deterministic_algorithms(determinista)
torch.manual_seed(0)
X, y = make_data(B)
X, y = torch.from_numpy(X).to(device), torch.from_numpy(y).to(device)
model = CeldaMLP().to(device)
opt = torch.optim.AdamW(model.parameters(), lr=1e-3)
def paso():
loss = F.cross_entropy(model(X), y)
opt.zero_grad(set_to_none=True)
loss.backward()
opt.step()
for _ in range(20):
paso()
torch.cuda.synchronize()
t0 = time.perf_counter()
for _ in range(pasos):
paso()
torch.cuda.synchronize()
torch.use_deterministic_algorithms(False)
return (time.perf_counter() - t0) / pasos * 1e3
'''), encoding="utf-8")
script = '''
import numpy as np
from scipy import stats
from repro_l20 import entrenar, coste_paso
if __name__ == "__main__":
for det in (False, True):
(pa, ha, aa), (pb, hb, ab) = entrenar(0, det), entrenar(0, det)
d = np.abs(pa - pb)
primero = int(np.argmax(d > 0)) if d.max() > 0 else None
print(f"determinista={det!s:5} huellas {ha} {hb} pérdidas idénticas: {np.array_equal(pa, pb)} "
f"primer paso distinto: {primero} diferencia máxima: {d.max():.1e} precisión {aa:.4f} {ab:.4f}")
t = [coste_paso(det) for det in (False, True, False, True)]
print(f"paso de entrenamiento: {np.mean(t[0::2]):.2f} ms normal, {np.mean(t[1::2]):.2f} ms determinista "
f"(x{np.mean(t[1::2]) / np.mean(t[0::2]):.2f})")
acc = np.array([entrenar(s, False, workers=0)[2] for s in range(10)])
m, sd = acc.mean(), acc.std(ddof=1)
h = stats.t.ppf(0.975, len(acc) - 1) * sd / np.sqrt(len(acc))
print("diez semillas:", np.round(acc, 4))
print(f"media {m:.4f} desviación típica {sd:.4f} IC 95 % [{m - h:.4f}, {m + h:.4f}] "
f"mejor {acc.max():.4f} peor {acc.min():.4f}")
'''
t = time.perf_counter()
r = subprocess.run([sys.executable, "-c", script], cwd=DIR, capture_output=True, text=True, encoding="utf-8",
timeout=900, env={**os.environ, "PYTHONUTF8": "1"})
print(r.stdout if r.returncode == 0 else r.stderr[-3000:])
print(f"({time.perf_counter() - t:.0f} s)")npm run lab and open the connection link.On the lab machine, output tells the whole story in four lines:
- Without deterministic mode, with complete seeding, the two runs give different fingerprints. Losses begin to differ at some early step, changing between runs (between steps 3 and 20 in the lab, of about 190 total), by millionths. Final accuracy matches: three epochs are insufficient for the difference to become noticeable, but the models are already distinct.
- With deterministic mode, both fingerprints are identical: bitwise reproducibility including two workers and augmentation.
- Cost: a factor of 1.3 per step (about 2.3 versus 3.0 ms in one run; absolute times vary with GPU load, ratio does not).
- Ten seeds: accuracies between 0.892 and 0.928, mean 0.909, standard deviation 0.011 and 95% interval .
The last line matters for any claim about this model and leads to the final section.
Multiple seeds: how many and how to report them
Viewed from outside, a training result is a random variable : seed chooses initialization, data order and augmentations, and GPU adds its own noise. A method does not have “one accuracy”; it has a distribution with mean and standard deviation , and methods are compared through those distributions. That is the idea of multi-seed evaluation: run trials with seeds fixed beforehand (for example ), report all and summarize with an estimate of and uncertainty. Choosing the best is the most common way to cheat unknowingly.
Proof
(1) The variables are exchangeable and, being continuous, tie with probability 0. Each is largest with probability , and the maximum of exceeds exactly when the largest of the is not : probability . (2) with standard normal . The maximum’s distribution function is , whose derivative is , and is its expectation (the largest order statistic; order statistics are studied in probability).
∎With two identical methods, someone comparing the best of runs of theirs with the published baseline figure (one run) “wins” with probability : 80% with , 90% with . The reported figure is inflated by an average : , , . With the lab’s standard deviation, points, the best of 20 seeds promises about two points the method does not have. The figure turns this into frequencies.
The figure separates rules into two groups. “Best of versus 1” and “mean” without interval always declare a winner, so with every verdict is false, and one favoring B occurs and 50% of the time. “Best seed of each” is symmetric but a poor estimator: a sample maximum has high variance, and with and 20 seeds it is right only 75% of the time versus 94% for the mean (both theoretical; the figure with 1000 experiments per point varies by a point or two). The interval rule declares a winner only when the 95% confidence interval of the mean difference excludes 0, and with wrongly favors B 2.5% of the time. Its price is power: with it needs about nine seeds per method to detect improvement half the time, and with and 20 seeds detects it in only 34% of experiments.
A protocol that withstands review:
- Fix seeds before looking: for all methods, declared in configuration. Using the same seeds for all also allows paired comparison when the seed controls the same thing in both methods (data split, for example), reducing difference variance.
- Report all runs: mean, standard deviation, number of seeds and interval , and plot individual points, not only a bar (uncertainty visualization from the matplotlib lesson).
- Choose for the difference you want to detect. With normal approximation, detecting difference at power 0.8 and level 0.05 requires about seeds per method: 16 for , 63 for (sample-size calculation is developed in statistics).
- Do not tune and evaluate with the same seeds. Choosing hyperparameters with seed 0 and reporting seed 0 is best-seed selection under another name: the sweep winner is partly the lucky one. Tune with some seeds and evaluate with others.
- Randomize every source that varies in practice, not initialization alone. Bouthillier et al. (2021) found data splitting often contributes at least as much variance as initialization and ignoring it makes intervals too optimistic.
import numpy as np
from statistics import NormalDist
rng = np.random.default_rng(0)
Z = rng.standard_normal((200_000, 20))
# 1. Lo que vale en promedio «la mejor de k semillas», en desviaciones típicas sobre la media
for k in (1, 2, 5, 20):
print(f"k = {k:2d}: E[max] = mu {Z[:, :k].max(axis=1).mean():+.3f} sigma")
# 2. Mejor de k frente a una ejecución del rival, con dos métodos idénticos: P = k / (k + 1)
for k in (1, 4, 9):
p = (Z[:, :k].max(axis=1) > Z[:, k]).mean()
print(f"k = {k}: B «gana» en el {p:.3f} de los experimentos (k/(k+1) = {k / (k + 1):.3f})")
# 3. Media e intervalo t con 10 semillas (cuantil t de 9 grados de libertad: 2.262)
acc = 0.80 + 0.02 * rng.standard_normal(10)
m, s = acc.mean(), acc.std(ddof=1)
h = 2.262 * s / np.sqrt(len(acc))
print(f"10 semillas: media {m:.4f}, desviación típica {s:.4f}, IC 95 % [{m - h:.4f}, {m + h:.4f}], mejor {acc.max():.4f}")
# 4. Semillas por método para detectar una diferencia delta con potencia 0.8 y alfa 0.05 (aprox. normal)
z = NormalDist().inv_cdf
for d in (1.0, 0.5, 0.25):
n = 2 * (z(0.975) + z(0.8)) ** 2 / d**2
print(f"delta = {d:4} sigma: unas {int(np.ceil(n))} semillas por método")The simulation reproduces both theorem formulas and the power table. The normal approximation falls short by one seed because it ignores that standard deviation is also estimated (exact gives 17 and 64), but the message is unchanged: detecting improvements of half a standard deviation requires dozens of seeds. In reinforcement learning, where is huge, this is the norm rather than exception (variance across seeds); the research module treats variance sources and expected maximum performance as an honest way to report sweeps.
Common mistakes
Exercises
torch.use_deterministic_algorithms(True), cudnn.benchmark = False and a locked environment, obtaining a weight fingerprint. In which scenarios can you expect exactly the same fingerprint? There may be several.More than one answer may be correct.
torch.use_deterministic_algorithms(True) and training stops with RuntimeError: adaptive_avg_pool2d_backward_cuda does not have a deterministic implementation. Which statements are correct? There may be several.More than one answer may be correct.
Step 1 of 4. How do you approach the proof?
seed_everything(seed), which seeds random, NumPy global state and PyTorch, and make_worker_init_fn(seed), which returns a worker_init_fn(worker_id) function for DataLoader. Inside a worker, PyTorch has already done torch.manual_seed(base_seed + worker_id), so torch.initial_seed() equals base_seed + worker_id, and base_seed changes each epoch. Your worker_init_fn must reseed random and np.random with state derived from seed and torch.initial_seed() (using np.random.SeedSequence), so workers have distinct streams even if they inherit identical state, each stream is repeatable, and changes with epoch and seed. It must also be serializable with spawn: no lambda or local function.import random
import numpy as np
import torch
def seed_everything(seed):
"""Siembra Python, NumPy (estado global) y PyTorch (CPU y GPU)."""
random.seed(seed)
# tu código
def make_worker_init_fn(seed):
"""Devuelve worker_init_fn(worker_id), serializable, que da a cada trabajador un flujo propio y repetible."""
return lambda worker_id: NoneSummary
- Three levels: portable bitwise (almost never attainable on GPU), bitwise in the same environment (for debugging, tests and resumption), and statistical (the only one supporting a conclusion).
- A generator is state, transition and output. Congruential generators have structure (planes, short-period low bits); PCG hides it with output permutation, and counter-based Philox permits direct access and parallel keyed streams.
np.random.Generatorreplaces global state. - Experiment streams derive from a root with
SeedSequenceandspawn, never seed plus index. With random starting points overlap risk is at most , negligible with ; the real risk is 32-bit seeds. - In PyTorch:
torch.manual_seed, onetorch.Generatorper component,generator=in DataLoader and dataset generators created inworker_init_fn(serializable) fromget_worker_info().seed. - Floating-point addition depends on order. Atomics in
index_add_,scatter_add_and many backwards, and cuDNN algorithm choice, change results each run; in sensitive training the difference grows into another seed.use_deterministic_algorithms(True)andcudnn.benchmark = Falsecontrol it at a cost to measure (×10 forindex_add_, ×1.3 for the lab step). - With identical methods, best of versus one rival run wins with probability and inflates by . Fix seeds beforehand, report all with mean and interval, and choose for the difference to detect.