Skip to content

Parity-check a port

Use this guide when you need evidence that a TPU result is correct: a ported model, a new kernel, a compiler flag, a sharding change, or a serving build. You decide in advance what level of agreement you owe, build an independent reference, compare with tolerances you can trace to a source or a measurement, prove the check can fail, and, when it fails, find the first layer that diverges. Chapter 23 explains why TPU numbers differ from CPU and GPU numbers without any bug, and where each tolerance comes from.

Prerequisites

  • The model or op under test, and a reference that computes the intended function independently: by default the same code in float32 on the CPU with the same weights and inputs.
  • This book's code/ch23_correctness/ (source): parity.py (parity_report, first_divergent_layer, bisect_layers, loss_curve_parity, top1_agreement) and bisect_demo.py.

Steps

1. Write down the level you owe

Level When Check
Bitwise The change cannot alter the arithmetic (a view instead of a copy, two runs of one program with fixed seeds) torch.equal, or equal loss and gradient norm at every logged step
Elementwise, within a dtype tolerance Same math, different rounding: CPU against TPU, eager against compiled, a kernel against the op it replaces assert_close at the dtype's tolerance
Statistical Rounding amplified over many steps or samples Loss and gradient norm over steps, against measured drift or seed-to-seed spread
Task-level The change alters the model on purpose (quantization, a new serving kernel) Greedy tokens with a tie rule, logprob deltas, an accuracy evaluation

Check: the change has a written class before any number is run. A difference in the seventh digit for a change you classed as bit-identical is a bug.

2. Build the reference

Synchronize the weights (load_state_dict), use identical inputs, and compare outputs and, after loss.backward(), every gradient. Run the TPU side under torch.set_float32_matmul_precision("highest") (restore it afterwards): at TorchTPU's default "medium" a float32 matmul is one bf16 pass and the comparison measures about \(10^{-2}\), which leaves no room to see a bug. Compare like with like: bf16 against bf16, or float32 under Precision.HIGHEST against float32. Perturb parameters initialized to one (norm weights, learned scales) with \(1 + 0.1 \cdot \text{randn}\), and re-tie tied weights after Module.to(device), asserting they are the same object.

Check: the reference does not share the code under test. Eager against compiled checks the compiler, not the model; a laptop run of a CPU-against-TPU helper compares the CPU with itself.

3. Compare with traceable tolerances

import sys
import torch
sys.path.insert(0, "code/ch23_correctness")
from parity import parity_report

rep = parity_report(out_cpu_fp32, out_tpu.cpu(), torch.float32)   # dtype sets the tolerance
rep["allclose"], rep["tol_ratio"], rep["mismatch_fraction"], rep["worst_index"]
rep["peak_rel"], rep["rel_l2"]                                     # for cross-dtype and gradients

Pick the bound by what you compare:

Compared Bound Source
Elementwise, float32 rtol 1.3e-6, atol 1e-5 assert_close defaults, named by TorchTPU's precision guide
Elementwise, bfloat16 rtol 1.6e-2, atol 1e-5 same
Elementwise, float16 rtol 1e-3, atol 1e-5 same
Model at "highest": logits, loss atol 1e-4, rtol 1e-4; atol 1e-5, rtol 1e-5 TorchTitan TPU onboarding skill
Model at "highest": each gradient relative L2 at most 1e-4 same
Model at default precision, dense: logits, loss, gradients atol 5e-2, rtol 1e-2; atol 5e-3, rtol 1e-3; relative L2 2e-2 same
bf16 candidate against fp32 reference peak-relative error 5% TPU Agent Suite compare_parity.py

Bound gradients by relative L2, not elementwise atol: an atol that fits the large gradients accepts a zeroed small one.

Check: read the failure pattern, not just the verdict. Many mismatched elements with small differences point to rounding; a few large ones, or a large peak_rel, point to a logic bug at worst_index. Record the measured error next to each bound.

4. Prove the check can fail

Feed the same comparison the reference gradients zeroed, and again sign-flipped, and assert that it fails both times. For activations, scale one layer's weight (the companion's inject_bug scales block 7's fc1 by 1.10). For a loss curve, change the warm-up schedule; scaling gradients is not a control, because AdamW's update is invariant to gradient scale.

Check: every negative control fails. A bound that cannot reject them is not a bound.

5. When it fails, find the first divergent layer

Capture each layer's output on both sides with forward hooks and compare in execution order:

from parity import first_divergent_layer

idx = first_divergent_layer(ref_acts, out_acts, torch.float32)             # like with like
idx = first_divergent_layer(ref_acts, out_acts, torch.bfloat16, peak_tol=0.05)  # bf16 vs fp32

If captures are expensive and the comparison is like with like, bisect_layers finds the first failing layer in about \(\log_2 n\) runs. In a loose cross-dtype comparison, capture every row instead: the residual stream can dilute a bug back under the bound downstream, so a binary search wanders off.

Check: python code/ch23_correctness/bisect_demo.py --cpu-smoke injects a bug at block 7 of a 12-block model, finds it in 3 bisection probes, shows the bf16 comparison hiding it at block level (3.89% against a 5% bound) while the module row blocks.7.fc1 reads 10.23%, and ends cpu-smoke: OK.

6. Training runs: step 1 tight, later steps against measured drift

Step 1 has no optimizer state, so a gap there is a bug; bound it tightly and check loss, gradient norm and gradients separately. Later steps drift because AdamW amplifies rounding, so their bound comes from a measured clean run, judged on post-warm-up medians, never a per-step 1e-4 over many steps. For determinism, two runs with the same seed and --debug.seed=42 --debug.deterministic (TorchTitan) must give equal loss and gradient norm at every step, read from the TensorBoard event file rather than stdout.

Check: loss_curve_parity in the companion passes reordered sums and fails a warm-up change (step 5 of parity.py --cpu-smoke).

7. Serving: greedy tokens with a tie rule

With temperature: 0, compare greedy tokens with a trusted build. At the first disagreement, excuse the flip only if the reference's top-1 minus top-2 margin is under the tie gap: twice the RMS logprob difference on agreeing positions, floor \(10^{-3}\). Compare teacher-forced logits so one flipped token cannot cascade; top1_agreement in the companion does this. For a change that alters the model on purpose, also run an accuracy evaluation: vLLM-TorchTPU's gate allows a drop of \(\max(1.5\text{ pp}, 1.645\sqrt{se_\text{baseline}^2 + se_\text{run}^2})\).

Check: a clean build passes with any flips explained as ties; a build with a known bug (for example, an LM head scaled by 10%) fails.

8. Run it on the TPU and in CI

python code/ch23_correctness/parity.py --cpu-smoke        # any machine; ends "cpu-smoke: OK"
python code/ch23_correctness/bisect_demo.py --cpu-smoke
python code/ch23_correctness/parity.py                    # TPU VM: block output and every gradient, float32 at "highest" and bf16
python code/ch23_correctness/bisect_demo.py --bug-layer 7 # TPU VM: the bisection demo on the device

Put the parity test in CI on hardware that exercises the code, and confirm in the CI log that it ran rather than skipped. Keep timing assertions out of correctness tests.

Check: the TPU paths print reports with measured errors under their bounds; that output is the record for your TorchTPU version and TPU generation.

Troubleshooting

What you see Usually a false alarm when Usually a real bug when What to do
float32 outputs differ by about \(10^{-3}\) to \(10^{-2}\) The TPU ran at the default "medium" precision The difference survives "highest" Rerun at "highest"
assert_close fails at bf16 tolerance on a few percent of elements One side is float32, or the failing elements are near zero peak_rel far above about 3%, or mismatches cluster on one index Compare like with like; read peak_rel and the worst index
Compiled differs from eager in the last bits Fusion changed summation order The difference is large, or the change was classed bit-identical Classify the change
Loss matches at step 1 and drifts later Optimizer amplification of rounding Step 1 already differs, or the gradient norm differs by a constant factor such as world_size Bound step 1 tightly; compare post-warm-up medians
Two runs of the same program differ Deterministic mode is off They differ with --debug.deterministic and the same seed Rerun deterministically; read every step from the event file
One greedy token differs, then the rest The reference's top two logprobs were within the tie gap The reference margin was wide Apply the tie rule on teacher-forced logits
Everything passes, the model trains worse Rarely; treat it as a bug A dropped multiply hidden by unit initialization; tied weights untied by .to(device); packed batches without segment ids Perturb unit scales; assert tied weights are the same object
A verdict of UNVERIFIED from compare_parity.py Never; the comparison proved nothing Both sides ran the same rewritten code Build an independent reference

References