5.8 Reproducibility and Inspection
Suppose you tweak a single line in a training script and validation accuracy on Fashion-MNIST edges up by 0.3 percentage points. Before celebrating, you need to know how much two runs of the unchanged script vary on their own. In Section 5.8.1.5, we run softmax regression five times differing only in their random seed and watch final accuracies span one to four percentage points simply from different initial weights and batch shuffling, swamping a 0.3 point gain completely.
Debugging a crashing training run presents the mirror-image problem: if the loss explodes to NaN after hours of training, we want to reproduce the exact sequence of steps leading up to the crash and then peer inside the running network to pinpoint which layer emitted the first non-finite value.
This section addresses both halves together. First, we make runs repeatable by controlling pseudorandom number generators—global seeds, private generator objects, and multi-worker data loaders—and then tackle the trickier GPU wrinkle: floating-point non-associativity under parallel atomic reductions. Second, we inspect live models without modifying their code using hooks (and their framework equivalents) to log activation scales, catch the first NaN layer, and monitor gradient norms. Both halves reinforce each other: internal diagnostics are only comparable across two code versions when nothing else changes between runs. On a first pass, feel free to skim the subsections on generator objects and data-loader workers, revisiting them once your data pipelines perform random augmentations.
from torch.utils.data import DataLoader, Dataset5.8.1 Seeds and Random Number Generators#
Randomness sneaks into a training pipeline from far more places than most practitioners realize: weight initialization (Section 5.3), dropout masks at every step, epoch-by-epoch minibatch shuffling, random data augmentations (crops, flips, color jitter), and parallel data-loader worker processes. Every random number comes from a pseudorandom number generator (PRNG), a deterministic algorithm whose entire sequence is determined by its initial seed. Seeding every generator the pipeline touches therefore locks down every random draw.
5.8.1.1 Global Seeds#
Deep learning frameworks either pull random numbers from a shared global generator or require passing generator state explicitly as an argument. Below we demonstrate seeding on a small five-step training loop where weights and synthetic inputs all come from one seeded source.
torch.manual_seed(k) seeds the framework's global CPU and GPU generators (note that Python's random and NumPy's np.random must be seeded separately if used).
def train_once(seed):
torch.manual_seed(seed) # seeds the CPU and every GPU
net = nn.Sequential(nn.Linear(20, 32), nn.ReLU(), nn.Linear(32, 1))
opt = torch.optim.SGD(net.parameters(), lr=0.1)
X, y = torch.randn(128, 20), torch.randn(128, 1)
for _ in range(5):
opt.zero_grad()
loss = ((net(X) - y) ** 2).mean()
loss.backward()
opt.step()
return loss.item(), net[0].weight.detach().clone()
loss_a, w_a = train_once(seed=0)
loss_b, w_b = train_once(seed=0)
loss_c, _ = train_once(seed=1)
print('same seed, identical loss and weights:',
loss_a == loss_b, torch.equal(w_a, w_b))
print('different seed:', loss_a, 'vs', loss_c)same seed, identical loss and weights: True True
different seed: 0.8643209338188171 vs 0.9312677383422852
Both runs with seed=0 match bit for bit (every weight and the final loss are
identical) because identical initial weights, data, and deterministic arithmetic
produce identical gradients (we examine operation order in
Section 5.8.2). Changing the seed to 1 yields a
distinct trajectory and loss.
5.8.1.2 Generator Objects#
Relying on a single global PRNG couples every piece of code that draws from it: adding a single extra layer or a temporary random print during debugging shifts the entire downstream stream, silently altering train/validation splits, weight initializations, and dropout masks all at once. A private generator object isolates a stream behind its own seed so unrelated draws elsewhere can never perturb it.
torch.Generator().manual_seed(42) creates an isolated PRNG stream unaffected by global draws:
g = torch.Generator().manual_seed(42)
split = torch.randperm(10, generator=g)
_ = torch.randn(1000) # unrelated draws from the global generator
split_again = torch.randperm(10, generator=g.manual_seed(42))
print(torch.equal(split, split_again), split)True tensor([2, 6, 1, 8, 4, 5, 0, 9, 3, 7])
5.8.1.3 Data Loader Workers#
When data loaders prepare minibatches in parallel worker processes, random
data augmentation introduces two silent failure modes. If workers are spawned via
OS fork as clones of the main process without re-seeding, every worker
inherits the exact same generator state and generates identical "random"
augmentations. Conversely, if each worker initializes from OS entropy, no two
runs will ever match.
DataLoader seeds each worker's PyTorch, random, and global NumPy RNGs from base_seed + worker_id, but a private np.random.default_rng() attribute on the Dataset is cloned identically across forked workers unless re-seeded via worker_init_fn using torch.utils.data.get_worker_info().seed:
class NoisyData(Dataset):
"""Eight examples whose values are random draws, as in augmentation."""
def __init__(self):
self.rng = np.random.default_rng() # the dataset's own generator
def __len__(self):
return 8
def __getitem__(self, i):
return self.rng.random()
def seed_worker(worker_id):
info = torch.utils.data.get_worker_info()
info.dataset.rng = np.random.default_rng(info.seed) # this worker's seed
for init_fn in (None, seed_worker):
loader = DataLoader(NoisyData(), batch_size=4, num_workers=2,
worker_init_fn=init_fn,
multiprocessing_context='fork', # copies of this one
generator=torch.Generator().manual_seed(0))
print([[round(x, 3) for x in batch.tolist()] for batch in loader])[[0.61, 0.817, 0.884, 0.742], [0.61, 0.817, 0.884, 0.742]]
[[0.777, 0.641, 0.352, 0.467], [0.653, 0.267, 0.932, 0.823]]
Without per-worker or per-example re-seeding, both workers output identical "random" numbers in the first line; proper seeding gives distinct, reproducible draws in the second line.
5.8.1.4 Randomness as a Value#
Every worker bug above stems from hidden mutable generator state being copied or shared implicitly behind the scenes. Functional random APIs eliminate hidden state by treating randomness as an explicit value: every random call takes a key, calling it twice with the same key returns identical numbers, and independent streams come from explicitly splitting keys. While you can still reuse a key accidentally, the reuse is right there in the code. The price is plumbing keys through every stochastic function. A global seed is simply the implicit shorthand for that same contract, and private generator objects recover explicit isolation wherever needed.
5.8.1.5 The Spread across Seeds#
Now we measure the seed-to-seed variance mentioned at the start of the section. Below we train softmax regression (Section 3.3.5) on Fashion-MNIST for three epochs on a GPU across five seeds (0 through 4), seeding every generator involved and returning each run's final validation accuracy and weights.
def train_classifier(seed, data):
torch.manual_seed(seed) # initialization and shuffle order
model = d2l.SoftmaxRegression(num_outputs=10, lr=0.1)
trainer = d2l.Trainer(max_epochs=3, num_gpus=1)
trainer.board.display = False
trainer.fit(model, data)
return trainer.history['val_acc'][-1], model.net[1].weight.detach().cpu()
data = d2l.FashionMNIST(batch_size=256)
runs = [train_classifier(seed, data) for seed in range(5)]
accs = 100 * np.array([acc for acc, _ in runs])
print('validation accuracy (%):', ' '.join(f'{a:.1f}' for a in accs))
print(f'mean {accs.mean():.1f}, max - min {np.ptp(accs):.1f} points')validation accuracy (%): 79.8 81.8 81.9 78.3 82.1
mean 80.8, max - min 3.7 points
Even though all five runs execute identical code and hyperparameters, their final accuracies spread by one to four percentage points around 81%, confirming that a 0.3-point jump from a single run is pure noise. Sound empirical comparisons always report the mean and spread across multiple seeds.
To verify that seed choice alone drove those differences, we rerun seed=0
and compare both accuracy and every weight against the first run:
acc, w = train_classifier(0, data)
print('same accuracy:', acc == runs[0][0],
'| same weights:', torch.equal(w, runs[0][1]),
f'| largest difference {(w - runs[0][1]).abs().max().item():.2g}')same accuracy: True | same weights: True | largest difference 0
The rerun matches the first run's validation accuracy identically. Whether every single weight matches down to the last bit depends on whether the GPU sums floating-point numbers in a fixed order, something seeds alone do not control (Section 5.8.2).
5.8.2 Deterministic Arithmetic#
Seeding fixes which random numbers a run draws, not how floating-point arithmetic combines them. Because every floating-point addition rounds to the nearest representable value, floating-point addition is not associative: changing summation order can change the result.
Three float32 numbers make the effect unmistakable. Near , adjacent float32 numbers lie 8 apart (Section 5.5), so rounds right back to :
a, b, c = [torch.tensor(v, dtype=torch.float32) for v in (1e8, -1e8, 1.0)]
print(float((a + b) + c), float(a + (b + c))) # same numbers, regrouped1.0 0.0
Simply shifting parentheses changes the answer from 1.0 to 0.0. In long
reductions the discrepancy is subtler but pervasive: summing a million floats
forward versus backward routinely differs in the lowest bits.
On a CPU with a fixed thread count, reduction order usually stays constant, so seeded runs repeat cleanly. On a GPU, thousands of threads race in parallel, and several fast kernels (including embedding gradients, scatter-adds, certain convolution backward passes, and reductions) accumulate partial results via atomic additions that land in whatever order threads finish. Two identically seeded runs on the same GPU can therefore diverge in their lowest bits, which chaotic gradient steps eventually amplify into visibly distinct loss curves. Every framework provides a determinism mode (or alternative kernel) that forces a fixed summation order, typically at some speed cost. Below we observe this directly on a GPU scatter-add summing one million random numbers into ten bins twice in a row.
torch.use_deterministic_algorithms(True) switches operations like index_add_ to deterministic kernels (or raises a RuntimeError if none exists):
if torch.cuda.is_available():
src = torch.randn(2**20, device='cuda') # a million numbers
idx = torch.randint(0, 10, (2**20,), device='cuda') # their bins
for deterministic in (False, True):
torch.use_deterministic_algorithms(deterministic)
a, b = [torch.zeros(10, device='cuda').index_add_(0, idx, src)
for _ in range(2)]
print(f'deterministic {deterministic!s:5}: bitwise equal '
f'{torch.equal(a, b)}, largest difference '
f'{(a - b).abs().max().item():.2g}')
torch.use_deterministic_algorithms(False)
else:
print('no GPU: on a CPU this sum adds in a fixed order')deterministic False: bitwise equal False, largest difference 0.0051
deterministic True : bitwise equal True, largest difference 0
Without determinism enabled, two consecutive scatter-adds on the exact same GPU data differ by a few thousandths on sums of a few hundred; with a deterministic kernel, both calls match bit for bit.
Remember the proper scope of bitwise reproducibility: it holds only on a single machine, software stack, and hardware configuration; no framework promises identical bits across library upgrades, different GPU architectures, or CPU vs. GPU. Bitwise determinism is an invaluable debugging tool for bisecting the exact step where two runs diverge. Scientific reproducibility is both looser and stronger: any genuine improvement ("this architectural change improves accuracy") must hold robustly across multiple seeds, reported as mean and spread just as in Section 5.8.1.5 (~81%, spanning 1–4 points). As with 16-bit formats (Section 5.5), any claim that flips under a new seed or last-bit rounding needs stronger evidence.
5.8.3 Model Inspection with Hooks#
Repeating a bug reliably proves it is real, not where inside the network it
originates. Inserting print statements into every layer's forward method is
clumsy, and impractical for third-party library models whose source code you do
not want to fork. A hook solves this cleanly: it is a callback registered from
outside the model that the framework invokes automatically before or after a
layer executes.
module.register_forward_hook(f) runs f(module, inputs, output) inside __call__ after forward (and returning a new tensor replaces the output).
The __call__ wrapper as a pipeline: input flows through pre-hooks, then forward, then hooks, to the output, with the two hook stages dashed and orange against forward's solid blue, and a side arrow from the hooks stage to an observer that can capture, check, or modify.
For our inspection examples, we build an eight-block residual stack of width 64 between a 20-input layer and a 10-output head (Section 5.1), each block computing with Xavier-initialized weights (Section 4.4.2.1) and zero biases. We deliberately leave this network unseeded so each run draws fresh random weights, which is why the diagnostic measurements below are cited as typical ranges.
The seeded runs above left PyTorch's global generator at a fixed state,
which would fix this model's weights too, so the cell first reseeds the
generator from the operating system's entropy with torch.seed().
torch.seed() # a fresh seed from the operating system
class ResidualBlock(nn.Module):
def __init__(self, num_hiddens):
super().__init__()
self.body = nn.Sequential(nn.Linear(num_hiddens, num_hiddens),
nn.ReLU(),
nn.Linear(num_hiddens, num_hiddens))
def forward(self, X):
return X + self.body(X)
net = nn.Sequential(nn.Linear(20, 64),
*[ResidualBlock(64) for _ in range(8)],
nn.Linear(64, 10))
for m in net.modules():
if isinstance(m, nn.Linear): # Xavier weights, zero biases
nn.init.xavier_uniform_(m.weight)
nn.init.zeros_(m.bias)5.8.3.1 Activation Statistics#
In Section 5.3, we manually looped through blocks to measure activation standard deviations across depth. With hooks, we can collect the exact same profile from an unmodified model in just a few lines on a minibatch of 256 standard normal inputs:
stats, handles = [], []
def record(module, inputs, output):
stats.append((type(module).__name__, output.detach().std().item()))
for m in net:
handles.append(m.register_forward_hook(record))
net(torch.randn(256, 20))
for h in handles:
h.remove()
for name, std in stats:
print(f'{name:15s} std {std:.2f}')Linear std 0.72
ResidualBlock std 0.88
ResidualBlock std 1.09
ResidualBlock std 1.31
ResidualBlock std 1.62
ResidualBlock std 1.98
ResidualBlock std 2.28
ResidualBlock std 2.93
ResidualBlock std 3.58
Linear std 3.51
Activation standard deviations climb steadily with depth, from roughly 0.7 right after the input layer to around 3–4.5 after the eighth block, matching theory closely. Xavier initialization gives the input layer weight variance , yielding output variance (standard deviation 0.69). Each residual block then adds an approximately uncorrelated body output whose variance is half its input variance (the first linear layer preserves variance, ReLU halves the mean square, and the second linear layer preserves it), multiplying total variance by (and standard deviation by ) at every block. Across eight blocks, , right in the middle of our measurements. This is the exact variance-growth analysis of Section 5.3 (with factor here instead of under He initialization), underscoring why deep residual branches benefit from scaled-down output projections.
Two rules keep hooks leak-free: always .detach() any tensor stored inside a hook (otherwise the entire autograd graph stays alive in memory across steps), and always remove the hook handle (h.remove()) once inspection is done.
5.8.3.2 A NaN Finder#
When a training loss suddenly turns NaN at step 40,000, your first diagnostic question is which layer emitted the first non-finite value? Attaching a finiteness hook to every leaf layer pinpoints the culprit in a single forward pass, because hooks execute in forward execution order. To test our detector, we deliberately inject a NaN into one weight of the third residual block (index 3):
def make_finite_check(name):
def check(module, inputs, output):
if not torch.isfinite(output).all():
raise RuntimeError(f'first non-finite output in {name}')
return check
handles = [m.register_forward_hook(make_finite_check(name))
for name, m in net.named_modules()
if len(list(m.children())) == 0] # leaf modules only
saved = net[3].body[0].weight[0, 0].item()
with torch.no_grad():
net[3].body[0].weight[0, 0] = float('nan') # break one layer
try:
net(torch.randn(2, 20))
except RuntimeError as e:
print(e)
for h in handles:
h.remove()
with torch.no_grad():
net[3].body[0].weight[0, 0] = saved # restore the weightfirst non-finite output in 3.body.0
The hook immediately identifies the corrupted layer in block 3 without adding a single print statement inside the layer classes. Of course, catching a planted NaN is the clean demo case; in a real training crash, the finder points you to the first symptom, while the underlying cause (such as runaway activation growth culminating in overflow) may begin several layers earlier.
5.8.3.3 Gradient Inspection#
We can monitor the backward pass with the same precision. Since forward activations grew across our eight residual blocks, do gradients grow in reverse? Using the mean squared output on 256 standard normal inputs as our loss, we log the gradient norm at each residual block's output alongside the weight and bias gradient norms of the first linear layer in block 3.
module.register_full_backward_hook(f) invokes f(module, grad_input, grad_output) during backward() (firing in reverse topological order, from last block to first):
X = torch.randn(256, 20)
grad_norms, handles = [], []
def record(module, grad_input, grad_output):
grad_norms.append(grad_output[0].norm().item()) # store a number
for block in net[1:-1]:
handles.append(block.register_full_backward_hook(record))
net.zero_grad()
(net(X) ** 2).mean().backward()
for h in handles:
h.remove()
# The hooks fire in backward order, last block first
print('block output gradients:',
' '.join(f'{g:.3g}' for g in reversed(grad_norms)))
layer = net[3].body[0] # block 3, first layer
print(f'weight {layer.weight.grad.norm().item():.3g}, '
f'bias {layer.bias.grad.norm().item():.3g}')block output gradients: 1.04 0.83 0.659 0.489 0.396 0.317 0.257 0.194
weight 12.9, bias 2.52
Reading backward from the eighth block to the first, the output gradient norm grows by roughly to per block (five- to sixfold across the stack), mirroring the forward growth for the exact same reason: on the backward pass, each residual block adds the branch gradient back onto the skip-connection gradient. Isolated parameter gradient norms mean little on their own, but comparing them across depth or tracking them across training steps reveals vanishing or exploding dynamics immediately (see the exercises).
Remember what these debugging tools do and do not solve: they cannot force two different machines to match bit for bit, nor can a single run settle whether an experimental gain is real (for that, compare distributions across multiple seeds). Yet combined with resumable checkpoints (Section 5.6), you now have every piece needed to replay a failing job right up to the crash and attach a diagnostic hook to isolate the exact layer at fault.
The 8-billion-parameter language model that opened this chapter has not shrunk (it still weighs 32 GB in fp32), but nothing about how frameworks handle it is a black box anymore. Constructing architectures from configs, auditing parameters and buffers, initializing deep stacks, building custom layers and gradients, training in mixed precision, saving crash-safe checkpoints, managing GPU memory, and inspecting live runs all operate over the exact same tree of modules. Equipped with this engineering toolkit, we are ready to move on to architectures built around the structure of real-world data, starting with convolutional neural networks in Chapter 6.
5.8.4 Summary#
Every random choice in training (initialization, shuffling, dropout, and data augmentation) traces back to pseudorandom number generators controlled by seeds, with private generator objects or explicit keys preventing unrelated code from perturbing a stream. Because floating-point addition is non-associative and parallel GPU atomic operations sum in arbitrary thread order, bit-for-bit repeatability also requires deterministic kernels and holds only on one machine and software stack, making bitwise determinism a debugging tool while scientific conclusions must hold across multiple seeds. Finally, forward and backward hooks (and their framework equivalents) let us inspect activation scales, gradient norms, and first-occurrence NaNs inside unmodified models.
5.8.5 Exercises#
- [code] Residual variance budget. Let ,
and denote the input, body output and
output of block , with each variance taken over all entries. On one
batch, record for every
ResidualBlockthe variance of withregister_forward_pre_hook(the pre-hook receives the argument tuple, so unpack it), of with a forward hook on the block, and of with a forward hook on itsbody. The standard deviations in the table of Section 5.8.3.1 grow because each block adds its body's output to the stream. Measure how closely
holds for every block, and name the term this equation omits.
2. [code] Seeds and data loading. ● Extend train_once to load its
data through a DataLoader with shuffle=True and num_workers=4,
keeping the single torch.manual_seed(seed) call at its top. The
dataset adds noise to each example inside __getitem__, drawn from an
np.random.default_rng() object created in the dataset's constructor.
Run the code as a standalone script, because worker processes started
with spawn, the default on macOS and Windows, cannot import a dataset
class defined in a notebook.
- Predict whether two runs with the same seed agree on the shuffle order and on the noise, and whether the four workers draw the same noise. Justify each prediction from where that randomness is drawn, then verify all three.
- Add the
seed_workerof this section and a seededgeneratorto the loader, and verify that two runs now agree and that the workers draw different noise. Does an example receive the same noise in the second epoch as in the first? Explain the answer from when the loader draws its base seed and calls the initializer.
Adapted from the PyTorch documentation
Multi-process data loading.
3. [code] Divergence monitor. ● Turn the finiteness check of
Section 5.8.3.2 into a per-step training monitor. Rebuild
net and train it with SGD at learning rate 1 on the mean squared
error between its output and standard normal targets, using one fixed
batch of 256 standard normal inputs. Report the first step at which a
layer's output is non-finite, and the first such layer by depth. Check
the loss at every step as well, and report whether it becomes
non-finite before any layer output does.
4. [code] Gradient norms. ● Rebuild net, multiply the weight of
every linear layer inside its residual blocks by 3, and use the mean
squared output on a fixed batch as the loss.
- Record the norm of each block's output gradient as in this section. After the backward pass, compute each block's parameter-gradient norm, and plot both families against depth.
- Express the gradient of a linear layer's weight through the layer's input and its output gradient. Use this expression to explain why the two depth profiles differ, and state which family to monitor for an exploding backward signal.