Highlights

Contents

Part V
05

Reading a Real Model: Qwen3

A saved checkpoint expects one particular architecture. Familiar components can still use unfamiliar dimensions and conventions. Read the configuration and tensor roles before constructing the decoder.

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

#Section 24From Our Transformer to Qwen

Download Qwen3-0.6B and you get a folder of files. The one that describes the architecture is a 726-byte config.json. Everything else in this part is read out of it. Before reading it, it helps to see that nothing in Qwen3 is new to you. Mapping known Transformer concepts onto Qwen is mostly a matter of names.

Concept Where this book taught it Qwen3-0.6B
Decoder-only architecture Chapter 1, Part XII Qwen3ForCausalLM, 28 layers
RMSNorm Chapter 2, Part II pre-norm, ε=10−6\varepsilon = 10^{-6}, plus a final norm
RoPE Chapter 2, Part I base 1,000,000, half-split rotate_half
GQA Chapter 2, Part IV 16 query heads, 8 key/value heads
SwiGLU Chapter 2, Part III gate_proj, up_proj, down_proj, width 3,072
Residual connections Chapter 1, Section 65 two per layer, around attention and MLP
LM head Chapter 1, Section 68 tied to the embedding table

There is one addition the textbook block does not have, a small RMSNorm applied to each query and key head, which Section 28 covers. Otherwise, if you can draw the block from Chapter 2, you can draw Qwen3.

ONE QWEN3 DECODER LAYER, HUGGING FACE NAMES (× 28)input_layernormq_projk_projv_projq_normk_normRoPE + SDPA (GQA 16 : 8)o_projpost_attention_layernormgate_proj, up_projSiLU ⊙ → down_proj++residual stream(B, T, 1024)(B, T, 1024)q 2048 · k 1024 · v 1024per head, 128 wideθ = 1,000,0002048 → 10241024 → 3072 → 1024new in Qwen3:the two orangenorms
Figure 4.30One Qwen3 decoder layer with its Hugging Face module names. The orange stream is the residual; the only part not in Chapter 2's block is the pair of small norms on q and k.

#Section 25Reading a Model Configuration

Here is the whole config.json of Qwen3-0.6B, as published. Read it top to bottom and each key either confirms something you expected or tells you something you could not have guessed.

text
{
  "architectures": ["Qwen3ForCausalLM"],
  "attention_bias": false,
  "attention_dropout": 0.0,
  "bos_token_id": 151643,
  "eos_token_id": 151645,
  "head_dim": 128,
  "hidden_act": "silu",
  "hidden_size": 1024,
  "initializer_range": 0.02,
  "intermediate_size": 3072,
  "max_position_embeddings": 40960,
  "max_window_layers": 28,
  "model_type": "qwen3",
  "num_attention_heads": 16,
  "num_hidden_layers": 28,
  "num_key_value_heads": 8,
  "rms_norm_eps": 1e-06,
  "rope_scaling": null,
  "rope_theta": 1000000,
  "sliding_window": null,
  "tie_word_embeddings": true,
  "torch_dtype": "bfloat16",
  "use_cache": true,
  "use_sliding_window": false,
  "vocab_size": 151936
}

Vocabulary size, vocab_size, is 151,936: the number of rows in the embedding table and the LM head. It is not the number of tokens the tokenizer knows, which is 151,669 (Part VIII); the remaining 267 rows are padding, kept so the matrix dimension is a multiple of 128, which suits GPU kernels. Hidden size, hidden_size, is the residual width d=1,024d = 1{,}024. Number of layers, num_hidden_layers, is 28. Attention heads, num_attention_heads, is 16 query heads, and KV heads, num_key_value_heads, is 8. Intermediate size, intermediate_size, is the SwiGLU width, 3,072. head_dim is 128, which Section 26 will make a fuss about.

Maximum sequence length, max_position_embeddings, is 40,960. Qwen3 uses RoPE and has no position table, so this number is not a hard limit of the weights; it is the length the authors configured, and the model card states a context length of 32,768. When the two disagree, trust the card for quality and the config for what the code will accept. RoPE parameters are rope_theta, the base, 1,000,000 (Llama 3 uses 500,000; Finch-24 uses 10,000), and rope_scaling, null here, meaning no context stretching is applied (Chapter 2, Section 6). The normalization epsilon, rms_norm_eps, is 10−610^{-6}, ten times smaller than Finch-24's.

The token IDs at the top need care. bos_token_id is 151643, <|endoftext|>, but Qwen3's tokenizer does not add it to prompts (add_bos_token is false). eos_token_id is 151645, <|im_end|>, the end-of-turn marker of the chat format. The separate generation_config.json lists both 151645 and 151643 as stopping tokens and sets 151643 as the padding ID. Part IX explains why a chat model stops on end-of-turn.

The rest is housekeeping: attention_bias: false (no bias on the projections), hidden_act: "silu" (the gate's activation), tie_word_embeddings: true (the LM head reuses the embedding table), torch_dtype: "bfloat16" (the dtype the weights were saved in), and the three sliding-window keys, which together say "no sliding window in any layer".

TEN CONFIG KEYS, AND WHAT EACH ONE CONTROLSvocab_size: 1519361hidden_size: 10242num_hidden_layers: 283num_attention_heads: 164num_key_value_heads: 84head_dim: 1285intermediate_size: 30726rope_theta: 10000007rms_norm_eps: 1e-068tie_word_embeddings: true9embed_tokens151,936 × 1,024lm_head(same matrix)11293× 28RMSNorm, ε 1e-68GQA: 16 q, 8 kv4head size 1285RoPE, θ 1e67SwiGLU, 3,0726
Figure 4.31Every architectural key in the config, numbered, and the part of the model it controls. These ten keys fix the whole architecture.

#Section 26Reconstructing Architecture From Config

Building layers from configuration values means writing a constructor that takes nothing but the config and produces every module with the right shape. Here is the skeleton for Qwen3, in our own naming:

python
@dataclass
class Cfg:
    vocab: int = 151936; d: int = 1024; n_layers: int = 28
    n_heads: int = 16; n_kv: int = 8; d_head: int = 128
    d_ff: int = 3072; theta: float = 1e6; eps: float = 1e-6; tied: bool = True

class Layer(nn.Module):
    def __init__(self, c):
        super().__init__()
        self.wq = nn.Linear(c.d, c.n_heads * c.d_head, bias=False)   # 1024 -> 2048
        self.wk = nn.Linear(c.d, c.n_kv * c.d_head, bias=False)      # 1024 -> 1024
        self.wv = nn.Linear(c.d, c.n_kv * c.d_head, bias=False)      # 1024 -> 1024
        self.wo = nn.Linear(c.n_heads * c.d_head, c.d, bias=False)   # 2048 -> 1024
        self.q_norm, self.k_norm = RMSNorm(c.d_head, c.eps), RMSNorm(c.d_head, c.eps)
        self.gate = nn.Linear(c.d, c.d_ff, bias=False)
        self.up = nn.Linear(c.d, c.d_ff, bias=False)
        self.down = nn.Linear(c.d_ff, c.d, bias=False)
        self.norm1, self.norm2 = RMSNorm(c.d, c.eps), RMSNorm(c.d, c.eps)

Deriving head dimension

Qwen3 specifies head_dim independently of residual width. Its query projection expands into the configured heads, and the output projection returns to residual width. Deriving head size from hidden_size // num_attention_heads builds the wrong architecture.

HEAD SIZE: DERIVED (WRONG FOR QWEN3) vs READ FROM THE CONFIGd_head = 1024 / 16 = 64x: 1,024q_proj16 heads × 64 = 1,024o_projout: 1,024head_dim = 128 (config)x: 1,024q_proj16 heads × 128 = 2,048o_projout: 1,024q_proj (1024, 1024): checkpoint will not loadq_proj (2048, 1024): matches the file
Figure 4.32The head-size trap. Dividing the width by the heads gives 64 and a 1,024-wide attention; Qwen3 configures 128, so attention runs 2,048 wide and the projections widen and narrow.

Deriving GQA grouping

The group size is H/Hkv=16/8=2H / H_{kv} = 16 / 8 = 2: query heads 0 and 1 share key/value head 0, heads 2 and 3 share head 1, and in general query head ii reads key/value head ⌊i/2⌋\lfloor i / 2 \rfloor. Expand with repeat_interleave or the expand-reshape helper, never with .repeat (Chapter 2, Section 19).

Computing tensor shapes and checking the count

Projection widths, head sharing, and configured depth determine which learned tensors must exist.

A parameter-count sanity check can expose missing tensors or an unintended untied head. It supports shape validation but does not prove that the loaded function is correct.

QWEN3-0.6B: 596,049,920 PARAMETERS, AND ONE LAYER OF 15,730,944embedding (tied with LM head)155,582,464 (26.1%)28 × attention176,167,936 (29.6%)28 × MLP264,241,152 (44.3%)norms: 58,368 (0.01%)one layerattention: q, k, v, o + q_norm, k_norm6,291,712 (40%)MLP: gate, up, down9,437,184 (60%)+ 2,048 norm gainsa big vocabulary is expensive in a small model
Figure 4.33Where Qwen3-0.6B's 596,049,920 parameters live. A quarter is the embedding table, which a large vocabulary makes expensive in a small model; within each layer the MLP holds 60% and attention 40%.

Check every configured dimension and sharing convention, then compare logits. Matching a total count alone can hide compensating mistakes.

#Section 27Real Model Tensor Shapes

PyTorch stores a linear layer's weight as (out features,in features)(\text{out features}, \text{in features}), the transpose of the xWx W convention used in this book's equations. The layer computes xW⊤x W^\top. So every shape in the checkpoint reads "output size first". These are the shapes in Qwen3-0.6B's file, read from its header (Part VI):

Tensor Shape Role
Embedding weights, model.embed_tokens.weight (151,936, 1,024) one row per token ID
Q projection, self_attn.q_proj.weight (2,048, 1,024) 16 heads of 128
K projection, self_attn.k_proj.weight (1,024, 1,024) 8 heads of 128
V projection, self_attn.v_proj.weight (1,024, 1,024) 8 heads of 128
self_attn.q_norm.weight, self_attn.k_norm.weight (128,) per-head norm gain
Output projection, self_attn.o_proj.weight (1,024, 2,048) back to the residual width
SwiGLU gate/up/down projections: mlp.gate_proj.weight, mlp.up_proj.weight (3,072, 1,024) widen
mlp.down_proj.weight (1,024, 3,072) narrow
Normalization weights: input_layernorm.weight, post_attention_layernorm.weight (1,024,) pre-norm gains
model.norm.weight (1,024,) final norm
LM head, lm_head.weight (151,936, 1,024) same values as the embedding

Per-layer tensors are prefixed model.layers.N. with NN from 0 to 27. Notice that q_proj and o_proj are not square and not transposes of each other's shape by accident: (2,048,1,024)(2{,}048, 1{,}024) and (1,024,2,048)(1{,}024, 2{,}048) are the widen-then-narrow pair from Section 26. In the head-split view, row block 128h128h to 128h+127128h + 127 of q_proj produces query head hh, and column block 128h128h to 128h+127128h + 127 of o_proj consumes head hh's output. The LM head appears in the file even though it is tied; Section 32 deals with that.

PYTORCH STORES LINEAR WEIGHTS AS (OUT, IN): HEADS ARE BANDS OF ROWS, OR OF COLUMNSout 2,048in 1,024rows 0 to 127: head 0q_proj.weightx (1, 1024)@ Wᵀ =q (1, 2048)16 heads × 128o_proj.weight (1024, 2048)columns 0 to 127 read head 0;each output mixes all 16 heads back into 1,024 numbersoutput size comes first
Figure 4.34How the checkpoint lays out heads. q_proj is stored (2,048, 1,024), output size first; each band of 128 rows makes one query head. o_proj is stored (1,024, 2,048); each band of 128 columns reads one head.

#Section 28Qwen Attention Internals

Qwen3's attention is Chapter 2's attention with two deliberate differences. Walk through it with the shapes for a batch of BB sequences of TT tokens.

Qwen query heads. q_proj maps (B,T,1,024)(B, T, 1{,}024) to (B,T,2,048)(B, T, 2{,}048), viewed as (B,T,16,128)(B, T, 16, 128). Qwen KV heads. k_proj and v_proj each give (B,T,1,024)(B, T, 1{,}024), viewed as (B,T,8,128)(B, T, 8, 128). The GQA layout pairs query heads 2j2j and 2j+12j + 1 with key/value head jj.

Qwen3 applies query/key normalization after projection and head reshape, before RoPE. Shared per-head gains control scale, helping prevent scores from growing excessively during training. Values are not normalized this way; match the reference placement exactly.

QK-NORM BOUNDS THE SCORES (SKETCH IN 2D, LENGTHS ILLUSTRATIVE)without: lengths grow with the weightswith: every head rescaled to one lengthscores q·k can grow without limitunit gains: length √128 ≈ 11.31, |score| ≤ 11.31orange arrows: queries slate arrows: keys
Figure 4.35What QK-norm does. Without it, query and key lengths can grow with the weights and scores grow with them; with it, every head is rescaled to a fixed length, √128 with unit gains, so scores stay bounded.

RoPE application. After the norm, queries and keys are rotated with base 1,000,000 using the half-split rotate_half convention, pairing dimension ii with i+64i + 64 in each 128-wide head (Chapter 2, Section 4). Rotating all 128 dimensions, with 64 pair speeds from 11 down to 106×(−126/128)10^{6 \times (-126/128)}, about 1.2×10−61.2 \times 10^{-6} radians per position.

Attention. After transposing to (B,16,T,128)(B, 16, T, 128) and (B,8,T,128)(B, 8, T, 128), SDPA computes causal attention with scale 1/1281 / \sqrt{128}, with enable_gqa or after expanding keys and values. Attention output projection. The output (B,16,T,128)(B, 16, T, 128) is transposed back and flattened to (B,T,2,048)(B, T, 2{,}048), and o_proj maps it to (B,T,1,024)(B, T, 1{,}024) for the residual add.

QWEN3-0.6B ATTENTION, PREFILL OF T TOKENS, EVERY SHAPERMSNorm(x)(B, T, 1024)q_proj → view(B, T, 16, 128)k_proj → view(B, T, 8, 128)v_proj → view(B, T, 8, 128)q_norm (128 gains)same shapek_norm (128 gains)same shapeRoPE, θ = 10⁶RoPE, θ = 10⁶transpose → SDPA, causal, scale 1/√128, enable_gqa → (B, 16, T, 128)transpose, reshape (B, T, 2048) → o_proj → (B, T, 1024) → + residualv is nevernormalizedor rotated
Figure 4.36Qwen3-0.6B attention with every shape. The orange boxes are the two Qwen-specific steps: the per-head norms on q and k, and the 2,048-wide attention space that o_proj folds back to 1,024.

Model-specific architectural details to check in the reference code, every time: the order of norm and RoPE (norm first in Qwen3), whether the norm gain is per head or shared (shared), whether projections have biases (not in Qwen3; yes in Qwen2.5's q, k and v), and the RoPE pairing convention (half-split). Each of these produces a model that runs if you get it wrong.

python
q = self.q_norm(self.wq(x).view(B, T, 16, 128)).transpose(1, 2)   # (B, 16, T, 128)
k = self.k_norm(self.wk(x).view(B, T, 8, 128)).transpose(1, 2)    # (B, 8, T, 128)
v = self.wv(x).view(B, T, 8, 128).transpose(1, 2)                 # (B, 8, T, 128)
q, k = rope(q, cos, sin), rope(k, cos, sin)
o = F.scaled_dot_product_attention(q, k, v, is_causal=True, enable_gqa=True)
x = x + self.wo(o.transpose(1, 2).reshape(B, T, 2048))           # (B, T, 1024)

#Section 29Qwen Feed-Forward Block

The MLP is Chapter 2's SwiGLU without changes, so the mechanism lives there: two projections, one passed through SiLU and used as a gate on the other, then a projection back (Chapter 2, Part III, with the gate in action in Section 14). For Qwen3-0.6B:

MLP(x)=Wdown(SiLU⁡(Wgate x)⊙Wup x)\text{MLP}(x) = W_{\text{down}}\big(\operatorname{SiLU}(W_{\text{gate}}\,x) \odot W_{\text{up}}\,x\big)

Read it as: the gate projection maps the 1,024-wide normalized hidden state to 3,072 features and SiLU, z⋅σ(z)z \cdot \sigma(z), turns each into a soft switch; the up projection maps the same input to 3,072 candidate features; the element-wise gating multiplies them feature by feature, so each switch decides how much of its feature passes; and the down projection maps the 3,072 results back to 1,024 for the residual add.

Read the feed-forward hidden width from the config. Its projections can account for much of the stored weight and decode traffic, making them important quantization targets.

QWEN3-0.6B MLP, BAR HEIGHT = WIDTH (1,024 → 3,072 → 1,024)x1,024gate_projup_projgate 3,072up 3,072SiLU⊙h3,072down_projout1,0243 × 1,024 × 3,072= 9,437,184per layer60% of every layer
Figure 4.37Qwen3-0.6B’s MLP drawn to scale. The 1,024-wide state fans out into two 3,072-wide projections, the SiLU gate multiplies the up features one by one, and down_proj folds the result back.