Highlights

Contents

Part VII
07

Proving the Implementation Is Correct

Plausible text can hide an incorrect implementation. Parity compares the underlying computation. Hold inputs and settings fixed, localize the first divergence, and distinguish rounding from convention errors.

YOU ARE HEREmessageschat templatetokenizertoken IDsconfig.jsonmodel.safetensorsint8 / int4 weightsOUR DECODER, REBUILT FROM THE CONFIGprefilldecodeattention kernelKV cacheparity checkvs referenceLM head → logitssamplingdetokenizereply textnext token

#Section 35Why Good-Looking Text Is Not Enough

A wrong RoPE convention can still produce a correct familiar answer. Plausible text is a weak test because implementation errors may appear only at longer positions or harder inputs.

Plausible output can hide implementation bugs because fluency is the skill the model learned most thoroughly, and the last one to break. Three things make eyeballing hopeless. Sampling introduces randomness: two runs of a correct model differ, so a difference between yours and the reference proves nothing. Small numerical errors compound: an error in layer 3 is carried by the residual stream through 25 more layers, and in generation one changed token changes every token after it. And a wrong model and a right one can produce identical text for dozens of prompts and then diverge on the next.

So we need deterministic validation: the same inputs, no randomness, a reference we trust, and a numerical comparison with a threshold decided in advance.

SAME ANSWER, DIFFERENT MODEL (ILLUSTRATIVE)correct port"The capital of France is Paris."positionmax |logit diff|RoPE pairing swapped"The capital of France is Paris."positionmax |logit diff|the text agrees; the numbers do not
Figure 4.47Two models answer the same short prompt fluently. One has the RoPE pairing convention swapped. Only the numbers underneath, compared position by position, tell them apart. (Illustrative.)

#Section 36Reference Implementation

A reference implementation is a second, trusted way to compute the same function. For Qwen3 the obvious one is Hugging Face’s transformers implementation, which the Qwen team contributed and which produced the published results. The comparison is only meaningful if everything except the code under test is held identical.

Same checkpoint: both models load the identical model.safetensors, not two downloads of possibly different revisions. Same tokenizer and same input tokens: tokenize once and feed both models the same tensor of IDs, so tokenization differences cannot hide in the comparison (Part VIII tests the tokenizer separately). Same dtype where possible: for the tightest comparison run both in fp32, where rounding noise is tiny; then repeat in bf16 with a looser tolerance. And the reference Hugging Face model should use its simplest attention path (attn_implementation="eager") so a kernel choice is not a variable.

python
ref = AutoModelForCausalLM.from_pretrained(
    "Qwen/Qwen3-0.6B", torch_dtype=torch.float32, attn_implementation="eager").eval()
ours = load_ours("model.safetensors", dtype=torch.float32).eval()
ids = torch.tensor([prompt_ids])                       # (1, 26), tokenized once
with torch.inference_mode():
    a = ref(ids).logits                                # (1, 26, 151936)
    b = ours(ids)                                      # (1, 26, 151936)
ONE CHECKPOINT, ONE TENSOR OF IDS, TWO IMPLEMENTATIONS, ONE COMPARISONmodel.safetensorstoken IDs(1, 26)reference: HF Qwen3eager attention, fp32ours: rebuilt fromthe config, fp32a: (1, 26, 151936)b: (1, 26, 151936)max |a − b|mean |a − b|per positionargmax3,950,336 logits each, compared number by number
Figure 4.48The parity setup. One file of weights, one tensor of token IDs, two implementations, one comparison. Everything that is not the code under test is shared.

#Section 37Logit Parity

Logit parity compares raw scores under identical input. Text and probabilities can hide disagreement, so inspect the distribution before sampling.

The maximum absolute difference, max⁡i∣ai−bi∣\max_i |a_i - b_i|, catches any single badly wrong value, and is the main pass/fail number. The mean absolute difference tells you whether the error is everywhere (a systematic bug, or a dtype difference) or concentrated in a few places. The relative error, ∣ai−bi∣/∣ai∣|a_i - b_i| / |a_i|, puts differences on the scale of the values, though it explodes for logits near zero, so use it with care. Same argmax token checks that both models would pick the same next token at every position. And position-by-position comparison, the maximum difference per position rather than over the whole tensor, shows where in the sequence the error lives, which points straight at position bugs.

With numbers

Check the largest and average differences as well as winner agreement. A tiny error can still change the chosen token near a tie; the figure illustrates why the margin matters.

FIVE LOGITS AT ONE POSITION (ILLUSTRATIVE), DIFFERENCES ×1,000 BELOW14.81token A0.513.94token B1.49.25token C0.3-2.13token D0.77.69token E1.5margin 0.875slate: referenceorange: ours|a − b| × 1,000
Figure 4.49The five illustrative logits from the two implementations, side by side, with their differences magnified a thousand times below. The top token and the margin are what generation depends on.
python
d = (a - b).abs()                                   # (1, 26, 151936)
print("max", d.max().item(), "mean", d.mean().item())
print("per position", d.amax(-1).squeeze(0))        # (26,)
print("argmax equal", (a.argmax(-1) == b.argmax(-1)).all().item())

The per-position line is the one to look at first. A healthy implementation has differences of similar size at every position. A difference that is zero at position 0 and grows with position is the signature of a RoPE or position bug, because position 0 is not rotated at all. A difference that appears only at the last position points at the LM head or final norm path.

MAX |LOGIT DIFF| BY POSITION: THREE SIGNATURES (ILLUSTRATIVE)healthyposition 0 → 25RoPE or position bugposition 0 → 25weight or layer bugposition 0 → 25position 0 is never rotated, so a rotation bug starts at zero and grows
Figure 4.50Maximum logit difference by position, three illustrative cases. Flat and tiny: healthy. Zero at position 0 and growing: a RoPE or position bug. Large everywhere: a weight or layer bug.

#Section 38Layer-Level Debugging

When logit parity fails, the logits only tell you that something is wrong, not where. Layer-level debugging finds the first point at which the two models disagree. Both models compute the same sequence of intermediate tensors, so capture them in both and compare in order: the first mismatch is downstream of the bug and upstream of everything else.

The checkpoints, in the order data flows, are the embedding output, the hidden state after normalization, the Q/K/V tensors (before and after the QK norm and RoPE), the attention output (before and after o_proj), the residual stream after the attention add, the FFN output, the residual after the MLP add, and so on through the layers to the final hidden state after the last norm, and the LM logits.

python
acts = {}
def keep(name):
    return lambda mod, inp, out: acts.setdefault(name, out.detach().float())
for i, layer in enumerate(ref.model.layers):
    layer.self_attn.q_proj.register_forward_hook(keep(f"ref.{i}.q"))
    layer.mlp.register_forward_hook(keep(f"ref.{i}.mlp"))
# same names on our model, then compare in data-flow order:
for name in order:
    diff = (acts["ref." + name] - acts["ours." + name]).abs().max()
    print(f"{name:12s} {diff:.2e}")

Forward hooks capture a module's output without changing its code. For intermediate values that are not module outputs, such as qq after RoPE, add a temporary line that stores them in both implementations. Compare in the order of computation and stop at the first tensor whose difference jumps by orders of magnitude.

FIRST DIVERGENCE, LAYER 0, RoPE PAIRING SWAPPED (ILLUSTRATIVE VALUES)1e-81e-51e-31toleranceembed✓norm✓q, k, v✓q_norm✓afterRoPE✗attnout✗residual✗FFN✗logits✗the bug lives here; everything after is a consequence
Figure 4.51Bisecting a parity failure. Differences stay at rounding level through the embedding, norm and projections, then jump at q after RoPE: the bug is in the rotation, and everything after it is a consequence.

A useful trick is to compare on a tiny input first: one sequence of 4 or 5 tokens. Tensors are small enough to print and inspect by eye, and position-dependent bugs still show (they need at least two positions).

#Section 39Common Sources of Parity Failure

Most porting bugs come from a short list, and each has a place in the data flow where it first shows. The table is the order to check them in when Section 38's bisection points at a stage.

Bug First diverges at Signature
Wrong RoPE implementation (interleaved vs half-split, wrong base) q, k after RoPE zero at position 0, grows with position
Wrong position IDs q, k after RoPE fine in prefill, wrong in decode (Section 8)
Q/K/V shape errors (head_dim from width, view order) q, k, v usually a crash; sometimes a silent reshape
Head ordering attention output view(B, H, T, d) instead of view(B, T, H, d).transpose
GQA replication mistakes attention output .repeat instead of repeat_interleave
Incorrect normalization epsilon after norm tiny, larger for small-norm inputs
Incorrect weight transpose that projection square matrices load silently (Section 32)
Wrong activation (GELU for SiLU) FFN output everywhere, moderate
Wrong causal mask attention output position 0 fine, later positions see the future
Dtype differences everywhere, slightly uniform small noise, no pattern by position

Two of these deserve a picture. The head ordering bug comes from reshaping a (B,T,H⋅dh)(B, T, H \cdot d_h) projection into heads. The correct move is view(B, T, H, d_h).transpose(1, 2): split each token's 2,048 numbers into 16 consecutive chunks of 128, one per head. Writing view(B, H, T, d_h) directly produces the same shape, but it takes the flat memory in the wrong order, so each "head" receives a mix of different tokens' features. Nothing crashes.

SPLITTING (T = 3, H·d = 4) INTO 2 HEADS OF 2: COLOURS ARE TOKENSmemory of the projection output, row by rowt0h0t0h0t0h1t0h1t1h0t1h0t1h1t1h1t2h0t2h0t2h1t2h1view(T, H, d).transposehead 0t0h0t0h0t1h0t1h0t2h0t2h0head 1t0h1t0h1t1h1t1h1t2h1t2h1each head row is one tokenview(H, T, d)head 0t0h0t0h0t0h1t0h1t1h0t1h0head 1t1h1t1h1t2h0t2h0t2h1t2h1rows mix tokens and headssame shape, no error
Figure 4.52Splitting a projection into heads. The correct view cuts each token's row into 16 consecutive 128-wide chunks. Viewing straight to (B, H, T, d) has the same shape but scrambles tokens and heads together.

An incorrect epsilon matters most when the input norm is small. Ordinary large inputs can hide it, so include small-norm cases when testing normalization.

#Section 40Numerical Tolerance

Exact equality vs approximate equality

Two correct implementations almost never produce identical numbers, so exact equality is the wrong test, and approximate equality needs a threshold. The reason is floating-point rounding. Every addition rounds to the nearest representable number, and the rounding depends on the order of the additions. In fp32, the spacing between representable numbers near 10810^8 is 8, so 108+110^8 + 1 rounds back to 10810^8. Then (108+1)−108=0(10^8 + 1) - 10^8 = 0, while (108−108)+1=1(10^8 - 10^8) + 1 = 1. The same three numbers, added in two orders, give two answers. A matmul sums 1,024 products, and different kernels sum them in different orders, in different tile shapes, with different fused operations. Both answers are correct to within rounding; neither is "the" answer.

REPRESENTABLE NUMBERS BETWEEN 11.85 AND 12.15, AND WHERE 12.03 IS STOREDtrue value 12.03fp3212.03step 9.5e-7fp1612.03125step 0.0078125bf1612step 0.062511.8751212.125
Figure 4.53Representable values near a logit of 12 in three formats. In fp32 they are a millionth apart, in fp16 0.0078 apart, in bf16 0.0625 apart, so a bf16 logit can only be 11.9375, 12 or 12.0625 in this range.

FP32 vs BF16/FP16

The format sets the scale of the noise. Near a logit of 12, neighbouring values are 9.5×10−79.5 \times 10^{-7} apart in fp32, 0.0078 in fp16 and 0.0625 in bf16. A bf16 computation rounds every intermediate value through 28 layers at that coarseness, so two correct bf16 implementations can easily differ by a few bf16 steps in the logits. Comparing a bf16 model against an fp32 reference mixes both kinds of difference, which is why the tightest test runs both in fp32 first.

Choosing meaningful tolerances

Choose tolerances from correct reference comparisons under the actual dtype and kernels, then test whether they detect relevant mistakes. A threshold is evidence about a test, not a universal boundary between rounding and bugs.

Per-operation tolerance defaults are useful starting points. Validate the full network separately, since depth and kernel choices change accumulated rounding.

Top-token agreement

Because generation only uses the argmax (or the distribution's shape), top-token agreement is the second test: at every position, both models pick the same most likely token. It needs one exception. When the top two logits are closer together than the tolerance, a near-tie, rounding alone can swap them, so either answer is acceptable there. Count near-ties separately; a correct model has a handful in a long text, and a buggy one disagrees on clear winners.

#Section 41Generation Parity

Logit parity tests one forward pass. Generation parity tests the whole loop: the cache, the position bookkeeping and the stopping logic. It uses greedy decoding, always taking the argmax, because it is deterministic. Feed the same prompt as token IDs to our generator and to the reference’s generate(do_sample=False), run both for 100 or 200 tokens, and require the same generated tokens.

Two parities are worth separating. Cached vs uncached parity compares our own generator with and without its KV cache (Section 8), which isolates cache bugs from everything else. Reference vs custom parity compares our cached generator against Hugging Face’s, which tests everything at once.

Greedy runs can diverge at a near-tie without any bug: rounding swaps the top two tokens at step 37, and from then on the texts differ. When a divergence happens, look at the logits at that step. If the top two were within tolerance in both models, it is a near-tie; continue the test by forcing both models to take the reference’s token and keep comparing. If the reference’s winner beat the runner-up by a clear margin, it is a bug.

GREEDY GENERATION, OURS vs REFERENCE (ILLUSTRATIVE TOKENS AND LOGITS)refoursParis is the capital and most populous cityParis is the capital and largest city of=====logits at the split stepref: " most" 17.25 " largest" 17.21ours: " largest" 17.24 " most" 17.22gap 0.04 < tolerance: near-tie, not a bugforce the referencetoken, keep comparing
Figure 4.54Two greedy token streams, ours and the reference. They agree step for step; where they split, the logits at that step decide whether it was a near-tie (fine, force the reference token and continue) or a bug.