A Released Checkpoint in the Book’s Own Code

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

A Port Can Load, Write Fluent Text, and Still Be Wrong

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?

By the End of This Deck You Can

Goals

  • list how a released block differs from d2l.GPT and turn the list into subclasses;
  • write a weight map that accounts for every tensor, with the permutation between two RoPE layouts;
  • decide agreement by a measured tolerance, not one picked by hand;
  • localize a failing port to the first layer that diverges;
  • say what a bf16 logit check cannot see, and what to run instead.

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.

Later Sections Measure on This Model, So We Check It First

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
  • Uses: d2l.GPT, RoPE, the KV cache, GPT-2’s name map, safetensors headers.
  • Skips: Qwen3.5 and other hybrids, whose recurrent layers are ported in the architectures chapter.
  • Why now: a constant that is off by a fraction of a percent shifts every later measurement.

At Qwen3’s Size, Only the Norms of the Book’s Block Fit

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.

Nine Settings Separate the Two Models

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.

QK-Norm and a Wider Head Are One Attention Subclass

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)
  • QK-norm: an RMSNorm on the query and the key of each head, before the rotation. It keeps attention logits from growing with the weights.
  • head_dim = 128 is an argument: 16 heads give queries of width 2,048.
  • The fused attention kernel is inherited from d2l.CausalAttention.

With Its Features Off, the Subclass Is the Book’s GPT

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.
  • Test: the weights of a small 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.

A Strict Map Accounts for Every Tensor

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)']
  • 311 = 28 layers \times 11 tensors + embedding + final norm + a stored copy of the embedding (verified, dropped).
  • Strict accounting: no tensor left over, no name unfilled (here one k_norm was deleted), then a strict load.
  • Port, configuration and file header each count 596,049,920 parameters.

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.

The Two RoPE Layouts Differ by a Permutation of Four Tensors

  • Transformers rotates the pairs (i, i + d_h/2), the book the pairs (2i, 2i+1), by the same angles.
  • Orange: rows of q_proj, k_proj and gains of q_norm, k_norm are permuted within each head.
  • Everything else is renamed.

Permuted Queries and Keys Reproduce Transformers’ Scores

\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}.

  • Rows of q_proj, k_proj and both gains permuted: scores agree with Transformers’ to fp32 rounding.
  • Gain of QK-norm not permuted: largest difference 80% of the largest score.

QK-norm sits between projection and rotation, so its gain must move with the coordinates. Forgetting it changes no shape.

Check: The Permutation for a Head of Width 4

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.
  • No. Values are never rotated, so v_proj and o_proj keep their order.

The Rule: No Further from fp64 Than Transformers Itself

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.

  • Two correct programs differ by rounding, so the tolerance is measured.
  • Interval of the ratio: resample the 32 prompts in pairs, 2,000 times (the bootstrap). Pass only if the whole 95% interval is at most 1.5.

In fp32 the Port Is as Close to fp64 as Transformers Is

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
  • Both errors about 4 \times 10^{-6}; no logit differs by more than about 10^{-4}; two runs give the same bits.
  • Left column: only the port’s batch size changes, and the ratio moves from 0.8 to 1.2. Right column: equal batches, ratio about 1.

An interval over prompts says nothing about batching. Apply the rule with both programs batched alike.

Matching a Reference Includes Its Rounding of the Angles

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
  • In fp32, 24 of the 64 frequencies differ in the last bit. At position 4,095 the angles differ by 2.4 \times 10^{-4}.
  • The rule measures agreement with Transformers, its rounding included.

Compute a port’s constants with the expressions of the reference implementation, in its precision.

In bf16 the Errors Are 10,000 Times Larger, and the Port Passes

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
  • In fp32 both errors were 4 \times 10^{-6}.
  • The programs round in different places. A ratio below 1 is no merit of the port.
  • Batching moves the ratio between 0.71 and 0.76.

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: Can Rounding Flip a Greedy Token?

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?

  • Only in bf16. One different token changes all later ones.
  • fp32: identical text unless a gap falls below 10^{-4}. bf16: texts part at such near-ties.

One Decoding Loop Drives the Port, Transformers, and Any Module

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
logits, step = start(prompt_ids)          # logits after the prompt
for n in range(max_new_tokens):
    nxt = sample_logits(logits, strategy, temperature, k, p, min_p)
    logits = step(nxt)                    # one new token per row

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.

Greedy Text Is Identical in fp32 and Parts at Near-Ties in bf16

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
  • Gap between the two best fp32 logits at the parting: 4 \times 10^{-4} to 0.2, mostly below the mean bf16 logit error of 0.05.
  • The bf16 counts shift with batching and do not rank the two programs.

Before suspecting a bug in a comparison of two bf16 runs, look at the gap.

An Error Cannot Appear Before the Layer That Causes It

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
  • Error of a tensor \mathbf{A} against its fp64 value \mathbf{A}^{64}: \|\mathbf{A} - \mathbf{A}^{64}\|_F / \|\mathbf{A}^{64}\|_F, median of 32 prompts.
  • Floor: the error of a correct implementation at the same point. Divergence: the first point above 10 times the floor.

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: Five One-Line Bugs That Pass Strict Accounting

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.

Each Bug First Diverges Where It First Acts

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%
  • Floor: the correct port’s fp32 error. Transformers in fp32, within a factor of 2 of it, gives the same six answers.
  • Top token kept: share of 2,048 positions with the fp64 reference’s most likely next token. B2 would pass a reading of sampled sentences.

Check: The Size of a Wrong Epsilon

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.

  • Embeddings: 4.5 \times 10^{-6} / 7.3 \times 10^{-4} \approx 0.6\%, about one bf16 rounding.
  • Last block: about 10^{-8}, less than one fp32 rounding.

A Wrong Epsilon Passes the bf16 Logit Check and Fails the fp32 One

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%
  • fp32 rule: B5 fails at a ratio of about 2,000, against a limit of 1.5.
  • bf16 rule: B5 passes at 0.77, beside 0.73 for the correct port. Batching alone moves the correct port from 0.71 to 0.76.
  • Only next to a correct port does the bug show in bf16: its logit error is about 6% larger.

The error of a wrong \epsilon is one bf16 rounding where it is made, and less at every later layer.

At No Depth Does a Wrong Epsilon Rise above bf16 Rounding

  • Relative error of the residual stream after each block, median of 32 prompts.
  • Black: correct in fp32. Gray: correct in bf16. Left: the port (solid) on Transformers (dashed).
  • Right: B1, B2, B3 leave the correct port in block 0, B4 in block 2. B5 runs flat, from the gray curve to five times below it.

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

Wrap-up

  • Port: nine settings in two subclasses of d2l.GPT, a strict map of 311 tensors, one permutation of four tensors per layer.
  • Rule: at most 1.5 times Transformers’ own error against fp64, both batched alike. Qwen3-0.6B: about 1 in fp32, about 0.7 in bf16.
  • Constants: computed as the reference implementation computes them. The book’s angle formula fails at about 2 on 4,096 tokens.
  • A failing port: find the first divergence, with Transformers in fp32 as the floor. Five bugs diverge where they first act.
  • Precision: check in fp32. A wrong \epsilon fails there at about 2,000 and passes in bf16 at 0.77.

Next: how much of a model’s behavior the prompt decides.