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.
#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, , 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.
#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.
{
"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 . 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 , 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".
#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:
@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.
Deriving GQA grouping
The group size is : query heads 0 and 1 share key/value head 0, heads 2 and 3 share head 1, and in general query head reads key/value head . 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.
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 , the transpose of the convention used in this book's equations. The layer computes . 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 from 0 to 27. Notice that q_proj and o_proj are not square and not transposes of each other's shape by accident: and are the widen-then-narrow pair from Section 26. In the head-split view, row block to of q_proj produces query head , and column block to of o_proj consumes head 's output. The LM head appears in the file even though it is tied; Section 32 deals with that.
#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 sequences of tokens.
Qwen query heads. q_proj maps to , viewed as . Qwen KV heads. k_proj and v_proj each give , viewed as . The GQA layout pairs query heads and with key/value head .
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.
RoPE application. After the norm, queries and keys are rotated with base 1,000,000 using the half-split rotate_half convention, pairing dimension with in each 128-wide head (Chapter 2, Section 4). Rotating all 128 dimensions, with 64 pair speeds from down to , about radians per position.
Attention. After transposing to and , SDPA computes causal attention with scale , with enable_gqa or after expanding keys and values. Attention output projection. The output is transposed back and flattened to , and o_proj maps it to for the residual add.
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.
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:
Read it as: the gate projection maps the 1,024-wide normalized hidden state to 3,072 features and SiLU, , 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.