Module contents
Lesson 20 of 24Core 80 min

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:

ChangeBreak level 2?Why
Different seedyesanother experiment: another point in the distribution
Different GPU modelyes, generallya different number of multiprocessors changes reduction distribution; different heuristics choose different kernels
Different CUDA, cuDNN or PyTorch versionyesdifferent algorithms and summation orders
Different batch sizeyeschanges the calculation itself: different gradients, different number of steps
cudnn.benchmark = Trueyesconvolution algorithm is chosen by timing, and the clock has noise
GPU atomic operationsyesaddition order changes each run
CPU versus GPUyessame 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 SS is finite, the state sequence is eventually periodic, with period at most ∣S∣\abs{S}. 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):

xn+1=(a xn+c) mod m,un=xn/m.x_{n+1} = (a\,x_n + c) \bmod m, \qquad u_n = x_n / m.

With m=231−1m = 2^{31} - 1, a=16807a = 16807 and c=0c = 0 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 (un,un+1,…,un+d−1)(u_n, u_{n+1}, \dots, u_{n+d-1}) 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 m=2km = 2^k, the fastest because the modulus is free:

Proof

Since 2j2^j divides 2k2^k, reducing modulo 2j2^j commutes with the recurrence (congruences): xn+1≡a xn+c(mod2j)x_{n+1} \equiv a\,x_n + c \pmod{2^j}. Thus yn=xn mod 2jy_n = x_n \bmod 2^j, the low jj bits, is itself a congruential generator with 2j2^j states, and its period cannot exceed 2j2^j. For j=1j = 1 with a,ca, c odd, yn+1≡yn+1(mod2)y_{n+1} \equiv y_n + 1 \pmod 2.

∎

A generator whose least significant bit alternates is useless if someone uses x % 2 to flip a coin. But a congruential state modulo 2642^{64} 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 gg 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 21282^{128}, and an odd increment cc selecting one of 21272^{127} streams. It supports advance(n), advancing nn steps in O(log⁡n)\bigO(\log n) because composing congruential generators produces another, and jumped(), jumping (φ−1)⋅2128(\varphi - 1) \cdot 2^{128} 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, sn+1=sn+1s_{n+1} = s_n + 1, and put all complexity in output:

un=gk(n),u_n = g_k(n),

where gkg_k is a bijection keyed by kk 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 nnth 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 219937−12^{19937} - 1) 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:

[ ]Global state, Generator, SeedSequence and PhiloxBrowser
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 rr uses seed rr and its worker ww uses r+wr + w, 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 x0′=x0+dx'_0 = x_0 + d, a one-line induction (one exercise) shows

xn′−xn≡and(modm),x'_n - x_n \equiv a^n d \pmod m,

a sequence independent of x0x_0: given one stream, the other is determined. With MINSTD and d=1d = 1, term n=1n = 1 divided by mm is 16807/m≈7.8⋅10−616807/m \approx 7.8 \cdot 10^{-6}, 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 nn 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 cc, 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 ii and jj. Stream jj shares a state with ii if and only if its starting point is fewer than LL positions from ii in either direction: there are 2L−12L - 1 such positions among the cycle’s PP, and since jj‘s point is uniform and independent of ii, probability is (2L−1)/P(2L - 1)/P. By the union bound over n(n−1)/2n(n-1)/2 pairs, probability of any overlap is at most n(n−1)2⋅2L−1P<n(n−1)LP\frac{n(n-1)}{2} \cdot \frac{2L-1}{P} < \frac{n(n-1)L}{P}.

∎

With PCG64, P=2128P = 2^{128}. An absurd sweep of a million streams consuming 240≈10122^{40} \approx 10^{12} numbers each gives a bound of 1012⋅240/2128≈3⋅10−1510^{12} \cdot 2^{40}/2^{128} \approx 3 \cdot 10^{-15}. The real risk lies not in period but seed: if root seeds are selected randomly with only 32 bits, like integers from 0 to 232−12^{32} - 1 accepted by np.random.seed, the birthday paradox makes at least one matching pair expected in a sweep of 10510^5 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.

InteractiveThe seed tree
replica 0: seed 0
main= stream A
seed 0
0 1 5 3 4 2
worker 0= stream A
seed 0
worker 1= stream B
seed 1
worker 2= stream C
seed 2
worker 3= stream D
seed 3
replica 1: seed 1
main= stream B
seed 1
0 4 1 5 2 3
worker 0= stream B
seed 1
worker 1= stream C
seed 2
worker 2= stream D
seed 3
worker 3u₁ nearly equal
seed 4
fingerprint: first 12 numbers, from 0 to 1main: order of first 6 samples · workers: three augmentations (rotation and flip)
Difference between two streams, (un′−un) mod 1(u'_n - u_n) \bmod 1
00.51110203040
root seed 0root seed 17
The difference does not depend on the root: the streams are tied.
Seeding strategy
Generator
0
Distinct streams5 of 10
Pairs with the same stream6
Pairs with nearly equal u1u_1 (∣Δ∣<10−4|\Delta| < 10^{-4})39
Seed plus index: worker 0 repeats the main stream, and in replica 1, 4 of its 5 components repeat a stream from replica 0, shifted one position.
Two replicas of an experiment, each with a main process and four DataLoader workers. Each row shows its stream fingerprint (first twelve numbers in color) and, for workers, the first three glyph augmentations (rotation and flip); the main process shows its first six samples' order. Rows with the same stream carry the same color label. Start with ‘seed + index’ and MINSTD: find the worker repeating the main process and streams replica 1 reuses from 0, and notice the first augmentation is almost the same throughout. Below, difference between two streams: filled and hollow points use two root seeds and coincide, because the difference is and mod ma^n d \bmod m. Switch to ‘Same seed’, then PCG64 and finally SeedSequence.spawn. With PCG64 and spawn, numbers are exactly NumPy's: hover over replica 1 worker 2's fingerprint with root 0 and compare with the previous cell.

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.

[ ]PCG32 and a seed mixer from scratchBrowser
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 nn, compare output from seed ss with seed s+1s + 1 across a thousand seeds. With MINSTD, correlation at n=1n = 1 is exactly 1: first outputs are 16807 s/m16807\,s/m, a straight line, and for the thousand seeds do not exceed 0.00780.0078 (the left histogram has one bar). At n=2n = 2, u2′=(u2+c) mod 1u'_2 = (u_2 + c) \bmod 1 with c=168072 mod m/m≈0.1315c = 16807^2 \bmod m / m \approx 0.1315, and for uniform UU the correlation between UU and (U+c) mod 1(U + c) \bmod 1 is exactly 1−6c(1−c)≈0.3151 - 6c(1 - c) \approx 0.315, what is measured. With mixed seeds, all correlations are noise of size 1/1000≈0.031/\sqrt{1000} \approx 0.03. 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) and torch.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().seed and torch.initial_seed() equal base_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 WW 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.

[ ]PyTorch generators, workers and the __init__ trapLocal GPU
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)")
This cell needs the local lab (PyTorch with your GPU). Start it with 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, fl⁡(a+b)=(a+b)(1+δ)\operatorname{fl}(a + b) = (a + b)(1 + \delta) with ∣δ∣≤u\abs{\delta} \le u (u=2−24u = 2^{-24} in float32), and error depends on what is added to what. In float32, (108+1)−108=0(10^8 + 1) - 10^8 = 0 because 1 is lost to rounding, whereas (108−108)+1=1(10^8 - 10^8) + 1 = 1.

Proof

Reorder summands so the order is x1,…,xnx_1, \dots, x_n. Computed partial sums satisfy s^1=x1\hat{s}_1 = x_1 and s^k=(s^k−1+xk)(1+δk)\hat{s}_k = (\hat{s}_{k-1} + x_k)(1 + \delta_k) with ∣δk∣≤u\abs{\delta_k} \le u. Expanding, S^=∑ixi∏k=max⁡(i,2)n(1+δk)\hat{S} = \sum_i x_i \prod_{k = \max(i, 2)}^{n} (1 + \delta_k), and each product has at most n−1n - 1 factors. Higham’s classical lemma says ∣∏k=1m(1+δk)−1∣≤γm\abs{\prod_{k=1}^{m}(1 + \delta_k) - 1} \le \gamma_m if mu<1mu < 1, so each summand has relative error at most γn−1\gamma_{n-1} and ∣S^−S∣≤γn−1∑i∣xi∣\abs{\hat{S} - S} \le \gamma_{n-1}\sum_i\abs{x_i}. 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 n u\sqrt{n}\,u. 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.

[ ]Float32 summation depends on orderBrowser
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 ∑∣xi∣\sum\abs{x_i} 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 O(ulog⁡n)\bigO(u\log n)).

Do a few ulps matter? That depends on what happens next, as the figure shows.

InteractiveThe changing sum
Atomic sum of N=4096N = 4096 float32 values: each point is a run, in ulps relative to the rounded exact value
−52−260+26+52
1
1
0
0
0
0
0
1
0
0
0
1
0
1
1
1
0
0
1
0
1
1
1
0
0
0
1
1
1
1
0
1
sexponentmantissa: highlighted bits differ from the first run
Fixed-order cost measured on the lab RTX 4060: index_add_ with one million values takes about ten times longer (from just over 0.1 ms to just over 1 ms); the lab training step takes 1.3 times longer (about 2.3 to 3.0 ms).
Relative parameter distance from the fixed-order run
  • run 1
  • run 2
  • run 3
  • run 4
Loss for the five training runs
  • fixed order
  • run 1
  • run 2
  • run 3
  • run 4
4096
1.05
Latest result−9.44878864
Runs24
Distinct results21
Spread−47 to +22 ulp
Maximum relative error4.7·10⁻⁶
Final parameter distanceup to 7.2·10⁻²
Final loss of all five0.0130 to 0.0447
The difference in final bits has grown enough to change training outcomes: same seed, five different models.
Above, NN simulated threads add NN float32 values with one atomic operation each, in a different order each run. Each dot is a run positioned in ulps relative to the rounded exact value; the ring marks the last and its 32 bits appear below with those differing from the first run highlighted. Press ‘Run’ repeatedly, raise NN and enable deterministic mode (fixed-order tree sum). Below, five identical training runs of a 2-16-1 MLP by gradient descent, whose gradient is the float32 sum of 64 example gradients: one with fixed order (dashed) and four with each run's order. Start with η=1.05\eta = 1.05: the 10−810^{-8} difference in the first step grows until final loss changes. Lower η\eta to 0.6 then 0.3: how far does the difference grow in each case?

The training below teaches the essential point. With η≤0.45\eta \le 0.45 dynamics are stable: descent contracts perturbations, distance between runs remains at accumulated rounding level (10−710^{-7}), and all five losses agree in every digit. Between 0.5 and 0.7 distance jumps at some point above 10−210^{-2} and ends between 10−410^{-4} and 10−210^{-2}: final parameters differ, but final losses differ by only a few relative hundredths (up to 8% with η=0.6\eta = 0.6) and all five models have similar quality. Sensitivity does not grow monotonically with η\eta (with 0.8 and 0.9 distance returns below 10−510^{-5}), 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 η=1.05\eta = 1.05). 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.

[ ]GPU nondeterminism and deterministic modeLocal GPU
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)
This cell needs the local lab (PyTorch with your GPU). Start it with 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 10−410^{-4} 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 (−4025.405-4025.405 versus −4025.408-4025.408): 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:

SituationLevelDeterministic mode
Debugging a NaN or intermittent failure2yes: without it, each run is another program
Comparing code versions or bisecting a regression2yes
Regression test of a short training run2yes
Checking exact resumption from checkpoint2yes
Hyperparameter sweep, multiple seeds, final training3no: 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 8×88 \times 8 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.

[ ]Lab: complete seeding, deterministic mode and ten seedsLocal GPU
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)")
This cell needs the local lab (PyTorch with your GPU). Start it with 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 [0.902,0.917][0.902, 0.917].

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 RR: 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 μ\mu and standard deviation σ\sigma, and methods are compared through those distributions. That is the idea of multi-seed evaluation: run kk trials with seeds fixed beforehand (for example 0,…,k−10, \dots, k-1), report all and summarize with an estimate of μ\mu and uncertainty. Choosing the best is the most common way to cheat unknowingly.

Proof

(1) The k+1k + 1 variables are exchangeable and, being continuous, tie with probability 0. Each is largest with probability 1/(k+1)1/(k+1), and the maximum of X1,…,XkX_1, \dots, X_k exceeds X0X_0 exactly when the largest of the k+1k + 1 is not X0X_0: probability 1−1/(k+1)1 - 1/(k+1). (2) max⁡iXi=μ+σmax⁡iZi\max_i X_i = \mu + \sigma\max_i Z_i with standard normal ZiZ_i. The maximum’s distribution function is P(max⁡iZi≤x)=Φ(x)k\Pr(\max_i Z_i \le x) = \Phi(x)^k, whose derivative is k φ(x) Φ(x)k−1k\,\varphi(x)\,\Phi(x)^{k-1}, and eke_k is its expectation (the largest order statistic; order statistics are studied in probability).

∎

With two identical methods, someone comparing the best of kk runs of theirs with the published baseline figure (one run) “wins” with probability k/(k+1)k/(k+1): 80% with k=4k = 4, 90% with k=9k = 9. The reported figure is inflated by an average ek σe_k\,\sigma: e2=0.564e_2 = 0.564, e5=1.163e_5 = 1.163, e20=1.867e_{20} = 1.867. With the lab’s standard deviation, σ≈1.1\sigma \approx 1.1 points, the best of 20 seeds promises about two points the method does not have. The figure turns this into frequencies.

InteractiveThe seed lottery
One experiment: accuracy per seed (ground truth: A ∼N(80,22)\sim \mathcal{N}(80, 2^2), B with δ=0.0\delta = 0.0 more points)
72 %76 %80 %84 %88 %92 %A: 1 runB: 5 seeds
Frequency of declaring B the winner by kk (1000 experiments per point)
  • k/(k+1)
  • best of k vs one
  • best seed
  • mean
  • mean with 95% CI
Reporting rule
5
0.0 σ
Reported for A80.4 %
Reported for B80.8 %
Verdict for this experimentB wins by 0.4 points
B declared winner in 1000 experiments83.3 %
Both methods have identical distributions, yet this rule declares B the winner in 83% of experiments.
Two methods A and B with accuracy per seed N(80 %,22)\Normal(80\,\%, 2^2); B adds real improvement δ\delta, measured in standard deviations (δ=1\delta = 1 is 2 points). Above, one experiment with kk seeds per method and what the chosen rule reports: rings for best seed, vertical bar for mean, 95% interval for the last rule. Below, in 1000 experiments for each kk, frequency with which each rule declares B the winner. Start with δ=0\delta = 0, identical methods, and the common paper rule: best of kk of the new method versus one rival run. Compare its curve with k/(k+1)k/(k+1), the gray reference curve, press ‘Another experiment’ several times and try other rules. Then set δ=1\delta = 1: how many seeds does the interval need to detect improvement half the time? With δ=0.5\delta = 0.5, why does the best-seed rule not detect it reliably even with 20?

The figure separates rules into two groups. “Best of kk versus 1” and “mean” without interval always declare a winner, so with δ=0\delta = 0 every verdict is false, and one favoring B occurs k/(k+1)k/(k+1) and 50% of the time. “Best seed of each” is symmetric but a poor estimator: a sample maximum has high variance, and with δ=0.5σ\delta = 0.5\sigma 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 δ=0\delta = 0 wrongly favors B 2.5% of the time. Its price is power: with δ=σ\delta = \sigma it needs about nine seeds per method to detect improvement half the time, and with δ=0.5σ\delta = 0.5\sigma and 20 seeds detects it in only 34% of experiments.

A protocol that withstands review:

  1. Fix seeds before looking: 0,…,k−10, \dots, k-1 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.
  2. Report all runs: mean, standard deviation, number of seeds and interval xˉ±tk−1,0.975 s/k\bar{x} \pm t_{k-1, 0.975}\,s/\sqrt{k}, and plot individual points, not only a bar (uncertainty visualization from the matplotlib lesson).
  3. Choose kk for the difference you want to detect. With normal approximation, detecting difference δ\delta at power 0.8 and level 0.05 requires about 2(z0.975+z0.8)2σ2/δ22(z_{0.975} + z_{0.8})^2\sigma^2/\delta^2 seeds per method: 16 for δ=σ\delta = \sigma, 63 for δ=σ/2\delta = \sigma/2 (sample-size calculation is developed in statistics).
  4. 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.
  5. 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.
[ ]Multiple seeds: best of k, intervals and sample sizeBrowser
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 tt gives 17 and 64), but the message is unchanged: detecting improvements of half a standard deviation requires dozens of seeds. In reinforcement learning, where σ\sigma 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

QuizWhat level can you expect?
You train on your RTX 4060 with complete seeding, 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.

QuizA RuntimeError in deterministic mode
You enable 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.

NumericBest of ten
A method's accuracy on one seed is approximately N(0.80,0.022)\Normal(0.80, 0.02^2). If the best of 10 seeds is reported, what value is reported on average? Estimate by simulation (or using the theorem's integral).
NumericThe seed birthday paradox
A sweep launches 10510^5 runs, each with an independently uniformly random 32-bit root seed. What is the expected number of pairs of runs sharing a seed?
NumericHow many seeds?
In the lab, standard deviation across seeds is σ=1.07\sigma = 1.07 accuracy points. You want to detect a real improvement of 1 point with power 0.8 and level 0.05 (two-sided). With the normal approximation, how many seeds per method are needed at minimum?
ProofTwo tied streams
Prove: Let a congruential generator be xn+1=(a xn+c) mod mx_{n+1} = (a\,x_n + c) \bmod m and two streams have seeds x0x_0 and x0′=x0+dx'_0 = x_0 + d. Then xn′−xn≡and(modm)x'_n - x_n \equiv a^n d \pmod m for all n≥0n \ge 0, regardless of x0x_0, and the streams are correlated.
0
Both sequences use the same aa, cc and mm.

Step 1 of 4. How do you approach the proof?

Codeseed_everything and make_worker_init_fn
Implement 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: None
Shift+Enter to run

Summary

Key idea
Fixing a seed does not make a result reproducible: it makes it repeatable in a particular environment only if all generators and all sums whose order the GPU decides are controlled. What can be claimed of a method is its distribution over seeds, reported in full, never its best run.
  • 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.Generator replaces global state.
  • Experiment streams derive from a root with SeedSequence and spawn, never seed plus index. With random starting points overlap risk is at most n(n−1)L/Pn(n-1)L/P, negligible with P=2128P = 2^{128}; the real risk is 32-bit seeds.
  • In PyTorch: torch.manual_seed, one torch.Generator per component, generator= in DataLoader and dataset generators created in worker_init_fn (serializable) from get_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) and cudnn.benchmark = False control it at a cost to measure (×10 for index_add_, ×1.3 for the lab step).
  • With identical methods, best of kk versus one rival run wins with probability k/(k+1)k/(k+1) and inflates by ekσe_k\sigma. Fix seeds beforehand, report all with mean and interval, and choose kk for the difference to detect.