Skip to content

Correctness: parity gates and numerical checks

40 min read

Prerequisites: Numerical precision and the MXU

A model that runs on a TPU and produces fluent text, a falling loss or plausible images can still be computing the wrong function. A transposed weight, a dropped scale, a mask off by one or a loss summed where it should be averaged rarely crashes anything. Earlier chapters each ended with a check against one of those failures: a layer compared with a CPU run, a loss curve compared with a reference, greedy tokens compared with a trusted build. This chapter turns those checks into one method. It covers what "correct" can mean for a TPU result, how to build a reference you can trust, how to choose a tolerance from the dtype and the operation instead of guessing, how to find the first layer that goes wrong when outputs disagree, and how to wire the result into CI gates that are proven able to fail. It builds directly on chapter 6: every tolerance here traces back to how the MXU rounds.

What this chapter covers

  • The four levels of agreement a TPU result can owe its reference (bitwise, elementwise within a dtype tolerance, statistical over training steps, task-level) and which one a given change needs.
  • References that are independent of the code under test: CPU float32, a GPU run, eager against compiled, a golden dump.
  • Tolerances derived from the dtype, the matmul precision and the operation, using published bounds and measurements instead of guesses.
  • Locating a parity failure: capturing activations, finding the first divergent layer, and telling precision, reduction order and bugs apart.
  • Parity gates in CI: calibrated tolerances, negative controls that prove a gate can fail, and hardware that exercises the code.

What "correct" means for a TPU result

On a CPU you might expect a ported function to return exactly the same numbers. On a TPU that expectation is usually wrong, for the reasons chapter 6 took apart: a float32 matmul at TorchTPU's default "medium" precision rounds its inputs to bf16; XLA fuses operations and may change the order in which a reduction adds its terms; and a compiled program can keep float32 intermediates that eager mode rounds. So "correct" has to be stated as a level of agreement, chosen before you run the check. There are four useful levels.

Level You owe it when Check Example in this book
Bitwise The change cannot alter the arithmetic: a view instead of a copy, reading the loss less often, two runs of one program with fixed seeds torch.equal, or equal loss and gradient norm at every logged step FLUX zero-copy QKV split (chapter 11); determinism repeats
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, or a bound derived for the operation Pallas kernel against its reference (chapter 12)
Statistical Rounding is amplified over many steps or samples: training curves, sampled generation Loss and gradient norm over steps, judged against measured drift or seed-to-seed spread FSDP loss parity (chapter 14); GRPO reward curves (chapter 15)
Task-level The change alters the model on purpose: quantization, a new kernel path in a server, a different MoE balancer Greedy tokens with a tie rule, logprob deltas, and an accuracy evaluation vLLM and SGLang parity gates (chapter 18, chapter 19)

TorchTitan's TPU onboarding skill uses the same idea for every change to a training recipe and calls it the change's numerics class: bit-identical (loss and gradient norm equal to the recorded oracle at every logged step of a run of at least 10 steps), rounding-order (float32 round-off from tiles, fusion or reduction order: fine for speed, judged on a reference trajectory) and semantic (a bf16 gradient reduce, dropped tokens, another load balancer: a separate, labelled recipe, never a tuning lever). The useful discipline is to write the class down before you run the check. If a change you classed as bit-identical produces a difference in the seventh digit, that is a bug, however small the difference looks; chapter 11's worked problem 4 turns on exactly that.

The levels also order the checks. A cheap elementwise check on one layer finds a bug in minutes and points at the layer; a loss curve over a thousand steps finds it in hours and points nowhere. Use the lowest level that can see the change, and the higher levels to confirm that nothing below them was missed.

Building a reference

A parity check is a comparison, and its value depends on what you compare against. A reference has to compute the intended function, run with the same weights and inputs, and be independent of the code under test.

CPU float32 is the default reference. The TorchTPU precision guide's parity procedure runs the same layer or submodule on the CPU and the TPU with synchronized weights (load_state_dict) and identical inputs, then compares outputs and, after loss.backward(), gradients. TorchTitan's onboarding skill makes this the one test that matters for a new model: a tiny configuration in float32 (hidden size 128, two layers that cover every layer type, a vocabulary of 2048, sequence 16, batch 2), the same weights loaded through the model's state-dict adapter with no missing and no unexpected keys, one forward and one backward, and logits, loss and every parameter gradient compared. Two details from that skill are easy to miss. First, perturb parameters that are initialized to one (norm weights, learned scales) with \(1 + 0.1 \cdot \text{randn}\), because at their default a dropped multiply is invisible. Second, Module.to(device) unties tied weights; re-tie them after the move and assert that they are the same object, or the reference and the candidate are different models.

Matmul precision decides what the comparison can see. At TorchTPU's default, a float32 matmul is one bf16 pass, and the onboarding skill reports that the comparison then measures about \(10^{-2}\): for OLMo 2, logits differed by \(1.6 \times 10^{-2}\) at most and the gradients' relative L2 error was \(1.85 \times 10^{-2}\) against a bound of \(2 \times 10^{-2}\), which leaves no margin for a real bug. Under torch.set_float32_matmul_precision("highest"), restored afterwards, the same comparison measures about \(10^{-6}\) and the bounds can be tight. Run reference-parity tests at "highest" unless an op refuses it: the skill records that libtpu 0.0.48 rejects HIGHEST for the bf16 ragged dot behind torch._grouped_mm, so an MoE test scopes default precision to the expert path only.

A GPU run is a reference for higher levels, not for the last bits. PyTorch on CUDA defaults to "highest" (pure float32) and TorchTPU to "medium" (one bf16 pass), so a float32 model differs between the two in the third or fourth digit before any bug enters (chapter 6). Google's Hugging Face coverage pipeline compares TPU against a GPU baseline at the model level instead: a causal LLM passes if TPU and baseline perplexity differ by at most 0.10 relative, and other models pass on a relative MSE of at most 0.10 (MSE divided by the baseline's variance plus \(10^{-7}\)), or an absolute MSE under 0.05 for near-constant outputs. That is the right shape of check for a GPU reference: a statistical one.

Eager against compiled checks the compiler, not the model. The FLUX case study compiles its fused RoPE function and asserts that the result matches eager execution with torch.testing.assert_close at default tolerances. Useful, but both sides share the model code, so a wrong formula passes. Pair it with a reference that is independent.

A golden dump, when the reference cannot run in your process. For a model ported from Megatron, MaxText or custom code, the onboarding skill writes a small script next to the test that runs the reference once and saves one file: configuration, seed, tokens and positions, the reference state dict in its own key names, logits, loss, every gradient, and provenance (repository, commit, framework version, device, dtype policy). The test loads that file and runs the same comparison without importing the reference framework. Regenerate it when the reference moves, and say so in the commit.

An unverified reference is not a weak pass

The TPU Agent Suite's compare_parity.py returns three verdicts, not two. UNVERIFIED means the model had no independent plain-PyTorch path, so both sides ran the same rewritten code; the numbers cannot catch an error in the rewrite. Treat it as "not checked" and build an independent reference. The same applies to a CPU-only laptop run of a CPU-versus-TPU helper: with no TPU it compares the CPU with itself, which tests the plumbing and nothing else.

Two more rules apply to every reference. Compare like with like: bf16 against bf16, or float32 under Precision.HIGHEST against float32; comparing bf16 against float32 measures quantization. And when you compare two training runs op by op, both must use the same dtype and the same seed: TorchTitan's numerics debugging skill matches ops between runs by shape and a float64 L1 norm, and a precision change makes every row diverge.

Choosing tolerances

A tolerance is a claim: "a correct implementation differs from the reference by at most this much, and a broken one by more." Both halves need evidence. The figure collects the bounds that PyTorch, TorchTitan's onboarding skill and the TPU Agent Suite use, by dtype and by check, with the errors they measured against them.

A log-scale chart of error bounds from 1e-7 to 1, one row per check, grouped. Elementwise, like with like: float32 rtol 1.3e-6, float16 rtol 0.001, bfloat16 rtol 0.016. Model vs reference under "highest": loss rtol 1e-5, logits rtol 1e-4, gradients relative L2 1e-4. Model vs reference at default precision: loss rtol 0.001, logits rtol 0.01, gradients relative L2 0.02 with a green measured dot just under it at 0.0185. Training steps: 3-step loss relative bound 1e-4 with green measured dots at 1.4e-5 and 2.9e-5 and orange control diamonds at 0.014 and 0.027. bf16 candidate vs fp32 reference: module peak relative bound 0.05 with green dots at 0.0292 and 0.0309 and an orange diamond at 0.1085. A note under the axis says only the relative bound, rtol, is drawn and that absolute bounds, atol, are in the chapter's tables.

Read each row from the left: a check passes while its error stays left of the tick. The green dots are clean runs and the orange diamonds are deliberate faults or controls. The gradient row at default precision has almost no margin, which is why the reference test runs at "highest". The bottom row shows the floor of a cross-dtype check: device noise near 3%, a 10% bug at 10.85%.

Elementwise checks: start from the dtype

torch.testing.assert_close picks rtol and atol from the dtype, and the TorchTPU guide tells you to start there and relax them only where reduced-precision accumulation explains it:

dtype rtol atol
torch.float32 1.3e-6 1e-5
torch.bfloat16 1.6e-2 1e-5
torch.float16 1e-3 1e-5

An element passes when \(|out - ref| \le atol + rtol \cdot |ref|\). The companion code reports the worst element's ratio of the two sides as tol_ratio: allclose holds exactly when tol_ratio is at most 1, and the number says by how much a check passes or fails, on one scale for every layer.

Read a failure by its pattern, as the TorchTPU guide describes: many mismatched elements with small absolute differences point to rounding or accumulation order; a few large ones, or a large greatest absolute difference, point to a logic bug, and the reported index tells you where. Do not read max_rel alone. Near a zero reference, a relative difference is huge for any rounding at all: the companion's first check passes float32 allclose with a max_rel of \(6.1 \times 10^{-3}\), because that element's reference is tiny and atol covers it.

Contractions: scale by the inputs

Chapter 6 derived the bound for a matmul whose inputs are rounded with unit roundoff \(u\) and summed in float32: \(|C_{ij} - \hat C_{ij}| \le (2u + K \cdot 2^{-24}) \sum_k |A_{ik}||B_{kj}|\). The scale is \(|A||B|\), not \(|C|\), so a fixed rtol fails on outputs that cancelled to near zero while a bound scaled by the inputs does not. Use it for single matmuls and convolutions; for a whole model, use the model-level bounds below.

Model against reference: logits, loss, gradients

TorchTitan's onboarding skill states the bounds it holds a new model to, and they depend on the matmul precision of the test:

Compared "highest" (dense; OLMo 2) Default precision, dense (Gemma 4) Default precision, MoE (Gemma 4)
Logits atol 1e-4, rtol 1e-4 atol 5e-2, rtol 1e-2 atol 1e-1, rtol 2e-2
Loss atol 1e-5, rtol 1e-5 atol 5e-3, rtol 1e-3 atol 5e-3, rtol 2e-3
Gradients relative L2 at most 1e-4 per tensor relative L2 at most 2e-2 per tensor same

Gradients get a different metric on purpose. They span orders of magnitude, and an absolute tolerance that fits the large ones accepts a zeroed or sign-flipped small one. The skill bounds each gradient tensor by its relative L2 error, \(\lVert g - g_\text{ref} \rVert / \lVert g_\text{ref} \rVert\), with an absolute floor of \(10^{-6}\) only where the reference norm is below \(10^{-4}\). It also records a cautionary example: an earlier port used atol 8e-2, rtol 2e-2 elementwise for gradients, which passes a zeroed gradient whose entries are all below 0.08. The companion code reproduces that trap: a zeroed gradient of magnitude about \(10^{-3}\) passes allclose at atol 8e-2 and has a relative L2 error of 1.00, fifty times the bound.

A bf16 candidate against an fp32 reference: peak-relative error

Sometimes the comparison is deliberately cross-dtype: a bf16 serving path against the model's float32 PyTorch code on a CPU. Elementwise allclose at bf16 tolerance fails there on near-zero elements, which is the false alarm in the companion's second check (9.4% of elements mismatched, every one explained by quantization). The TPU Agent Suite's compare_parity.py uses a scale-aware metric instead: the largest absolute difference divided by the reference tensor's own peak magnitude, which means the same thing on logits of magnitude 10 and activations of magnitude 0.02. Its default bound is 5%, and the reason is a measurement: on mamba-130m, CPU bf16 against TPU v6e bf16 with identical code, device noise alone reached 2.92% at layer 23 and 3.09% on the logits, while a deliberate 10% error in one layer read 10.85%. The same comment states the floor honestly: a rewrite wrong by less than roughly 3% is indistinguishable from device noise at that probe size, and no threshold fixes that; compare more modules or widen the probe set. The suite deliberately ships no default absolute bound, because tensor scales in that one model ran from 8.1 at layer 0 to 341.9 at layer 23.

The companion's parity report

parity_report(ref, out, dtype) in code/ch23_correctness/parity.py returns every number above, so one call answers "did it pass" and "how should I read it":

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
$ python code/ch23_correctness/parity.py --cpu-smoke   (excerpt)
1. Like with like: float32 vs float32, summation order changed (expect PASS)
   allclose=True   mismatched 0/16384 (0.0%)  max_abs=2.38e-06  max_rel=6.11e-03  tol_ratio=0.17  peak_rel=6.00e-07 ...
2. bf16 candidate vs float32 reference at bf16 tolerance (a false alarm)
   allclose=False  mismatched 1539/16384 (9.4%)  max_abs=1.34e-02  max_rel=1.47e+01  tol_ratio=2.3e+02  peak_rel=3.37e-03 ...
3. A real bug: the weight used transposed (expect FAIL on every measure)
   allclose=False  mismatched 16384/16384 (100.0%)  max_abs=6.54e+00  max_rel=3.39e+04  tol_ratio=5.1e+05  peak_rel=1.65e+00 ...

Compare the three rows: the false alarm fails on 9% of elements with a peak-relative error of 0.34%; the bug fails on every element with a peak-relative error of 165%. Whatever the tolerance, record the measured error next to it, as the onboarding skill requires in every pull request. A bound with no measurement beside it cannot be reviewed.

Finding the first divergent layer

When a model's output fails parity, the output tells you little about where. Capture every layer's output on both sides, compare them in execution order, and open the first one that fails. The companion bisect_demo.py does this on a 12-block residual MLP: the reference is the model in float32 on the CPU, and a bug is injected by multiplying block 7's fc1 weight by 1.10, the same size of fault the TPU Agent Suite's compare_parity.py is calibrated against. Forward hooks record each block's output.

An animation in eleven frames. Frames 1 to 3 build a bar chart of peak relative error per block for a bf16 candidate against a float32 reference: bars grow from 0.54% at block 0 to 1.04% at block 8, all under a dashed 5% bound. Frame 4 adds the bug at block 7: orange bars of 3.9%, 3.6%, 3.1%, 2.9%, 3.0% and 3.7% from block 7 to the head, all still under 5%; the caption says the residual dilutes it. Frame 5 shows module rows inside block 7: norm 1.3%, fc1 10.2%, act 11.1%, fc2 13.7% and block out 3.9%, with fc1 the first over 5%. Frame 6 switches to a float32 candidate with reordered sums on a log scale of tolerance ratio: clean bars grow from 0.04 to 0.12 under a limit of 1. Frame 7 adds the bug: block 7 and every later row near 1e4. Frames 8 to 10 are bisection probes with unprobed rows shown as question marks: block 6 passes, block 9 fails, block 7 fails. Frame 11 reads first divergent layer: block 7, 3 capture runs instead of 13.

Watch the clean bars grow: every layer adds its own rounding to what it received, so a deep model's last layers sit higher than its first, with no bug anywhere. Then watch the bug almost disappear at the block level in bf16, and stand out by four orders of magnitude in the like-with-like float32 comparison.

Error accumulates; bugs can dilute

In a clean run, each layer's output carries the rounding of every layer before it. In the demo, the bf16 candidate's peak-relative error grows from 0.54% at block 0 to 1.04% at block 8, and the float32 candidate's tol_ratio from 0.04 to 0.12. A tolerance that fits the first layer can fail the last one of a deeper model with no bug at all, which is one reason per-layer bounds should come from a measured clean run of the same depth.

The bug teaches the opposite lesson. In the bf16 comparison, block 7's output reads 3.89% and the head 3.70%: under the 5% bound. The fault is in the MLP branch, and the residual connection adds that branch to a stream that is much larger, so a 10% error in fc1 becomes a 4% error in the block's output. A block-level gate passes, and so does an end-to-end check on the head. Only finer rows catch it:

$ python code/ch23_correctness/bisect_demo.py --cpu-smoke   (excerpt)
4. Module rows of block 7 (bf16 vs fp32, first breach in execution order)
   blocks.7.norm    clean   1.31%   bug   1.31%
   blocks.7.fc1     clean   0.74%   bug  10.23%   <- breach
   blocks.7.act     clean   0.82%   bug  11.11%   <- breach
   blocks.7.fc2     clean   0.84%   bug  13.72%   <- breach
   blocks.7         clean   0.93%   bug   3.89%
   first_divergent_layer over 63 module rows: clean None, bug 37 (blocks.7.fc1)

The largest row is fc2, downstream of the fault, because errors grow as they flow forward. Read the rows in execution order and open the first breach, which is fc1. This is why the TPU Agent Suite's parity capture hooks individual modules; TPU Agent Suite: Onboard, Profile and Tune PyTorch on Cloud TPU shows the same dilution (2.23% at the block output for a 10% fc1 fault).

first_divergent_layer(ref_acts, out_acts, dtype) returns that index. By default it applies elementwise allclose at the dtype's tolerance, which suits like-with-like comparisons; pass peak_tol=0.05 for a bf16 candidate against a float32 reference. A shape mismatch, a NaN on one side only or a missing layer counts as a divergence: compare_parity.py makes the same point about shapes, that a cropping comparison turns a real divergence into a pass.

Bisection when captures are expensive

Capturing every activation of a large model costs memory and time. If each probe is a run that captures one layer, a binary search finds the first failing layer in about \(\log_2 n\) runs: probe the middle; if it fails, the first failure is there or earlier; if it passes, it is later. In the demo's float32 comparison, bisect_layers probes blocks 6, 9 and 7 and finds block 7 in 3 runs instead of 13.

Binary search is valid only if a failure persists downstream once it starts. That holds in the like-with-like float32 comparison, where the bug is thousands of times the tolerance at every later row. It fails in the bf16 comparison, where the rows after the bug drop back under the bound: a probe at block 9 would pass, and the search would wander off. So the rule is: bisect with a tight like-with-like comparison; with a loose cross-dtype one, capture every row and take the first breach.

Per-op capture in TorchTitan

TorchTitan keeps the industrial version as a skill in its repository's .claude/skills directory, numerics_debugging, for runs that should agree bitwise or within float32 reduction-order noise: eager against aot_fx_trace, FSDP against no FSDP, before against after a refactor. It captures per-op activations on one designated step with torch.utils._debug_mode.DebugMode, computing statistics inline in float64 so tensors are not held, and writes one log per rank. A standard-library script diffs two logs into an HTML report in which each row pairs one op from each run and cells turn red, on a log scale, as a statistic diverges. The capture is run like this, once per side:

./run_train.sh --dump_folder ./outputs/run_A --training.steps 2 \
    --profiler.dump_numerics --profiler.profile_freq 2 \
    --debug.seed 42 --debug.deterministic --training.mixed_precision_param float32

The tracer is wired in by patching torchtitan for the capture run and reverting afterwards; the skill's references give the patch set and the manual overrides for ops that the automatic matcher pairs wrongly between eager and traced runs (activation-checkpoint recompute under a shorter module name, per-layer counter shifts, collectives that are renamed when lowered). Its hash options make the levels of agreement concrete: "norm" (an L1 norm in float64, which keeps tolerance semantics) or "hash_tensor" (a bit-exact XOR reduction of the bytes).

Training parity over N steps

A training step is a function of the weights, and the optimizer feeds each step's rounding into the next. That makes step 1 special and the later steps statistical.

Step 1 is the sharp check. It has no optimizer state, so a gap there is a bug. TorchTitan's onboarding bar expects eager, per-block compile and GraphTrainer to agree on step-1 loss within about \(10^{-4}\) on its debug model. Bound step 1 tightly, and check loss, gradient norm and gradients independently so that one failed check does not skip the others.

Later steps drift, and the drift is not a bug. AdamW amplifies round-off, and the gap grows with the step count: the skill records OLMo 2 eager against compile at \(1.6 \times 10^{-4}\) through step 10 and \(6.1 \times 10^{-3}\) by step 12, GPT-OSS at \(2.5 \times 10^{-3}\) by step 10, and the merged Muse Glimmer debug model at \(1.45 \times 10^{-2}\); a multi-step CPU-against-device test of that model saw gaps from 0.004 to 0.37 across seeds after two Adam steps, all amplified bf16 error. So a later-step bound comes from a measured clean run, and for a long run the skill judges the trajectory on post-warmup medians, "never a per-step 1e-4 bound over N steps". A short comparison can still be tight when both sides are float32: GraphTrainer against per-block compile on OLMo 2 agreed over 3 steps within a relative \(10^{-4}\), measured 0, \(2.9 \times 10^{-5}\) and \(1.4 \times 10^{-5}\), while a bf16-parameter MoE measured \(8.2 \times 10^{-4}\) over the same 3 steps; set the bound from the dtype you actually run.

Determinism is its own check. Two runs with --debug.seed=42 --debug.deterministic must give equal loss and gradient norm at every step: equal, not close. The skill insists on reading the values from the TensorBoard event file with every step present, because stdout prints 5 digits and a log that skipped steps compares equal on the steps it has.

The control must be able to move the metric. The onboarding skill's control for a 3-step loss comparison is a schedule change: warmup 3 steps instead of 2 moved OLMo 2's loss by \(1.4 \times 10^{-2}\) and \(2.7 \times 10^{-2}\), far outside the bound. Scaling max_norm or the gradients is not a control, because AdamW's update is invariant to gradient scale and stays inside any bound. That invariance is also why chapter 14's summed-instead-of-averaged gradients can look almost right for a while: the gradient norm and clipping reveal it, the loss curve barely does. The companion reproduces both halves on a laptop:

5. Loss-curve parity over 6 AdamW steps (step 0 tight, later steps looser)
   reordered sums: rel diff 0.0e+00 1.1e-07 0.0e+00 6.9e-08 1.5e-07 0.0e+00  -> True
   warmup 3 not 2: rel diff 0.0e+00 3.0e-02 7.0e-02 4.5e-02 3.3e-02 3.2e-02  -> False (steps [1, 2, 3, 4, 5])

Across seeds, compare distributions. For reinforcement learning or anything sampled, a single curve is one draw. Chapter 15 followed the Miles team, who ran two seeds on TPU and two on GPU and judged the reward curves equal "within seed-to-seed variation". Run more than one seed before you call two curves different.

Serving parity

A server adds two things a training test does not have: generation, where one changed token changes everything after it, and a model that you may change on purpose (quantization, a new attention kernel, speculative decoding). Serving parity therefore has three layers.

Greedy tokens. With temperature: 0, a correct build returns the same tokens as a trusted one, and chapter 18's client checks exactly that (parity PASS: 4/4 prompts identical). Exact agreement catches a wrong checkpoint, a broken kernel or a quantization that changed the model. It also fails on two correct builds whenever one position is a near tie and the two numeric paths round it differently.

Logprobs with a tie rule. The verify_cpu_vs_tpu_serving_parity gate in the code that accompanies vLLM and SGLang on TPU: Production Serving with llm-d 1.0 (source) sends a fixed prompt suite to /v1/completions with temperature: 0 and logprobs: k, runs the same prompts through a CPU PyTorch reference, and walks the greedy tokens. On agreeing positions it checks the chosen token's logprob within logprob_atol (default 0.1) and the overlap of the top-k candidates (mean at least 0.6). At the first disagreement it asks whether the reference itself was near a tie: if the reference's top-1 minus top-2 logprob margin is under the tie gap, the flip is rounding and comparison of that prompt stops; otherwise it is a real mismatch. The tie gap is measured, not chosen: twice the RMS logprob difference on agreeing positions, with a floor of \(10^{-3}\), the rule in the TPU Agent Suite's compare_parity.py. The factor of 2 is there because two logits drifting in opposite directions can bridge about twice the typical difference, and the RMS, not the maximum, is used so that one badly wrong element cannot inflate the threshold meant to catch it. One more guard closes the loop: if the noise alone pushes the tie gap above max_tie_gap (default 0.05), the gate fails, because a systematic error inflates the noise and a gap that wide would excuse real mismatches. In that code's smoke run, a bf16 endpoint against a float32 reference passed (57 tokens compared, largest logprob difference 0.0148, top-k overlap 0.98, tie gap 0.0099) and the same endpoint with a 10% LM-head scale bug failed (largest difference 0.1238).

compare_parity.py applies the tie rule to teacher-forced logits: both sides run one forward pass over the same fixed token sequence, so every position is compared on the same inputs and one flipped token cannot cascade. The companion's top1_agreement does the same:

6. Greedy-token parity on teacher-forced logits (tie rule from compare_parity.py)
   bf16 head: 47/48 agree, ties 1, real 0, tie gap 0.0058 -> True
   sign bug:  9/48 agree, real disagreements 36 -> False

Task metrics. A change that alters the model on purpose needs an accuracy evaluation as well. vLLM-TorchTPU's CI runs check_regression.py --mode eval against the same live server as its performance check, comparing lm_eval accuracy (mmlu_llama and mmlu_pro by exact_match; humaneval_plus_tpu and mbpp_plus_tpu by pass@1, nightly) with a stored baseline. The allowed drop is 1.5 percentage points by default. Where the baseline carries a standard error, the gate becomes a one-sided 95% test on the difference of two independent runs:

\[ \text{allowed drop} = \max\left(\text{tolerance},\; 1.645 \sqrt{se_\text{baseline}^2 + se_\text{run}^2}\right) \]

If only the baseline records a standard error, the combined error is \(\sqrt{2}\, se_\text{baseline}\); if only the run does, it is \(se_\text{run}\) and the baseline is treated as exact. The guide explains why both errors are combined: using one raw standard error would still fail about 24% of clean reruns on a small benchmark such as humaneval_plus_tpu (164 problems). For a new baseline whose run-to-run spread is not yet known, EVAL_SOFT_FAIL=1 turns an eval regression into a warning while performance regressions still fail. The vLLM-TorchTPU coding guidance makes evaluation a rule: any change that can affect output, accuracy or serving behaviour ships with evaluation results in its pull request, with before-and-after evaluation on the same machine for numerics.

Parity gates in CI

A gate is a check that blocks a change. The figure below orders the gates from cheapest to most expensive. Before any of them runs, write down the change's numerics class, and give each gate a negative control that runs in the same test and must fail. Then each gate that applies to the change runs only when the one before it passed: training parity for a change that trains, serving parity for one that serves, and an accuracy evaluation for a change that alters the model on purpose and, in vLLM-TorchTPU, for any change that can affect output. Each failure sends you to the bisection of the previous section rather than to a wider tolerance.

A ladder read from top to bottom. A dark pill, A change, has an arrow down to a grey card, Write down the numerics class, bit-identical, rounding-order or semantic, and an arrow down to a grey card, Prove each gate can fail, it must fail on a negative control. An arrow leads down into five white numbered gate cards, each joined to the next by an arrow down. Gate 1: Op or kernel parity, assert_close at the dtype's tolerance. Gate 2: Model vs reference at "highest", logits, loss and every gradient. Gate 3: Training steps, with the tag if it trains, step 1 tight, later steps vs measured drift. Gate 4: Serving parity, with the tag if it serves, greedy tokens, logprobs with the tie rule. Gate 5: Accuracy eval, with the tag if it alters the model, drop within max(1.5 pp, 1.645 × combined se). An arrow from gate 5 leads down to a green card, Ship, with bounds and measured errors in the PR. From the right side of every gate a short orange line joins one orange rail, labelled fail, that runs down the right and ends with an arrow in an orange card at the bottom right, Bisect, open the first divergent layer.

A change here is a new kernel, a flag, a port or a quantization. Gates run from cheapest to most expensive, each only when the one above it passed and only for the kind of change its tag names; every failure goes to bisection, never to a wider tolerance.

The vLLM-TorchTPU coding guidance and TorchTitan's onboarding skill add rules about the gates themselves, and most of them are about tests that pass for the wrong reason:

  • A gate must be able to fail. The vLLM-TorchTPU coding guidance: a regression test must fail without the fix; if reverting the fix does not turn the test red, the test is not testing the fix. TorchTitan's onboarding skill puts the negative control inside the parity test: feed the comparison the reference gradients zeroed, and again sign-flipped, and assert that it fails both times. "A bound that cannot reject those is not a bound." For feature tests, remove the feature and assert that the output moves (drop the document mask and require the attention output to move by more than 10%).
  • Run on hardware that exercises the code, and make sure the test actually runs there. vLLM-TorchTPU routes tests with pytest markers: unmarked tests run in CPU pods with JAX_PLATFORMS=cpu, tpu_test on a v7x 1x1x1 slice and multichip on 2x2x1. Its guidance warns that green CI is not the same as exercised code: check the pipeline's ignore lists and markers. TorchTitan's CI has a related trap: a plain TestCase with skipUnless(<detect tpu>) is classified onto the CPU shard and skips on every run, green.
  • Use the smallest hardware that exercises the behaviour. Coverage that exists only on large configurations does not count as coverage.
  • Keep timing out of correctness tests. Correctness belongs in pytest, performance in the benchmark harness; a timing assert in a unit test produces flaky failures (chapter 24 builds the performance gates).
  • Make accuracy harnesses generic. Model, configuration and threshold are arguments, not constants hard-coded per model.
  • Fail loudly in code that can be silently wrong. Assert untested assumptions, especially in quantization and kernels, "where the failure mode is silently wrong numbers rather than a crash", and do not hide a dtype mismatch with a cast: find where the dtypes diverged.

False alarms and real bugs

Most parity failures on a TPU are expected precision effects, and most real bugs produce plausible output. The table pairs the common false alarms with the bugs that resemble them.

What you see Usually a false alarm when Usually a real bug when What to do
float32 outputs differ from CPU or GPU by about \(10^{-3}\) to \(10^{-2}\) The TPU ran at the default "medium" precision (one bf16 pass) The difference survives "highest" Rerun the comparison at "highest" (chapter 6)
assert_close fails at bf16 tolerance on a few percent of elements One side is float32 (quantization), or the failing elements are near zero The peak-relative error is far above about 3%, or the 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 the summation order, or allow_excess_precision kept float32 intermediates The difference is large, or appears for a change classed bit-identical Check the flag; classify the change
A kernel test passes alone but the model differs slightly The whole program's layout changes reduction order; "an isolated kernel test is not bit-identity" The difference grows with depth faster than a clean run's Label it rounding-order and judge it with the model-level bounds
Loss matches at step 1 and drifts later Optimizer amplification of round-off (0.004 to 0.37 across seeds after two Adam steps for one debug model) Step 1 already differs, or the gradient norm differs by a constant factor such as world_size Bound step 1 tightly; compare post-warmup medians
Two runs of the same program differ TorchTitan's deterministic setting is off by default, and the TorchTPU guide notes non-determinism in accumulation over thousands of elements They differ with --debug.deterministic and the same seed Rerun deterministically and read every step from the event file
One greedy token differs, then the rest of the sequence The reference's top two logprobs were within the tie gap The reference margin was wide, or the logprob gap exceeds the tolerance on agreeing positions Apply the tie rule on teacher-forced logits
Everything passes, but the model trains worse A dropped multiply hidden by unit initialization; tied weights untied by .to(device); a packed batch without segment ids (loss normal, attention across documents); a sliding window off by one; a config override that built the wrong shape Perturb unit scales, assert tied weights are the same object, assert per-layer patch counts and head counts

The last row is a list of bugs the onboarding skill's gotchas record as costing a previous port a day or more each. None of them fails a test written without them in mind, which is the argument for the reference-parity test's details: perturbed scales, tied-weight assertions, geometry that exercises every masking path, and a negative control.

Verifying the result

You have a trustworthy correctness result when a written parity report passes with tolerances you can trace to a published bound or a measurement, and a deliberately injected bug fails the same report. Run the companion first:

python code/ch23_correctness/parity.py --cpu-smoke        # tolerance arithmetic and every check type
python code/ch23_correctness/bisect_demo.py --cpu-smoke   # inject a bug, find its layer
pytest tests/ch23 -q

Both scripts end with cpu-smoke: OK, and the tests fail if the clean candidate fails, if the injected bug is not found at its layer, or if the bf16 dilution stops hiding it at block level. Then build the same evidence for your model:

  1. Write the report before you run it. For each check: what is compared (logits, loss, each gradient, module rows, greedy tokens, an eval task), the dtype and matmul precision of both sides, the metric (allclose, peak-relative, relative L2, logprob difference, accuracy drop), the bound and where it comes from, and the change's numerics class.
  2. Run it clean and record the measured numbers next to the bounds. A bound with no measured margin beside it (the OLMo 2 gradients at \(1.85 \times 10^{-2}\) against \(2 \times 10^{-2}\)) is a bound that cannot see a bug.
  3. Run the negative controls in the same test. Zeroed and sign-flipped gradients for the reference test; a scaled weight in one layer for the activation rows (as inject_bug does); a schedule change for the loss curve; a scaled LM head for the serving gate. Each must fail.
  4. On the TPU, run the companion's TPU paths. python code/ch23_correctness/parity.py compares a block's output and every parameter gradient in float32 under "highest" and in bf16 on both sides; python code/ch23_correctness/bisect_demo.py --bug-layer 7 repeats the demo with both candidates on the TPU. Record the numbers they print: your output is the record of how your TorchTPU version and TPU generation behave.
  5. Wire it into CI on the right hardware, marked so that it runs where the code runs, and confirm in the CI log that it ran, not that it was skipped.

Worked problems

Problem 1. A bf16 activation is compared with a bf16 reference at default tolerances. Element A has reference 0.25 and output 0.2504; element B has reference 0.0003 and output 0.0011. The tensor's peak magnitude is 3.2. Compute tol_ratio for each element, say whether allclose passes, and compute the tensor's peak-relative error if B is the largest absolute difference.

Answer

The bf16 defaults are rtol 1.6e-2 and atol 1e-5. A: bound \(10^{-5} + 0.016 \times 0.25 = 4.01 \times 10^{-3}\), difference \(4 \times 10^{-4}\), ratio 0.0998: passes. B: bound \(10^{-5} + 0.016 \times 0.0003 = 1.48 \times 10^{-5}\), difference \(8 \times 10^{-4}\), ratio 54: fails, so allclose fails. The peak-relative error is \(8 \times 10^{-4} / 3.2 = 2.5 \times 10^{-4}\), or 0.025%. One failing near-zero element with a tiny peak-relative error is the pattern of rounding, not of a bug; if this is like with like, check whether the failing elements are few and near zero, and whether the comparison should have been done at "highest" in float32 instead.

Problem 2. assert_close on a float32 model's logits, TPU at default precision against CPU float32, reports: mismatched elements 38%, greatest absolute difference 0.021, greatest relative difference 4.1. A second model reports: mismatched elements 0.4%, greatest absolute difference 3.7 at index (0, 17). Which one more likely holds a bug, and what is your next step for each?

Answer

The first is the signature of precision: a large fraction of small differences, at the scale (about \(10^{-2}\)) that one bf16 pass produces, with a huge relative difference that only means some reference logit was near zero. Rerun it at "highest"; if the difference drops to about \(10^{-6}\) (the onboarding skill's experience), the precision mode explained it. The second is the signature of a bug: few elements, one large difference, and an index to look at. Capture activations on both sides and find the first divergent layer; a logit 3.7 away at one vocabulary position suggests something position- or index-specific, such as a wrong embedding row, a mask, or a tied head that is no longer tied.

Problem 3. A model has 33 captured rows in a like-with-like float32 comparison, and the first failing row is 20. List the rows that bisect_layers probes and the number of capture runs. Then explain why the same search over the bf16-against-float32 rows of bisect_demo.py would be unsafe.

Answer

The first failing row starts somewhere in 0 to 32. Probe 16 passes, so it is in 17 to 32; probe 24 fails, so 17 to 24 (24 itself may be the first failure); probe 20 fails, so 17 to 20; probe 18 passes, so 19 to 20; probe 19 passes, so the answer is 20. Five runs instead of 33; bisect_layers(lambda i: i >= 20, 33, probes) returns 20 with probes [16, 24, 20, 18, 19]. The search assumes every row after the first failure also fails. In the bf16 comparison the bug reads 10.2% at fc1 but 3.9% at the block's output and 2.9% to 3.7% downstream, all under the 5% bound, so a probe after the bug can pass and send the search to the wrong half. With a loose cross-dtype tolerance, capture every row and take the first breach in execution order.

Problem 4. A pull request ports a dense model and asserts its gradients with torch.testing.assert_close(g, g_ref, atol=8e-2, rtol=2e-2) at default matmul precision, citing a previous port that used the same numbers. The test passes. Judge the test and propose the replacement, including what you would put in the pull request.

Answer

The test cannot reject a common bug: an elementwise atol of 0.08 accepts any gradient tensor whose entries are all below 0.08 in magnitude, including one that is zeroed or sign-flipped (the onboarding skill names this exact bound as one not to copy). Replace it with a relative L2 bound per gradient tensor, \(\lVert g - g_\text{ref} \rVert / \lVert g_\text{ref} \rVert\), with an absolute floor only for tensors whose reference norm is below \(10^{-4}\). Run the test under torch.set_float32_matmul_precision("highest") (restored in tearDown) so the bound can be \(10^{-4}\) instead of \(2 \times 10^{-2}\), scoping default precision to any op that rejects HIGHEST. Add the negative control in the same test: zeroed and sign-flipped reference gradients must fail. In the pull request, record each bound with the measured error beside it.

Problem 5. A serving parity run reports, for one prompt, a token disagreement at position 9 where the reference's top-1 minus top-2 logprob margin is 0.004. The RMS logprob difference on agreeing positions is (a) 0.003, or (b) 0.03. With max_tie_gap = 0.05, decide the verdict in each case and explain what (b) suggests.

Answer

The tie gap is \(\max(10^{-3}, 2 \times \text{RMS})\). (a) Tie gap 0.006; the margin 0.004 is under it, so the flip counts as rounding, comparison of that prompt stops there, and the gate can pass if the other checks do. (b) Tie gap 0.06, which excuses the flip, but 0.06 exceeds max_tie_gap = 0.05, so the gate fails on the noise check. Logprobs that differ by 0.03 RMS on positions where the tokens agree are not rounding noise between two correct builds (the gate's clean bf16 smoke run had a largest difference of 0.0148); a systematic error such as a scaled LM head or a wrong softmax temperature inflates the noise, and a tie gap that wide would excuse real mismatches. Bisect the model before shipping.

Problem 6. A quantization change is evaluated on mmlu_pro. The baseline scored 62.0% with a standard error of 1.2 points; the run scored 60.1% with a standard error of 1.3 points. Does check_regression.py --mode eval pass it at the default tolerance? Would it pass if neither side recorded a standard error? Is passing enough to ship?

Answer

The drop is 1.9 points. With both standard errors, the allowed drop is \(\max(1.5, 1.645 \sqrt{1.2^2 + 1.3^2}) = \max(1.5, 1.645 \times 1.769) = 2.91\) points, so it passes. With neither, the flat 1.5-point tolerance applies and a 1.9-point drop fails. Passing says the drop is within what two runs of the same model could show at 95% one-sided confidence; it does not say the model is unchanged. Before shipping, also require the cheaper gates: greedy-token and logprob parity with the tie rule against the unquantized model, so that a broken kernel is not hidden inside evaluation noise, and the before-and-after evaluation on the same machine that the coding guidance asks for.

Problem 7. Critique this CI gate for a new fused attention kernel: a test class derived from unittest.TestCase with @skipUnless(tpu_present()); it runs a 2-layer model on random inputs at default precision and asserts allclose(logits, ref_logits, atol=1e-1); the PR description says "parity test added, CI green".

Answer

Four problems. (1) It may never run: in TorchTitan's CI a plain TestCase with a TPU-detecting skip is classified onto the CPU shard and skips on every run, green; derive from the device-test base class and confirm in the log that the test executed. (2) An end-to-end logits check can pass a broken layer, because residual connections dilute a layer's error (a 10% fc1 fault reads under 4% at the block's output in this chapter's demo); compare the kernel's own output, or module rows, against the path it replaces. (3) There is no negative control: disable the kernel's distinguishing feature (the mask, the cap, the window) and assert that the output moves, or the test cannot tell a kernel that ignores the feature from one that implements it. (4) The bound has no source and no measured error beside it; at default precision the comparison measures about \(10^{-2}\) anyway. Run at "highest" where the op allows it, state the bound, record the measured error, and write "parity test added" as "bounds X, measured Y, control Z".

Quick questions

  1. Name the four levels of agreement a TPU result can owe its reference, and give a change that owes each one.
  2. Why does a reference-parity test perturb unit-initialized parameters, and what does Module.to(device) do to tied weights?
  3. What does a comparison at default matmul precision measure, according to the onboarding skill, and how does "highest" change that?
  4. Why are gradients bounded by relative L2 per tensor rather than by an elementwise atol?
  5. What is peak-relative error, what bound does compare_parity.py use for a bf16 candidate against an fp32 reference, and what measurement justifies it?
  6. Why can an end-to-end check pass a broken layer, and which row should you open first when several fail?
  7. When is binary search over layers valid, and when must you capture every row?
  8. How is the serving tie gap computed, and why does the gate also fail when the tie gap is too large?

Key takeaways

  • State the level of agreement before you check: bitwise for changes that cannot alter the math, a dtype tolerance for rounding changes, statistics for training curves and sampling, task metrics for changes that alter the model on purpose.
  • The reference must be independent of the code under test and compared like with like; run reference-parity tests at "highest", where the comparison measures about \(10^{-6}\) instead of \(10^{-2}\).
  • Take tolerances from the dtype (assert_close defaults), the operation (bounds scaled by \(|A||B|\) for contractions), the metric (relative L2 for gradients, peak-relative for cross-dtype rows) and a measured clean run, and record the measured error next to every bound.
  • Error accumulates with depth in a clean run, and residual connections dilute a layer's bug; capture module rows and open the first breach in execution order. Bisect only with a tight like-with-like comparison.
  • Bound training step 1 tightly; judge later steps against measured drift or post-warmup medians, and demand bit equality only for determinism repeats.
  • Serving parity is greedy tokens, logprobs with a measured tie gap, and an accuracy gate of \(\max(1.5\text{pp}, 1.645 \sqrt{se_b^2 + se_r^2})\).
  • A gate that cannot fail proves nothing: put a negative control in every parity test, and confirm in CI that the test ran on hardware that exercises the code.

References