Dive into Deep Learning · §18.2
A Released Checkpoint in the Book’s Own Code
the block as a diff · a strict weight map · one tolerance rule at two precisions · localizing a failing port
The problem
Qwen3-0.6B is 596,049,920 numbers, released with the Transformers library. We load them into our own d2l.GPT code, and every shape fits. Two wrong constants, and how often the most likely next token is still that of Transformers:
| constant | wrong | right | top token kept |
|---|---|---|---|
| RoPE base | 10^4 | 10^6 | at 4 positions in 5 |
| RMSNorm \epsilon | 10^{-5} | 10^{-6} | at more than 99% |
Correct means the same as what, and to which precision?
Goals
d2l.GPT and turn the list into subclasses;Running example: Qwen3-0.6B (28 blocks of width 1,024, 16 heads of width 128, 8 key–value heads) on 32 prompts of 64 tokens.
Where this fits
| movement | section |
|---|---|
| open a checkpoint | Pretrained Models with Hugging Face |
| A Released Checkpoint in the Book’s Own Code | |
| measure it | Prompting and In-Context Learning |
| Scoring Language Models | |
| Evaluation Suites, Judges and Error Bars | |
| inside and outside | Interpretability |
| Models behind an API |
d2l.GPT, RoPE, the KV cache, GPT-2’s name map, safetensors headers.d2l.GPT built with the widths of Qwen3-0.6B, against layer 0 of the released file. Shapes read (outputs, inputs).
| role | d2l.GPT |
Qwen3-0.6B |
|---|---|---|
| query, key, value | W_qkv (2048, 1024) |
q_proj (2048, 1024), k_proj, v_proj (1024, 1024) |
| attention output | W_o (1024, 1024) |
o_proj (1024, 2048) |
| query, key norms | none | q_norm, k_norm (128) |
| FFN gate, up | W_g, W_1 (2731, 1024) |
gate_proj, up_proj (3072, 1024) |
| FFN down | W_2 (1024, 2731) |
down_proj (1024, 3072) |
| block norms | norm1, norm2 (1024) |
two norms (1024) |
Check: W_qkv and q_proj are both (2048, 1024). Do they fit?
No. W_qkv stacks 1,024 query rows on 512 key rows and 512 value rows. q_proj holds queries alone: 16 heads of width 128.
| setting | d2l.GPT |
Qwen3-0.6B |
|---|---|---|
| head width d_h | 1,024 / 16 = 64 | 128 |
| query width, 16 heads | 1,024 | 2,048 |
| projections | fused W_qkv |
q_proj, k_proj, v_proj |
| QK-norm | none | RMSNorm per head, before RoPE |
| RoPE base \theta | 10^4 | 10^6 |
| RoPE pairs | (2i, 2i+1) | (i, i + d_h/2) |
| FFN width | 2,731 | 3,072 |
| RMSNorm \epsilon | 10^{-5} | 10^{-6} |
| output layer | tied | tied; untied in Qwen3-8B |
Eight rows are settings of two subclasses. The RoPE pairs are a property of the stored weights, and the weight map handles them.
def qkv(self, X, offset=0, tables=None):
B, T, _ = X.shape
q = self.W_q(X).reshape(B, T, self.num_heads, self.head_dim)
k = self.W_k(X).reshape(B, T, self.num_kv_heads, self.head_dim)
v = self.W_v(X).reshape(B, T, self.num_kv_heads, self.head_dim)
q, k = self.q_norm(q), self.k_norm(k) # QK-norm, per head
q, k, v = (u.transpose(1, 2) for u in (q, k, v))
q, k = (d2l.rope(u, tables=tables) for u in (q, k))
return q, k, v # (B, heads, T, d_h)head_dim = 128 is an argument: 16 heads give queries of width 2,048.d2l.CausalAttention.max |logit difference| from d2l.GPT: 0.0e+00
forward_cached against forward: 3.6e-07
same greedy tokens: True
Qwen3GPT(d2l.GPT) replaces the parent’s CausalAttention, passes its SwiGLU through ffn_factory, sets \epsilon, and adds lm_head if untied.d2l.GPT in a Qwen3GPT without QK-norm and with the book’s constants. Line 1 compares the logits, line 2 the KV-cache path with the full forward pass.The subclass generalizes the book’s model: code written for d2l.GPT runs on it.
consumed 311 tensors, produced 310 keys
stored lm_head.weight equals the embedding (dropped): True
KeyError: not consumed: []
not produced: ['blks.3.attention.k_norm.weight (from model.layers.3.self_attn.k_norm.weight)']
k_norm was deleted), then a strict load.load_state_dict(strict=True) sees the model’s side only. A port without QK-norm loads strictly and leaves two tensors per layer in the file.
q_proj, k_proj and gains of q_norm, k_norm are permuted within each head.\mathbf{R}_t \mathbf{P} = \mathbf{P} \mathbf{R}'_t \;\Longrightarrow\; (\mathbf{R}_s \mathbf{P}\mathbf{q})^\top (\mathbf{R}_t \mathbf{P}\mathbf{k}) = (\mathbf{R}'_s \mathbf{q})^\top (\mathbf{R}'_t \mathbf{k})
\mathbf{R}_t, \mathbf{R}'_t: the book’s and Transformers’ rotation at position t. \mathbf{P}: (\mathbf{P}\mathbf{x})_{2i} = x_i, (\mathbf{P}\mathbf{x})_{2i+1} = x_{i + d_h/2}, with \mathbf{P}^\top \mathbf{P} = \mathbf{I}.
q_proj, k_proj and both gains permuted: scores agree with Transformers’ to fp32 rounding.QK-norm sits between projection and rotation, so its gain must move with the coordinates. Forgetting it changes no shape.
Check
d_h = 4. Transformers rotates the pairs (x_0, x_2) and (x_1, x_3); the book rotates coordinates (0, 1) and (2, 3). Which index idx reorders the rows of q_proj? Must v_proj be permuted as well?
idx = [0, 2, 1, 3]: row j of the port is row idx[j] of the file.v_proj and o_proj keep their order.e^b_\textrm{ours} \le 1.5\, e^b_\textrm{HF}, \qquad e^b = \textrm{mean}\,\bigl|\mathbf{L}^b - \mathbf{L}^{64}\bigr|
\mathbf{L}^{64}: logits of Transformers in fp64 (double precision), the fp64 reference. b: the working precision, 32 (fp32) or 16 (bf16). HF: Transformers with attention written out operation by operation (eager). Ours: the port.
fp32: e_HF 3.94e-06, e_ours 3.89e-06, ratio 0.99 [0.96, 1] passes
max |L_HF - L_64| 1.0e-04, max |L_ours - L_HF| 1.1e-04, deterministic: True
batch ratio, Transformers in 4s ratio, Transformers in the same batches
1 0.81 [0.79, 0.83] passes 0.98 [0.97, 1] passes
4 0.99 [0.96, 1] passes 0.99 [0.96, 1] passes
16 1.2 [1.2, 1.3] passes 0.97 [0.96, 0.99] passes
An interval over prompts says nothing about batching. Apply the rule with both programs batched alike.
One prompt of 4,096 tokens, and three ways to compute the frequency of RoPE pair i in the port. Ratio of the rule against two fp64 references:
| the port’s frequencies | Transformers in fp64 as it is (fp32 angles) | the same with fp64 angles |
|---|---|---|
| 1/\theta^{2i/d_h}, as Transformers | about 1, passes | about 1, passes |
| \theta^{-2i/d_h}, as the book | about 2, fails | about 1, passes |
| angles and tables in fp64 | about 4.5, fails | about 0.25, passes |
Compute a port’s constants with the expressions of the reference implementation, in its precision.
Mean logit error against the fp64 reference in bf16, 32 prompts:
| attention in Transformers | its error | the port’s error | ratio |
|---|---|---|---|
| written out (eager) | 0.05 | 0.035 | about 0.7, passes |
| fused kernel (SDPA, its default) | 0.04 | 0.035 | about 0.9, passes |
A tolerance fixed at 10^{-3} fits neither precision: the worst fp32 logit is 10 times inside it, the average bf16 logit 50 times outside.
Check
In fp32 no logit is off by more than about 10^{-4}. In bf16 the mean logit error is 0.05. At one step the two best tokens are 0.01 apart. In which precision can port and Transformers choose differently, and what follows for a greedy continuation of 64 tokens?
| model | next logits from | batches |
|---|---|---|
Qwen3GPT |
its KV cache | prompts of equal length |
| Transformers | its own cache, left padding, positions counted from the mask | any lengths |
any ids -> logits module |
full recomputation | prompts of equal length |
d2l.generate: strings in, one record per prompt out (text, token ids, log-probabilities, finish reason). One loop for both implementations, so a difference in text comes from the model and not from the sampler.
28 text prompts, 64 new tokens each, all through d2l.generate. Continuations identical to those of Transformers in fp32:
| model | identical | the others |
|---|---|---|
Transformers in fp32, its own generate |
28 of 28 | |
| port in fp32 | 28 of 28 | |
| port in bf16 | about half | half part within 20 tokens |
| Transformers in bf16 | about half | half part within 20 tokens |
Before suspecting a bug in a comparison of two bf16 runs, look at the gap.
Record four tensors per block, in execution order, in the port and in Transformers in fp64:
| capture point | tensor |
|---|---|
attn_out |
output of attention |
resid_mid |
residual stream after attention |
mlp_out |
output of the feed-forward network |
resid_post |
residual stream after the block |
A porter has no correct port for the floor. Transformers in fp32 serves: it stays within a factor of 2 of the correct port at every point.
Check
Every tensor is consumed and every shape fits. Where does each port first leave the correct one?
| bug | the one change |
|---|---|
| B1 | RoPE permutation skipped |
| B2 | RoPE base left at 10^4 |
| B3 | gate and up projections of every FFN swapped |
| B4 | layers taken in string order, so block 2 gets layer 10 |
| B5 | \epsilon = 10^{-5} in every norm |
B1, B2, B5: attn_out of block 0. B3: mlp_out of block 0. B4: attn_out of block 2, with blocks 0 and 1 exact to the last bit.
| port | diverges at block, point | error / floor | fp32 rule | bf16 rule | top token kept |
|---|---|---|---|---|---|
| correct | nowhere | passes | passes | 99.9% | |
| B1 | 0, attn_out |
10^6 | fails | fails | 1 in 3 |
| B2 | 0, attn_out |
10^5 | fails | fails | 4 in 5 |
| B3 | 0, mlp_out |
10^6 | fails | fails | never |
| B4 | 2, attn_out |
10^6 | fails | fails | 1 in 25 |
| B5 | 0, attn_out |
10^4 | fails | passes | 99.7% |
Check
RMSNorm divides by \sqrt{m + \epsilon}, with m the mean square of its input. Using \epsilon' = 10^{-5} for \epsilon = 10^{-6} changes the output by about (\epsilon' - \epsilon)/(2m). Evaluate this for the token embeddings, m = 7.3 \times 10^{-4}, and for the last block, m \approx 350. One rounding is 2^{-8} \approx 0.4\% in bf16 and 2^{-24} \approx 6 \times 10^{-8} in fp32.
Relative error of the residual stream against Transformers in fp64:
| port | after block 0 | after block 27 |
|---|---|---|
| correct, fp32 | 10^{-6} | 10^{-6} |
| B5 (wrong \epsilon), fp32 | 0.45% | 0.2% |
| correct, bf16 | 0.5% | 1% |
The error of a wrong \epsilon is one bf16 rounding where it is made, and less at every later layer.
Rounding has no direction; a wrong \epsilon shifts every token the same way. Check a port in fp32 against fp64, even one that will only run in bf16.
Wrap-up
d2l.GPT, a strict map of 311 tensors, one permutation of four tensors per layer.Next: how much of a model’s behavior the prompt decides.