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.
#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.
#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.
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)#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, , 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, , 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.
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.
#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.
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 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.
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 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.
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 is 8, so rounds back to . Then , while . 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.
FP32 vs BF16/FP16
The format sets the scale of the noise. Near a logit of 12, neighbouring values are 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.