Example

Replay a computation exactly, then break batch invariance

Run the same seeded function twice and compare bit-for-bit, then show that changing the batch size changes the answer.

Reproducibility has levels. The same program with the same seed on the same device may replay bit-for-bit. The same computation with a different batch shape may not. A test that only checks the first property can pass while a serving system silently changes its answers when requests are batched together.

This example runs two checks. run_twice seeds PyTorch, executes a function, reseeds, executes again, and compares with torch.equal. batch_invariance computes the first sample’s output at batch 1 and batch 4 and compares them. The replay is exactly equal; the batch comparison differs by 5.378, so invariant: false. The second result is the important one: a batch-size change is a numerical change, not just a scheduling change.

Run it

From the canonical repository at commit f958967d70992d7b09d9c75000bd8c543f1644d4:

python examples/ch39/repro.py --json

Python 3.11 or later with PyTorch. CPU-only, seeded, no model download, network, GPU or credentials. It finishes in about a second.

Implementation

run_twice resets the seed before each call and checks torch.equal, not a tolerance. batch_invariance calls the same function at two batch sizes and compares the first row. make_manifest records Python, PyTorch, platform and seed alongside the result.

def run_twice(fn: Callable[[], torch.Tensor], seed: int = 0, tol: float = 1e-5) -> ComparisonResult:
    torch.manual_seed(seed)
    a = fn().detach().clone()
    torch.manual_seed(seed)
    b = fn().detach().clone()
    exact = torch.equal(a, b)
    diff = float((a - b).abs().max().item()) if a.numel() else 0.0
    return ComparisonResult(exact_equal=exact, max_abs_diff=diff, within_tolerance=diff <= tol, manifest=make_manifest(seed), metadata={})


def batch_invariance(fn_batch: Callable[[int], torch.Tensor], tol: float = 1e-5) -> dict:
    # fn_batch(batch_size) returns output for first sample; compare batch=1 vs batch=4.
    out1 = fn_batch(1)
    out4 = fn_batch(4)
    first = out4[0] if out4.dim() > 1 else out4
    diff = float((out1 - first).abs().max().item())
    return {"max_abs_diff": diff, "invariant": diff <= tol}

Expected outcome

Observed with the command above (exit 0). Selected stable fields:

  "comparison": {
    "exact_equal": true,
    "max_abs_diff": 0.0,
    "within_tolerance": true,
  "batch_invariance": {
    "max_abs_diff": 5.378466606140137,
    "invariant": false

The replay was bit-for-bit identical. The batch-1 and batch-4 first rows were not: the maximum difference was 5.378, far above the 1e-5 tolerance. The manifest records the Python, PyTorch and platform versions, so the claim is tied to an environment rather than to “PyTorch” in general.

Mechanism and limitations

Documented: run_twice resets the seed before each call and uses exact tensor equality. batch_invariance compares the first sample at two batch sizes. make_manifest captures Python, Torch, platform and seed. The tests check exact equality for a constant function, the manifest seed, the batch-invariance field, the demo, JSON serialisation and a zero-tolerance case.

Observed: the command exited 0 with exact replay and invariant: false for the batch comparison. The targeted tests.test_ch39_repro is part of the canonical suite; no independent test count is claimed here.

Not shown: that a different batch size always changes the answer; that a GPU would behave the same way; that the difference is acceptable for a task; or that the replay is portable across machines. The fixture draws new random tensors at each batch size, so it demonstrates sensitivity to the input draw as much as batch invariance. A proper invariance test holds the first sample fixed and changes only the batch dimension.

Challenge this result

Fix fn_batch so that the first row is identical for batch 1 and batch 4, then rerun. invariant should become true. Explain why that change weakens the test’s ability to detect a real batching bug. Then design a test that holds the first sample fixed, changes the batch size and the other rows, and still detects a kernel that mixes samples. State the tolerance and the exact comparison.

Source and verification

Canonical source: examples/ch39/repro.py at commit f958967d70992d7b09d9c75000bd8c543f1644d4. Tests: tests/test_ch39_repro.py . Chapter: Correctness, Determinism and Reproducibility . The run above is a fresh local execution on Windows 11 with Python 3.13.15 and PyTorch 2.6.0+cu124; it uses random tensors, not a model.

Understand this example

Copy this prompt into your AI tool. No code runs here.

Apply this example

Copy this prompt into your AI tool. No code runs here.