Reproducibility and Inspection

Dive into Deep Learning · §5.8

Reproducibility, Debugging, and Model Inspection
PRNG seeds & keys · data-loader workers · non-associative GPU atomics · forward & backward hooks

Why Reproducibility and Model Inspection Belong Together

Scientific Validity vs. Bug Hunting

  • Is a 0.3-point accuracy gain real or random noise? Five runs of the exact same Fashion-MNIST training script differing only in their random seed span 1\text{--}4 percentage points.
  • Why did the loss turn NaN at step 40,000? Debugging late-stage crashes requires reproducing the exact trajectory and inspecting layer activations/gradients via non-invasive hooks.

Where Randomness Enters a Deep Learning Pipeline

Five Stochastic Entry Points

  • Model & layer randomness: Weight initialization (\mathbf{W}_0) and stochastic forward masks (Dropout \boldsymbol{\xi}_j).
  • Data & worker randomness: Epoch minibatch shuffling, random data augmentations, and forked multi-process data-loader workers (which clone identical NumPy RNG state unless re-seeded per worker).

Seeding Repeats a Training Trajectory Bit for Bit

Global Seeds vs. Explicit Keys

When we seed every PRNG the loop touches, two runs with seed=0 produce identical losses and weights down to the last bit:

same seed, identical loss and weights: True True
different seed: 0.8643209338188171 vs 0.9312677383422852
  • Coverage caveat: A framework seed does not seed Python’s random or NumPy’s np.random—if your dataset uses NumPy, seed it explicitly too.

Private Generator Objects Prevent Stream Coupling

Isolating Stochastic Streams

  • A private generator object (or a split key) isolates a random stream so adding a debug call never shifts downstream weights or batches:
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])

The Multi-Worker DataLoader Fork Bug

Why Forked Workers Duplicate Random Draws

When a DataLoader spawns num_workers=2 processes via OS fork, each worker inherits an identical clone of any np.random.default_rng() attribute on the dataset:

[[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]]
  • Identical batches across workers (Row 1): Without per-worker re-seeding, Worker 0 and Worker 1 generate the exact same “random” numbers, so the two batches in the first line are identical.
  • The fix (Row 2): Re-seed each worker’s generator inside worker_init_fn using get_worker_info().seed (or seed per example index [base_seed, i]).

Measuring Seed-to-Seed Variance Across Five Runs

Statistical Reproducibility

Training softmax regression on Fashion-MNIST for 3 epochs across five seeds (0..4) with identical code and hyperparameters reveals the natural variance of stochastic optimization:

validation accuracy (%): 79.8 81.8 81.9 78.3 82.1
mean 80.8, max - min 3.7 points
same accuracy: True | same weights: True | largest difference 0
  • Never trust a single-seed delta: Final validation accuracies span 1\text{--}4 percentage points across seeds; always report mean \pm standard deviation across multiple seeds.

Why Floating-Point Addition Is Not Associative

The Arithmetic Wrinkle

  • Because every float addition rounds to the nearest representable value, (a + b) + c \neq a + (b + c):
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, regrouped
1.0 0.0
  • Swamping at 10^8: Near 10^8, adjacent float32 numbers sit 8.0 apart, so 10^8 + (-10^8 + 1.0) = 0.0 while (10^8 - 10^8) + 1.0 = 1.0.

GPU Atomic Reductions and Deterministic Kernel Switches

Why Seeded GPU Runs Diverge

On a GPU, thousands of threads accumulate partial sums into shared bins (in scatter_add, index_add_, embedding backward passes, and convolutions) via atomic additions that land in whatever order threads finish:

deterministic False: bitwise equal False, largest difference 0.0051
deterministic True : bitwise equal True, largest difference 0
  • Enabling bitwise GPU determinism: Turning on deterministic kernels enforces a fixed reduction tree so consecutive GPU runs match bit for bit.

Bitwise Determinism vs. Scientific Reproducibility

Scope of Bitwise Repeatability

  • Bitwise determinism is a local debugging tool: Guarantees identical bits on one machine, one GPU architecture, and one library version to bisect the exact step where a bug or NaN appears.
  • Scientific reproducibility is statistical: Real modeling improvements must hold across multiple random seeds (N \ge 5) and survive minor floating-point reassociation across hardware.

Non-Invasive Model Inspection with Execution Hooks

Observing Layers From Outside

When debugging a deep network or a locked third-party library model, editing every layer’s forward method to insert print statements is clumsy. Hooks wrap __call__ around each submodule’s execution from the outside:

  • Pipeline around forward: Invoking net(X) runs registered pre-hooks, executes forward(X), and passes (module, inputs, output) to registered forward hooks.

Building an 8-Block Residual Stack for Inspection

Unscaled Xavier Residual Stack

  • We construct an 8-block residual MLP (20 \to 64 \to 8\text{ blocks of width } 64 \to 10) initialized with Xavier uniform weights and zero biases.

The 8-Block Residual Stack in Code

Unscaled Xavier Residual Stack

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)

Profiling Activation Standard Deviations Across Depth

Forward-Hook Diagnostic

Attaching a forward hook to every top-level module captures the activation growth profile across all 10 layers in a single forward pass on 256 standard normal inputs:

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
  • Steady growth across blocks: The output standard deviation starts at \approx 0.7 after the 20 \to 64 input layer and climbs steadily to \approx 3.2\text{--}4.5 after the eighth residual block.
  • Zero model edits: Capturing intermediate outputs from outside records each block’s output scale cleanly without modifying layer definitions.

Why Xavier Residual Blocks Grow by √1.5 ≈ 1.22 per Block

Analytical Verification of Hook Measurements

\text{Var}[\mathbf{h}_k] \approx \text{Var}[\mathbf{x}_k] + \frac{1}{2}\text{Var}[\mathbf{x}_k] = 1.5\,\text{Var}[\mathbf{x}_k]

  • Why the body contributes \frac{1}{2}\text{Var}[\mathbf{x}_k]: The first 64 \to 64 Xavier layer preserves variance (1\times), ReLU halves the mean square (\frac{1}{2}\times), and the second Xavier layer preserves that half (\frac{1}{2}\times).
  • Exact match with hooks: Starting from \approx 0.69, multiplying by \sqrt{1.5} \approx 1.225 across 8 blocks predicts 0.69 \times 1.5^4 \approx 3.5.

Two Golden Rules for Leak-Free Hooks

Preventing Autograd Memory Leaks

  1. Always .detach() stored tensors (or extract scalars via .item()): Appending a live activation tensor output directly to a Python list retains the entire backward computation graph in GPU memory across steps.
  2. Always remove hook handles when finished (h.remove() / h.detach()): Unregister callbacks inside a finally block so they do not persist across future forward passes.

Pinpointing the First NaN Layer in One Forward Pass

Automated NaN Traps

Because forward hooks fire in exact execution order, attaching a finiteness check (isfinite(output).all()) to every leaf layer immediately halts and names the first layer that emits inf or NaN:

first non-finite output in 3.body.0

Monitoring Backward Gradient Norms Across Depth

Backward Hooks & Gradient Flow

Inspecting gradient norms at each residual block’s output during backpropagation reveals the exact mirror image of forward activation growth:

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
  • Backward amplification (\times 1.2\text{--}1.4 per block): Because each residual block’s backward pass adds the branch Jacobian back onto the skip connection, output gradient norms grow 5\text{--}6\times as they travel backward from block 8 to block 1.

Concept Check: Determinism, Variance Growth & Hooks

Concept Check

Test your diagnostic skills on these three questions:

  1. A training script seeds the framework PRNG with 0 at the top. Inside the dataset’s __getitem__, it adds Gaussian noise using self.rng = np.random.default_rng() created in its __init__. Will two single-process runs match? What happens with 4 data-loader workers under fork?
  2. In our Xavier-initialized residual stack, activation standard deviation grows by \sqrt{1.5} \approx 1.225 per block. After how many blocks k does the activation standard deviation exceed 100\times its post-input value?
  3. What happens to GPU memory during training if a forward hook executes history.append(output) on every step without calling .detach()?

Answers:

  1. Single-process runs differ because np.random.default_rng() draws fresh OS entropy ignoring the framework seed. With 4 forked workers, all 4 inherit identical clones of self.rng and apply identical noise.
  2. 1.5^{k/2} \ge 100 \implies k \ge \frac{2 \ln 100}{\ln 1.5} \approx 22.7 (23 blocks).
  3. Out-of-memory (OOM) crash: Each output keeps its entire autograd graph and intermediate activations alive in history forever.

Summary: Reproducibility, Debugging, and Inspection

Key Takeaways

  • PRNG seeding & statistics: Seed framework, NumPy, Python random, and data-loader workers; report mean \pm std across N \ge 5 seeds.
  • Bitwise determinism: Enable deterministic GPU kernels to replace non-associative parallel atomic adds with fixed-order reductions during bug bisection.
  • Execution hooks: Capture forward activations and backward gradients from outside (detaching stored tensors and removing handles when done) to profile scales and trap the first NaN layer.