A decoder-only transformer keeps one vector of D numbers per token, the residual stream, and every block adds two updates to it: attention, which mixes in what earlier positions hold, and a feed-forward network, which transforms each position on its own; the token table, reused as the output layer, turns the last vector into next-token scores, and cross-entropy against the sequence shifted by one is the whole training signal.
The tiny GPT, 5,836,032 parameters, on the running sequence (B = 1, T = 256). Not to scale: the token table has 16 times the position table's rows. Stream norms and probabilities are the trained checkpoint's, traced on CPU by the root's src/block/trace.py (this page's file loads that checkpoint with identical logits); removal losses measured on Apple M1 Pro.
You need: PyTorch's nn.Linear and a softmax. The root Topic: llm-architecture traces one token through one block of this same trained model in its Block lab tab (every intermediate vector, FLOPs per operation against context); this page builds the code that walk traces. Matrix calculus and backprop derives the backward pass counted here; Attention Is All You Need runs the 2017 encoder-decoder in the browser. Each piece's alternatives are a sibling's: Attention variants, Positional Encodings, Normalisation, residuals and stability, Mixture of experts, Tokenizers.
gpt_zero.py, their shapes and the test that proved each (reference)The page writes the pieces into an empty file, gpt_zero.py (230 lines when finished), tests each one on the running sequence as it is added, trains the result, samples from it, counts its parameters and FLOPs by hand, and removes one piece at a time. The code of each step is in a closed block under its section.
| Step | What it adds | Shape in → out | Parameters (tiny GPT) | The test that proved it (measured) |
|---|---|---|---|---|
| 1 Config | V, T, D, L, H and the switches | none | 0 | hd = D / H = 32, F = 4D = 1,024 |
| 2 Embedding | token table plus position table | (B, T) ids → (B, T, D) | 1,048,576 + 65,536 | lookup = one-hot × table (difference 0); shuffled tokens without positions give shuffled outputs (5.6 × 10-7) |
| 3 One head | q, k, v, scaled scores, causal mask, softmax | (T, D) → (T, hd), weights (T, T) | 3 D hd | changing token 200 moves outputs 0 to 199 by exactly 0 |
| 4 Many heads | split D into H heads, merge, output projection | (B, T, D) → (B, H, T, hd) → (B, T, D) | 262,144 per layer | equals 8 separate heads (0) and PyTorch's fused attention (1.5 × 10-8) |
| 5 Feed-forward | up to 4D, GELU, down to D | (B, T, D) → (B, T, 4D) → (B, T, D) | 524,288 per layer | one token alone gives the same output as inside the sequence (8.9 × 10-8) |
| 6 Block | pre-norm and the residual sum, twice | (B, T, D) → (B, T, D) | 786,944 | parameters add up exactly |
| 7 Model | 6 blocks, final norm, tied unembedding | (B, T) → (B, T, V) | 5,836,032 | same initial weights as the shared tiny GPT (difference 0); its trained checkpoint gives identical logits |
| 8 Loss | cross-entropy against the inputs shifted by one | (B, T, V), (B, T) → one number | 0 | untrained 8.360 against ln 4,096 = 8.318 |
| 9 Sampling | the generation loop and a KV cache | (1, t) → (1, t + 1), repeated | 0 | cached decoding equals a full forward (1.3 × 10-5) |
Step 1, the config, is one dataclass: every number the model needs plus the ablation switches (all on is the baseline).
# the_transformer_from_zero/src/zero/gpt_zero.py, lines 19 to 42 19 # ==== STEP 1: the config. Every number the model needs, and the switches the ablations turn off. 20 @dataclass 21 class Config: 22 vocab: int = 4096 # V: the running example's byte-level BPE 23 ctx: int = 256 # T max: the training context 24 d: int = 256 # D: width of the residual stream 25 n_layer: int = 6 # L: blocks 26 n_head: int = 8 # H: heads per attention layer, hd = D / H = 32 27 ffn_mult: int = 4 # F = 4 D = 1,024 28 swiglu: bool = False # SwiGLU FFN instead of GELU (F = 8/3 D rounded up to 32: 704) 29 # ablation switches: all True is the baseline 30 pos: bool = True # learned position table 31 resid: bool = True # x + sublayer(x); False: x = sublayer(x) 32 norm: bool = True # LayerNorm before each sublayer and before the head; False: no norm anywhere 33 attn: bool = True # the attention sublayer 34 ffn: bool = True # the feed-forward sublayer 35 36 @property 37 def hd(self): 38 return self.d // self.n_head 39 40 @property 41 def f(self): 42 return 32 * ((int(8 * self.d / 3) + 31) // 32) if self.swiglu else self.ffn_mult * self.d
cfg = Config() # V=4096 ctx=256 D=256 L=6 H=8 head size hd = D / H = 256 / 8 = 32 FFN hidden F = 4 D = 1024 (SwiGLU: 8/3 D rounded up to 32 = 704)
A language model gives the next token a probability from the tokens before it; a decoder-only transformer gives T of them in one pass over T tokens, position t predicting token t + 1 from positions 0 to t. Training lowers the average cross-entropy (minus the log probability of the token that came next) in nats; a loss L means the model is as unsure as a uniform choice among eL tokens, the perplexity.
The running example, defined once for the whole topic by the root page: TinyStories (Eldan and Li 2023, arXiv 2305.07759; licence CDLA-Sharing-1.0), short stories written by GPT-3.5 and GPT-4 for training small models; a byte-level BPE tokenizer of V = 4,096 tokens trained on it; and the running sequence, the first 256 tokens of validation story 1, never seen in training:
The model is the root's tiny GPT, with tied embeddings and a context of 256 tokens. Every shape on this page uses these letters:
| B | batch: sequences processed together (32 in training, 1 for the running sequence) |
| T | tokens per sequence (256) |
| D | model width, the length of the vector each position carries (256; 4,096 in Llama 3.1 8B) |
| H, hd | attention heads and the width of each, hd = D / H (8 and 32; 32 and 128 in Llama 3.1 8B) |
| F | feed-forward hidden width (1,024 = 4D; 14,336 in Llama 3.1 8B) |
| V, L | vocabulary size and number of blocks (4,096 and 6; 128,256 and 32) |
Real-model numbers are from the configs saved by the root (Llama 3.1 8B config.json, read 2026-10-18). Since the tiny GPT has T = D = 256, shapes are written with numbers and letters so it is clear which 256 is which. Every measurement comes from the file built below; its code and test outputs sit in a closed block under each section.
Each token id selects one learned row of D numbers from a (V, D) table: an id is a name, not a quantity (id 1,407 is not "more" than id 12). A row lookup equals a one-hot vector times the table, so the table trains like any weight matrix, but nn.Embedding only indexes. A second table adds one learned row per position (learned absolute positions, as in GPT-2), because attention compares positions only through dot products, which do not know where their vectors came from: shuffle the tokens and an attention layer without a mask returns the same outputs, shuffled the same way (it is permutation-equivariant), so word order would be invisible. Every later block reads the sum.
nn.Embedding only indexes.Vectors of the trained checkpoint, traced by the root's src/block/trace.py (CPU); the tables are drawn at the same height, not to scale. The shuffle test on the trained model's embeddings and head 0 of its first attention layer, without the causal mask: without positions the outputs are the same rows shuffled (largest change 5.6e-07 of the largest output); with positions added, 1.13. Measured by src/zero/steps.py on CPU.
Shapes on the running sequence (steps.py): idx (1, 256) = (B, T), token ids of the running sequence; emb.tok(idx) (1, 256, 256) = (B, T, D), one row of the (V, D) table per token; emb.pos(arange(T)) (256, 256) = (T, D), one row per position, broadcast over B; x = tok + pos (1, 256, 256) = (B, T, D), the residual stream starts here.
Cost. V × D parameters for tokens (1,048,576 here; 525M in Llama 3.1 8B, 128,256 × 4,096, derived) and Tmax × D for positions (65,536); no FLOPs. The token table is 18% of the tiny GPT and 6.5% of Llama 3.1 8B; in SmolLM2-135M it is 28M of 135M (config: 49,152 × 576), which is why small models tie it to the output layer (section 7). A learned position table also fixes the longest sequence the model can ever read: position 256 has no row (an IndexError, in the closed Mistakes block). RoPE, ALiBi and no positions at all (NoPE) remove the table; Positional Encodings compares them on this same model. Check: emb.tok.weight.shape == (V, D); the one-hot identity; the shuffle test with and without the position table.
gpt_zero.py, and its test output# the_transformer_from_zero/src/zero/gpt_zero.py, lines 45 to 58 45 # ==== STEP 2: embedding. Token ids (B, T) become vectors (B, T, D): one row of a V x D table per token, 46 # plus one row of a ctx x D table per position. 47 class Embedding(nn.Module): 48 def __init__(self, cfg): 49 super().__init__() 50 self.tok = nn.Embedding(cfg.vocab, cfg.d) # (V, D) 51 self.pos = nn.Embedding(cfg.ctx, cfg.d) if cfg.pos else None # (ctx, D) 52 53 def forward(self, idx, start=0): 54 B, T = idx.shape 55 x = self.tok(idx) # (B, T, D) 56 if self.pos is not None: 57 x = x + self.pos(torch.arange(start, start + T, device=idx.device)) # (T, D) broadcast over B 58 return x
lookup equals one_hot(idx) @ W: max |difference| = 0.0e+00
token " R" ("Roxy" is 4 tokens: " R", "o", "x", "y") at positions 20 and 25: token vectors differ by 0.0; after adding positions, cosine 0.433
trained layer-1 head 0, no mask, 256 tokens shuffled: without positions the outputs are the same rows shuffled (largest change 5.6e-07 of the largest output); with positions added: 1.13After the embedding, position t knows only its own token. Predicting what follows "Roxy found an" needs earlier positions, and which ones depends on content ("an" points at the next word's first sound; "Roxy" back at whoever Roxy is), which no fixed averaging window can do. Each position emits three linear maps of its residual vector x, hd numbers each: a query q (what it looks for), a key k (what it offers to be found by) and a value v (what it hands over if found). Position j's score for position i is qi·kj / √hd; the causal mask sets the scores of later positions (j > i) to minus infinity, so the softmax (exponentiate, divide by the row's sum) gives them weight exactly 0 and the rest weights that sum to 1. The output for position i is the weighted sum of the values.
steps.py): changing token 200 moves outputs 0 to 199 by exactly 0.0 and outputs 200 to 255 by up to 4.1e-04. One forward pass is therefore T valid next-token examples.Layer 1, head 4 of the trained checkpoint (scores already divided by √32, weights and vectors as traced by the root's src/block/trace.py); token 0 is <|endoftext|>, which starts every story. The score matrix is drawn wider than deep; it is 256 by 256.
Shapes on the running sequence (steps.py): x (256, 256) = (T, D), one sequence, no batch dim yet; q = x @ Wq (256, 32) = (T, hd), the same for k and v: (T, hd); scores q @ k.T (256, 256) = (T, T), row i: token i against every token; y = softmax(masked) @ v (256, 32) = (T, hd), one hd-vector per token.
Why divide by √hd. If the entries of q and k are independent with mean 0 and variance 1, their dot product sums hd such products and has variance hd (Vaswani et al. 2017, section 3.2.1 and its footnote, arXiv 1706.03762; the Attention Is All You Need paper page reproduces it). Measured: standard deviation 5.65 for hd = 32, against √32 = 5.66. Scores that wide push the softmax onto one key, so the row is close to one-hot and its gradient close to zero; the scale keeps the softmax soft at any head size. Seen from the keys' directions, q and k have length about √hd, so the scaled score is √hd times their cosine: the scale fixes the softmax's sharpness at β = √hd, sharp enough that a 64-dimension head can sum over about 1.2 million random keys before the leakage from the wrong ones is as large as the right value, soft enough to keep a gradient (the transformers-from-memory article):
Dropping the scale on the trained tiny GPT raises the running sequence's loss from 1.96 to 2.88, measured by the root's Block lab, which also shows the mask and transpose bugs. Llama's code stores it as self.scaling = self.head_dim**-0.5 (transformers modeling_llama.py:215); nanoGPT multiplies by 1.0 / math.sqrt(k.size(-1)) (nanoGPT model.py:67).
Cost. T × T scores per head: memory and FLOPs that grow with the square of the context (section 10). The alternatives (sharing K and V across heads, compressing them, windows) are Attention variants. Check: rows of the weights sum to 1, the upper triangle is 0, and editing a later token never moves an earlier output.
# the_transformer_from_zero/src/zero/gpt_zero.py, lines 61 to 71
61 # ==== STEP 3: one attention head, by hand. Each token asks a question (q), offers a label (k) and a
62 # payload (v); scores q.k / sqrt(hd); the causal mask hides the future; softmax turns scores into weights.
63 def one_head(x, Wq, Wk, Wv):
64 """x (T, D); W* (D, hd). Returns (T, hd) and the (T, T) weights."""
65 T = x.shape[0]
66 q, k, v = x @ Wq, x @ Wk, x @ Wv # each (T, hd)
67 s = q @ k.T / math.sqrt(q.shape[-1]) # (T, T): row i = token i's scores
68 future = torch.triu(torch.ones(T, T, dtype=torch.bool, device=x.device), 1)
69 s = s.masked_fill(future, float("-inf")) # token i sees tokens 0..i only
70 w = s.softmax(-1) # rows sum to 1
71 return w @ v, w
rows of w sum to 1: max |sum - 1| = 2.4e-07 weights above the diagonal (the future): max = 0.0 change token 200: outputs at 0..199 move by 0.0, at 200..255 by up to 4.1e-04 q.k of random unit-variance vectors, hd=32: std 5.65 (sqrt(hd) = 5.66); divided by sqrt(hd): 1.00 hd=32, 256 keys: mean largest softmax weight 0.62 unscaled, 0.04 scaled hd=128, 256 keys: mean largest softmax weight 0.84 unscaled, 0.04 scaled
A head with random weights on the running sequence's embeddings. The change test edits token 200 and recomputes: positions 0 to 199 do not move at all (difference exactly 0), which is what makes one forward pass a valid set of T training examples.
The largest of 256 softmax weights, averaged over random unit-variance queries and keys (steps.py, CPU). A uniform row would give each key 1/256 = 0.004.
One head produces one weighting per position, so it follows one relation at a time (the previous word, or the subject, or the matching quote). Several heads follow several relations in parallel, each in its own space of hd = D / H numbers, at the same parameter count as one wide head. Instead of H small (D, hd) matrices, one (D, D) matrix computes all H queries at once; the result is viewed as (B, T, H, hd) and transposed to (B, H, T, hd), so the head axis sits next to the batch axis and every head becomes an independent batched matrix multiply. After attention the heads are transposed back, laid side by side, and an output projection Wo (D, D) mixes them. The four matrices are the layer's 4D2 = 262,144 parameters.
att.q is one (256, 256) matrix: it computes all 8 heads' queries at once, (1, 256, 256) = (B, T, D); drawn is row 157, "o", in layer 1 of the trained model. Wk and Wv do the same for keys and values..view(B, T, H, hd) cuts each 256-vector into 8 heads of 32, (1, 256, 8, 32). Nothing moves in memory..transpose(1, 2) gives (1, 8, 256, 32): 8 independent (T, hd) problems, each with its own (T, T) weights. Row 157 of each, measured: heads 0 and 5 put 65% and 70% on the previous token " R"; head 4 79% on the earlier "x" tokens (Fig. 3); heads 1, 2 and 7 spread almost evenly (6.9 to 7.3 bits of entropy; uniform over 158 keys is 7.3)..transpose(1, 2).reshape(B, T, D) lays the 8 outputs side by side again, 256 numbers, and Wo (256, 256) mixes them into attention's output for "o" (norm 1.83), which is added to the stream (section 6).Measured: the batched layer equals 8 separate one-head calls concatenated (max difference 0) and F.scaled_dot_product_attention(q, k, v, is_causal=True) to 1.5 × 10-8; the file uses the fused call for speed. Vectors and weights: the trained checkpoint, layer 1, traced by the root's src/block/trace.py; weights under 0.3% are not drawn.
Shapes on the running sequence (steps.py): att.q(x) (1, 256, 256) = (B, T, D), (B, T, D): all 8 heads in one matmul; .view(B, T, H, hd) (1, 256, 8, 32) = (B, T, H, hd), split D = 8 x 32; .transpose(1, 2) (1, 8, 256, 32) = (B, H, T, hd), heads before T: 8 independent (T, hd) problems; q @ k.transpose(-2, -1) (1, 8, 256, 256) = (B, H, T, T), 8 score matrices; merge: .transpose(1, 2).reshape(B, T, D) (1, 256, 256) = (B, T, D), heads side by side again; att.o(y) (1, 256, 256) = (B, T, D), output projection mixes the heads.
Cost. The same 4D2 parameters and the same FLOPs whatever H is; each head's scores are T × T, so H heads hold H score matrices. The single-head ablation in section 11 measures what eight heads buy here. Check: the concatenation test, or the comparison with the fused kernel.
# the_transformer_from_zero/src/zero/gpt_zero.py, lines 74 to 106
74 # ==== STEP 4: all heads at once. One (D, D) matrix per q, k, v; split D into H heads of hd, move heads
75 # before T so each head is a batch of (T, hd) matrices; attend; merge heads back; output projection.
76 class CausalSelfAttention(nn.Module):
77 def __init__(self, cfg):
78 super().__init__()
79 D = cfg.d
80 self.H, self.hd = cfg.n_head, cfg.hd
81 self.q = nn.Linear(D, D, bias=False) # weight stored (out, in) = (D, D)
82 self.k = nn.Linear(D, D, bias=False)
83 self.v = nn.Linear(D, D, bias=False)
84 self.o = nn.Linear(D, D, bias=False)
85 self.o.is_residual_out = True
86
87 def forward(self, x, cache=None, manual=False):
88 B, T, D = x.shape
89 H, hd = self.H, self.hd
90 q = self.q(x).view(B, T, H, hd).transpose(1, 2) # (B, H, T, hd)
91 k = self.k(x).view(B, T, H, hd).transpose(1, 2)
92 v = self.v(x).view(B, T, H, hd).transpose(1, 2)
93 if cache is not None: # decoding: keep every past k and v
94 if "k" in cache:
95 k, v = torch.cat([cache["k"], k], 2), torch.cat([cache["v"], v], 2)
96 cache["k"], cache["v"] = k, v
97 Tk = k.shape[2]
98 if manual or (cache is not None and T != Tk):
99 s = (q @ k.transpose(-2, -1)) / math.sqrt(hd) # (B, H, T, Tk)
100 qpos = torch.arange(Tk - T, Tk, device=x.device)
101 future = qpos[:, None] < torch.arange(Tk, device=x.device)[None, :]
102 y = s.masked_fill(future, float("-inf")).softmax(-1) @ v # (B, H, T, hd)
103 else:
104 y = F.scaled_dot_product_attention(q, k, v, is_causal=True, scale=1 / math.sqrt(hd))
105 y = y.transpose(1, 2).reshape(B, T, D) # merge heads: (B, T, D)
106 return self.o(y)
equals 8 separate one_head() calls, concatenated: max |difference| = 0.0e+00 equals F.scaled_dot_product_attention(is_causal=True): max |difference| = 1.5e-08 parameters: 4 x D x D = 262,144
nanoGPT does the same split at nanoGPT model.py:57 to 59 and the merge at nanoGPT model.py:72. nn.Linear(D_in, D_out) stores its weight as (out, in) and computes x WT, so head h's query matrix is the slice q.weight[h*hd:(h+1)*hd].T. And .view needs memory laid out in the order of the new shape, which a transpose breaks: the merge must use .reshape or .contiguous().view. The split must be a view to (B, T, H, hd) followed by a transpose; viewing straight to (B, H, T, hd) silently scrambles tokens across heads (loss 1.96 to 3.64 on the trained model, root Block lab).
Attention moves information between positions, but its output is a weighted average of value vectors followed by one linear map: little nonlinear computation happens inside it. The model also needs a place to transform what a position now holds (combine features, look up facts associated with them). That is the feed-forward network (FFN), also called the MLP: up from D to F = 4D, GELU (a smooth ReLU: x times the probability that a standard normal is below x; the file uses its tanh approximation, as GPT-2 did), and down from F to D, applied to each position independently. Because no position looks at another, one token alone gives the same answer as inside the sequence (8.9 × 10-8). The 4x width is the 2017 choice (dff = 2,048 for dmodel = 512 in Vaswani et al.) and nanoGPT's (nanoGPT model.py:82).
Read as a memory. The FFN is out = V⊤σ(Kx): each hidden unit's input row is a key, σ weights it by its similarity to x, and its column of the down matrix is the value it adds. Attention is the same store with keys and values taken from the context and σ = exp, a weighted sum of every power of the similarity; the steeper the curve, the less the crowd of weakly similar keys leaks into a recall, which is the case for squared ReLU and gated units (the transformers-from-memory article puts numbers on it). A unit has two poles, and the negative one can carry meaning too: in Qwen3-32B, removing eight neurons whose negative side is Santa lore dropped "Santa" from near-certain to 6% (Neural Networks Are Already Clean).
SwiGLU. Most 2024 to 2026 models replace the two matrices with three: a gate Wg and an up matrix Wu both map D to F, the gate goes through SiLU (x · sigmoid(x)) and multiplies the up branch element by element, and Wd maps back down. Shazeer (2020, arXiv 2002.05202) kept parameters and compute equal by shrinking the hidden size: "To keep the number of parameters and the amount of computation constant, we reduce the number of hidden units dff ... by a factor of 2/3" (section 2; his base model goes from 3,072 to 2,048). Hence F = 8/3 D; Llama 3.1 8B uses 14,336 for D = 4,096, which is 3.5 D, wider than the equal-parameter rule. transformers writes the whole layer in one line, self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x)) (transformers modeling_llama.py:164). The file has it as a switch (Config(swiglu=True), F = 704, 3.1% more parameters than the GELU FFN); what activation functions do is Activation functions.
Shapes on the running sequence (steps.py): ffn.up(x) (1, 256, 1,024) = (B, T, F), 4 x wider; gelu(.) (1, 256, 1,024) = (B, T, F), elementwise: shape unchanged; ffn.down(.) (1, 256, 256) = (B, T, D), back to D.
Cost. 2 D F = 8D2 parameters, twice attention's 4D2: two thirds of every block's weights and of its FLOPs at short context. It is the part a mixture of experts multiplies (Mixture of experts); section 11 removes it. Check: the position-wise test; the parameter count 2 × 256 × 1,024 = 524,288.
# the_transformer_from_zero/src/zero/gpt_zero.py, lines 109 to 131 109 # ==== STEP 5: the feed-forward network. The same two-layer MLP applied to every token on its own: 110 # up to F = 4 D, a nonlinearity, back down to D. SwiGLU: a gated version with three matrices. 111 class FFN(nn.Module): 112 def __init__(self, cfg): 113 super().__init__() 114 self.up = nn.Linear(cfg.d, cfg.f, bias=False) # (F, D) 115 self.down = nn.Linear(cfg.f, cfg.d, bias=False) # (D, F) 116 self.down.is_residual_out = True 117 118 def forward(self, x): 119 return self.down(F.gelu(self.up(x), approximate="tanh")) # (B, T, F) inside, (B, T, D) out 120 121 122 class SwiGLU(nn.Module): 123 def __init__(self, cfg): 124 super().__init__() 125 self.gate = nn.Linear(cfg.d, cfg.f, bias=False) 126 self.up = nn.Linear(cfg.d, cfg.f, bias=False) 127 self.down = nn.Linear(cfg.f, cfg.d, bias=False) 128 self.down.is_residual_out = True 129 130 def forward(self, x): 131 return self.down(F.silu(self.gate(x)) * self.up(x))
position-wise: ffn(x)[157] vs ffn(x[157] alone): max |difference| = 8.9e-08 parameters: 2 x D x F = 524,288; SwiGLU 3 x D x 704 = 540,672 (3.1% more)
Stacking attention and FFN layers twelve deep in plain sequence makes a deep network whose gradient must pass through every layer on the way back, and whose input signal is rewritten by every layer on the way up. He et al. (2016, arXiv 1512.03385) found deeper plain networks trained worse than shallower ones; the fix was the residual connection: each layer adds its output to its input instead of replacing it.
The vector each position carries from the embedding to the output is the residual stream. A block reads a normalised copy of it, runs attention on the copy and adds the result to the stream; then reads a normalised copy again, runs the FFN and adds that. The stream itself is never normalised in place: this is pre-norm, GPT-2's change to the 2017 layout ("Layer normalization ... was moved to the input of each sub-block ... and an additional layer normalization was added after the final self-attention block", Radford et al. 2019, section 2.3, GPT-2 paper). LayerNorm subtracts each vector's mean, divides by its standard deviation and multiplies by a learned gain (D numbers; this model has no bias, like most modern ones); RMSNorm skips the mean subtraction.
"o" through block 1 of the trained checkpoint (the root's src/block/trace.py, CPU). Each vector is drawn to its own scale; the norm in its step is the number to compare. The initialisation numbers below are from the untrained file (steps.py, CPU).
Shapes on the running sequence (steps.py): block(x) (1, 256, 256) = (B, T, D), same shape in and out: blocks stack.
At initialisation the block's first output is as large as its input (ratio 1.15), not a small correction: the embeddings start with standard deviation 0.02 while LayerNorm hands each sublayer a copy of unit scale, so the first blocks dominate the stream. GPT-2 compensates by initialising the two matrices that write into the stream (Wo and the FFN's down matrix) with standard deviation 0.02 / √(2L) ("We scale the weights of residual layers at initialization by a factor of 1/√N where N is the number of residual layers", same section; nanoGPT nanoGPT model.py:145); the file's is_residual_out flag does the same. On the trained model the median token's norm grows from 1.3 to 65.5 through the stack under pre-norm (root Block lab; the traced "o" goes from 1.33 to 65.8), which is why the final norm before the output layer exists.
Cost. Two LayerNorm gains per block (512 parameters) and a few elementwise operations. Section 11 removes the residual and the norms at an equal budget. Post-norm, the 2017 placement, fails at this model's learning rate (held-out 5.943, the unigram level, against 2.281 for pre-norm; section 2 of Normalisation, residuals and stability); the stability side (RMSNorm, QK-norm, sandwich norms, loss spikes) is Normalisation, residuals and stability. Check: block(x).shape == x.shape, so blocks stack; the parameter sum in the test output.
# the_transformer_from_zero/src/zero/gpt_zero.py, lines 134 to 154 134 # ==== STEP 6: the block. Pre-norm residual: normalise a copy, run the sublayer, ADD its output to the 135 # stream. The stream x itself is never normalised in place, so every block only writes a correction. 136 class Block(nn.Module): 137 def __init__(self, cfg): 138 super().__init__() 139 self.cfg = cfg 140 if cfg.attn: 141 self.attn = CausalSelfAttention(cfg) 142 if cfg.ffn: 143 self.ffn = SwiGLU(cfg) if cfg.swiglu else FFN(cfg) 144 self.n1 = nn.LayerNorm(cfg.d, bias=False) if (cfg.norm and cfg.attn) else nn.Identity() 145 self.n2 = nn.LayerNorm(cfg.d, bias=False) if (cfg.norm and cfg.ffn) else nn.Identity() 146 147 def forward(self, x, cache=None, manual=False): 148 if self.cfg.attn: 149 a = self.attn(self.n1(x), cache, manual) 150 x = x + a if self.cfg.resid else a 151 if self.cfg.ffn: 152 f = self.ffn(self.n2(x)) 153 x = x + f if self.cfg.resid else f 154 return x
at initialisation |block(x) - x| / |x| = 1.15: embeddings start tiny (std 0.02) while LayerNorm hands each sublayer a unit-scale copy parameters per block: 786,944 = attention 262,144 + FFN 524,288 + 2 LayerNorm gains 512
Embed, run L blocks, apply a final LayerNorm, and multiply by the unembedding (the lm_head), a (V, D) matrix that gives each position one score per vocabulary entry: the logits, shape (B, T, V). With tied embeddings (Press and Wolf 2016, arXiv 1608.05859) the unembedding is the token table itself: the logit of token w is the dot product of the final vector with w's own embedding row, which saves V × D parameters (18% of this model). nanoGPT ties at nanoGPT model.py:138, transformers declares it with _tied_weights_keys (transformers modeling_llama.py:411). The file builds and initialises its modules in the same order as the root's tiny_gpt.py, so seed 0 gives the same 5,836,032 starting weights, and the root's trained checkpoint, with its parameter names mapped, gives the same logits to the last bit.
The trained checkpoint's final vector and top 10 probabilities for "o" (the root's src/block/trace.py, CPU); the bars are probabilities, the others drawn as one flat slab.
Shapes on the running sequence (steps.py): logits (1, 255, 4,096) = (B, T-1, V), predictions made at positions 0..254; targets = idx[:, 1:] (1, 255) = (B, T-1), the next token at each position.
The loss. Cross-entropy takes logits of shape (N, V) and targets of shape (N), so both are flattened over B and T first (nanoGPT nanoGPT model.py:187). Hugging Face models do the shift for you: labels = input_ids is correct there, because the loss pads and shifts at transformers loss/loss_utils.py:64; shifting yourself as well trains each position to predict the token after next.
What the first number says. An untrained model should be maximally unsure, so its loss should be close to ln V = 8.318; 8.360 is slightly above because random logits are not exactly flat (standard deviation 0.320). A starting loss far from ln V means a bug in the init or the loss (a missing scale on the logits, the wrong targets). After 1,500 steps the running sequence costs 1.956 nats per token: perplexity 7.1, as unsure as a choice among about seven tokens.
model.state_dict() holds tensors adding up to how many numbers?emb.tok.weight and lm_head.weight, so summing state_dict() counts its 1,048,576 entries twice; model.parameters() yields each tensor once. The same trap shows up in saved checkpoints: Qwen3-0.6B is tied in its config but its safetensors file stores lm_head.weight separately, so the Hub reports 751.6M for a 596.0M-parameter model (section 10).# the_transformer_from_zero/src/zero/gpt_zero.py, lines 157 to 175 157 # ==== STEP 7: the whole model. Embed, L blocks, a final norm, and the unembedding: a D x V matrix that 158 # turns the last residual vector into one score (logit) per vocabulary entry. Tied: it IS the embedding table. 159 class GPT(nn.Module): 160 def __init__(self, cfg): 161 super().__init__() 162 self.cfg = cfg 163 self.emb = Embedding(cfg) 164 self.blocks = nn.ModuleList(Block(cfg) for _ in range(cfg.n_layer)) 165 self.ln_f = nn.LayerNorm(cfg.d, bias=False) if cfg.norm else nn.Identity() 166 self.lm_head = nn.Linear(cfg.d, cfg.vocab, bias=False) # (V, D) 167 self.apply(self._init) 168 self.lm_head.weight = self.emb.tok.weight # weight tying 169 170 def _init(self, m): # GPT-2 initialisation 171 if isinstance(m, nn.Linear): 172 std = 0.02 / math.sqrt(2 * self.cfg.n_layer) if getattr(m, "is_residual_out", False) else 0.02 173 nn.init.normal_(m.weight, 0.0, std) 174 elif isinstance(m, nn.Embedding): 175 nn.init.normal_(m.weight, 0.0, 0.02)
parameters: 5,836,032 (tiny_gpt baseline: 5,836,032) lm_head.weight is emb.tok.weight: True; summing state_dict() instead counts it twice: 6,884,608 seed 0 initial weights vs tiny_gpt.py seed 0: max |difference| = 0.0 trained tiny GPT (ref_baseline_s1500) loaded into this file: logits differ by 0.0
# the_transformer_from_zero/src/zero/gpt_zero.py, lines 177 to 192
177 # ==== STEP 8: the loss. Position t predicts token t+1: targets are the inputs shifted by one.
178 def forward(self, idx, targets=None, cache=None, manual=False):
179 start = cache[0].get("len", 0) if cache else 0
180 if cache is not None and not cache:
181 cache.extend({} for _ in self.blocks)
182 x = self.emb(idx, start) # (B, T, D)
183 for i, b in enumerate(self.blocks):
184 x = b(x, cache[i] if cache is not None else None, manual) # (B, T, D) in and out
185 if cache is not None:
186 for c in cache:
187 c["len"] = start + idx.shape[1]
188 logits = self.lm_head(self.ln_f(x)) # (B, T, V)
189 loss = None
190 if targets is not None:
191 loss = F.cross_entropy(logits.float().view(-1, logits.shape[-1]), targets.reshape(-1))
192 return logits, loss, logits.new_zeros(()), None # same signature as tiny_gpt.GPT
untrained loss on the running sequence: 8.360; uniform guess ln V = ln 4096 = 8.318 trained (1,500 steps): 1.956 nats per token, perplexity 7.1 untrained logits: std 0.320, so softmax is near uniform (largest probability 0.00216)
Every token coloured by how surprised the model was by it, and the greedy continuation of the sequence's own opening. Snapshots of the root Inside lab's retrain of the same baseline (seed 0, the same schedule; final held-out 2.2744), evaluated here on CPU with this page's file. Measured on Apple M1 Pro.
The loop. Draw 32 random windows of 257 tokens from the training split, run the model, take the loss, backpropagate (the gradient of the loss with respect to every parameter; derived in Matrix calculus and backprop), clip the gradient's norm to 1, and let AdamW update the weights. The schedule is the running example's for every run on this topic: learning rate 3e-3 reached after 100 warm-up steps, then a cosine decay to 3e-4 at step 1,500; AdamW with betas (0.9, 0.95) and weight decay 0.1 on matrices only; fp32 (faster than bf16 autocast on this GPU: 40k against 30k tokens/s, root setup). How these choices are made at scale is Pretraining.
Reading the curve. A loss curve is easier to read against the losses of models you can write down. A model that ignores context and always predicts each token's overall frequency scores the unigram cross-entropy, 6.006 nats on the held-out split (root Block lab). A model that sees only the previous token scores at best about the bigram cross-entropy, 3.616 nats here (counts of token pairs in the 122M training tokens, smoothed toward the unigram, calculated by src/train/curve.py). The uniform guess is 8.318. The run passes the unigram line by step 30 (train loss) and the bigram line between steps 200 and 250 (held-out); everything below 3.62 is the model using more than one token of context.
Predict first: which tokens of the story stay expensive longest? Three phases show up; the steps walk seven of the run's twelve snapshots (all twelve are the dots on the curve).
It does so without an induction head in the usual sense (the root Inside lab's repeated-random-token probe scores 0.012 on this model), so the mechanism at this scale is unconfirmed.
How to check a run is healthy: the first logged loss is near ln V; the loss falls below the unigram line within tens of steps; the held-out loss keeps falling with the training loss (12.3M tokens is a tenth of one pass over the training shard, so no window is seen twice on average and there is nothing to overfit yet); no spike survives clipping.
# the_transformer_from_zero/src/train/train_zero.py, lines 58 to 65
58 for step in range(a.steps):
59 for g in opt.param_groups:
60 g["lr"] = lr_at(step)
61 x, y = batches.next(dev)
62 _, loss, _, _ = model(x, targets=y)
63 loss.backward()
64 gn = torch.nn.utils.clip_grad_norm_(model.parameters(), a.clip if a.clip > 0 else float("inf"))
65 opt.step(); opt.zero_grad(set_to_none=True)
src/train/train_zero.py: the root's train.py loop (its seeded batches and its fixed held-out windows are imported), with this page's model. Same seed, same batches, same starting weights as the reference run.
Measured on Apple M1 Pro (MPS), 2026-10-18. 1,500 steps x 8,192 tokens = 12.3M tokens, seed 0, 316 s at a median 40,711 tokens/s; held-out loss 2.2757 (the running example's 20 fixed validation windows) and 2.3001 on 100 windows, against 2.2776 and 2.3022 for the shared tiny GPT's reference run and 2.2811 for the Block lab's rerun of it (same seed; MPS reruns differ in the third decimal; a second seed gives 2.264). The run's arithmetic is about 4.8 × 1014 FLOPs (3 × the forward count of section 10, per sequence, × 48,000 sequences, derived), so the laptop sustained about 1.5 TFLOP/s. What transfers: losses at this seed and budget, and the order of the ablations; what does not: seconds, and anything about scale.
A 30-token prompt, then 10 generated tokens, as in steps.py's cache test. FLOPs are derived for the tiny GPT: weights 2 × 5,767,168 per token through the model (every block matrix and the output layer), attention 4 × L × D per key read (a query against a key and a weight times a value); with a cache only the new token goes through.
Generation runs the prompt through the model, turns the last position's logits into a distribution, picks one token, appends it, and repeats. Recomputing the whole prefix every step repeats work: the keys and values of earlier positions never change (the mask stops them from seeing new tokens), so a KV cache keeps them per layer, and each new step runs the model on one token only and attends over the cache.
Measured: decoding tokens 30 to 39 one at a time with the cache matches one full forward to 1.3 × 10-5. The cache costs 2 × L × D numbers per token: 6,144 bytes in bf16 here, 128 KiB for Llama 3.1 8B with its 8 key-value heads (root findings). How big it gets at long context is the Long context page's KV-cache calculator; serving at scale is Batching, KV cache and scheduling.
Shapes on the running sequence (steps.py): cache[0]['k'] after 40 tokens (1, 8, 40, 32) = (B, H, t, hd), (B, H, tokens so far, hd), per layer.
Picking the token. Greedy decoding takes the largest logit; it is deterministic and, in small models, repetitive. Temperature T divides the logits before the softmax: T < 1 sharpens the distribution toward greedy, T > 1 flattens it toward uniform. Top-k keeps only the k largest logits. The explorer uses the trained model's real logits at two points of the running sequence; the bars are the probabilities after the transform. Predict before you drag: at T = 2, does the true next token gain or lose probability? (Top-p, min-p and the rest are Sampling and decoding.)
Real continuations of evaluation prompt 1 ("Once upon a time, there was a little girl named Lily. She loved to") from the same model, seed 0, 50 new tokens:
| Setting | Continuation (measured, CPU) |
|---|---|
| greedy | play outside in the park. One day, she saw a big, scary dog. The dog was scared and ran away. Lily ran to the dog and asked, "Why are you sad?" The dog replied, "I lost my dog. I |
| T 0.5 | play outside in the garden. One day, she saw a big, scary cat. The cat was scared and ran away. Lily ran after the cat and picked up the cat. But then, the cat flew down and tried to catch it. Lily |
| T 0.8 | play outside in the garden. One day, she fell asleep and landed on the ground. She looked and it broke into little outside. Her mom said, "Lily, this fire truck is stuck up here." Lily tried to help her mom |
| T 1.0 | take walks in the garden. One day, she fell with her favorite yellow soc birdie when she noticed it. She looked outside and knew it was very broken. It was very important to see someone who didn't knowled. Lily decided |
| T 1.5 | especially aroundstairs all prints inside. One day, her daddy nearby came upon a letter when they noticed it squash adorable! He bouncyved excitedly hay and glass bow around the room. As he whistlingled the squash, z green |
| T 1.0, top-k 40 | take walks in the garden. One day, she fell with her favorite toy so she dropped it and started to cry. Her mommy heard her cry and came over to help. They told her to apologize and clean up the mess. After |
Greedy and T = 0.5 reuse the most familiar story ("a big, scary dog ... ran away"); T = 1.0 and above invent, and at T = 1.5 the words stop forming sentences. Top-k 40 at T = 1.0 starts identically to plain T = 1.0 (the same random draws pick the same tokens while they are inside the top 40) and then stays more coherent.
Check: greedy output is reproducible across runs; a sampler at a fixed seed is too; dividing by T = 0 is not a greedy decoder but an error (closed Mistakes block).
# the_transformer_from_zero/src/zero/gpt_zero.py, lines 194 to 214
194 # ==== STEP 9: sampling. Feed the prompt once, then one token at a time, reusing cached k and v.
195 @torch.no_grad()
196 def generate(self, idx, n_new, temperature=0.0, top_k=None, generator=None):
197 cache = []
198 logits, *_ = self(idx, cache=cache)
199 out = idx
200 for _ in range(n_new):
201 lg = logits[:, -1].float()
202 if temperature <= 0:
203 nxt = lg.argmax(-1, keepdim=True) # greedy
204 else:
205 lg = lg / temperature
206 if top_k:
207 v, _ = lg.topk(top_k)
208 lg[lg < v[:, -1:]] = float("-inf")
209 nxt = torch.multinomial(lg.softmax(-1), 1, generator=generator)
210 out = torch.cat([out, nxt], 1)
211 if out.shape[1] >= self.cfg.ctx: # learned positions stop at ctx
212 break
213 logits, *_ = self(nxt, cache=cache)
214 return out
decoding tokens 30..39 one at a time with the cache vs one full forward: max |difference| = 1.3e-05 greedy: Roxy was a little rhinoceros. He was very happy and loved to play with his friends. One day, he saw a big, scary dog. The dog was scared and wanted to T 0.8, seed 0: Roxy was a little rhinoceros. He had a big smile and loved to sleep all day. One day, he saw some good friends. He was watching the animals bouncy and not
Parameters. Everything above reduces to a few products. Per block: attention 4D2 (Wq, Wk, Wv, Wo), FFN 2DF = 8D2, two norm gains 2D. For the model: L blocks, plus the token table VD (shared with the output layer when tied), the position table TmaxD, and the final norm D.
The same formula, with grouped key-value heads (Wk and Wv have Hkv × hd outputs instead of D), a third FFN matrix for SwiGLU, an untied output layer and per-head QK-norm gains, reproduces the Hugging Face safetensors count of every dense model the root saved, to the parameter. Each residual is a stored tensor that is not a parameter, and the script names it (src/zero/accounting.py, Hub counts read 2026-10-18 from the root's config manifest):
| Model | Formula | Hub safetensors | Residual | Why |
|---|---|---|---|---|
| smollm2-135m | 134,515,008 | 134,515,008 | 0 | none |
| qwen3-0.6b | 596,049,920 | 751,632,384 | 155,582,464 | tied in the config, but the safetensors file stores lm_head.weight separately (151,936 x 1,024 = 155,582,464) |
| gpt2 | 124,439,808 | 137,022,720 | 12,582,912 | the checkpoint stores each layer's causal-mask buffer attn.bias (1,024 x 1,024 x 12 = 12,582,912), not parameters |
| llama-2-7b | 6,738,415,616 | 6,738,417,664 | 2,048 | the checkpoint stores rotary inv_freq buffers (F32, 64 per layer x 32 = 2,048) |
| mistral-7b-v0.1 | 7,241,732,096 | 7,241,732,096 | 0 | none |
| llama-3.1-8b | 8,030,261,248 | 8,030,261,248 | 0 | none |
| qwen3-8b | 8,190,735,360 | 8,190,735,360 | 0 | none |
| olmo-2-7b | 7,298,617,344 | 7,298,617,344 | 0 | none |
| llama-3.1-70b | 70,553,706,496 | 70,553,706,496 | 0 | none |
The Llama 2 residual was checked in the safetensors headers of NousResearch/Llama-2-7b-hf at revision 8efe6c9 (32 F32 tensors rotary_emb.inv_freq of 64 entries, headers fetched 2026-10-18); SmolLM2-135M and Qwen3-0.6B were checked tensor by tensor against the headers in the local Hugging Face cache. The Config calculator on the root does the same for 44 repositories including MoE, MLA and hybrid models; the Shapes and counts tab lists every weight and activation shape of these nine models.
FLOPs. A matrix multiply of a (1, n) row by an (n, m) matrix is n × m multiply-adds, which hardware counts as 2nm FLOPs (floating-point operations). So one token's forward pass through every weight matrix costs 2 FLOPs per weight it touches: 2 × (L (4D2 + 2DF) + VD) = 11,534,336 for the tiny GPT (the embedding lookup is free; the tied matrix is used once, as the output layer). Attention adds the part that has no weights: each token's query against T keys and its weights against T values, 2 × 2 × T × D per layer. Over the 256-token running sequence:
FlopCounterMode on the file's explicit attention path: 3,355,443,200, equal to the formula (the counter sees the full T × T product; a fused causal kernel can skip the masked half, 202,113,024)So training costs about 6N FLOPs per token plus the attention term, Kaplan et al.'s rule (2020, arXiv 2001.08361, Table 1, which drops the attention term when D > T/12). nanoGPT's MFU estimate is the same accounting in one line: flops_per_token = 6*N + 12*L*H*Q*T (nanoGPT model.py:296), where H × Q = D. At T = 256 attention is 12% of the tiny GPT's forward; the root's Block lab moves T and shows where attention overtakes the weights (about 28.6k tokens for Llama 3.1 8B in decode).
An ablation removes one component and retrains. Each run below is the same file with one switch off, the same seed, the same 1,500 steps of the same batches and the same schedule (measured on Apple M1 Pro, MPS; samples and per-token losses evaluated afterwards with eval_zero.py). Positions and heads leave the parameter count almost unchanged; removing the FFN or attention also removes parameters, so those two compare architectures and sizes together (stated in the table). Predict the order before reading it: which removal costs most?
| Run | What changes | Parameters | Held-out loss | vs baseline |
|---|---|---|---|---|
| Baseline | nothing (the file as built) | 5,836,032 | 2.276 | |
| No residual | x = sublayer(norm(x)) instead of x + sublayer(norm(x)) | 5,836,032 | 6.011 | +3.735 |
| No norm | every LayerNorm removed, including the final one | 5,832,704 | 2.546 | +0.270 |
| No position | no position table (NoPE); the causal mask remains | 5,770,496 | 2.375 | +0.100 |
| One head | H = 1, hd = 256 (same parameters) | 5,836,032 | 2.282 | +0.006 |
| One head, seed 1 | as above, seed 1 (compare the baseline at seed 1, 2.264) | 5,836,032 | 2.327 | +0.051 |
| No FFN | attention-only blocks (54% fewer parameters) | 2,688,768 | 2.702 | +0.427 |
| No attention | FFN-only blocks: each position sees only its own token and position | 4,261,632 | 3.695 | +1.419 |
| No residual, lr 1e-3 | as above at a third of the learning rate | 5,836,032 | 6.011 | +3.736 |
| No norm, lr 1e-3 | as above at a third of the learning rate | 5,832,704 | 3.061 | +0.785 |
| Baseline, lr 1e-3 | the reference model at lr 1e-3 (root Block lab run) | 5,836,032 | 2.464 | +0.189 |
Held-out loss on the running example's 20 fixed validation windows, as every lab on this topic reports it. Baseline seed spread: 2.278, 2.281 and 2.276 at seed 0 (three runs), 2.264 at seed 1, so differences under about 0.02 are noise.
Loss on the 20 fixed held-out windows, every 100 steps. Dashed: the unigram cross-entropy (a model that ignores context) and the bigram cross-entropy (one token of context, counted from the training split), both calculated by src/train/curve.py. Tap a run to show or hide it; the dashed runs are the lower learning rate and the second seed.
No residual: the model learns nothing past token frequencies. Held-out 6.011 at lr 3e-3 and 6.011 at lr 1e-3, against the unigram cross-entropy 6.006: both runs sit on the line of a model that ignores context, and the greedy continuation of every prompt is a row of full stops. Without the sum, every sublayer must rebuild the whole representation instead of adding a correction, and the gradient reaches the embedding only through twelve stacked sublayers. Dong et al. (2021, arXiv 2103.03404) prove the related failure for attention: without "skip connections or multi-layer perceptrons (MLPs), the output converges doubly exponentially to a rank-1 matrix". A lower learning rate does not rescue it here, so it is not an instability; it is the architecture. This is the largest effect on the page.
No attention: exactly the predicted floor. Blocks with only an FFN let each position see its own token and position and nothing else, so the best such model is a bigram model. It ends at 3.695, 0.08 above the bigram cross-entropy counted from all 122M training tokens (3.616); the network saw a tenth of them. Its greedy text shows it: one plausible phrase, then the same token repeated ("the park." and then only line breaks). A known answer the run lands on is a check on the whole pipeline. Everything the baseline gains below 3.62 comes from attention reading more than one token back.
No FFN: +0.43, but it is also a smaller model. Attention-only blocks have 2,688,768 parameters against 5,836,032; the run cannot separate "no MLP" from "54% fewer parameters" (a parameter-matched version with 18 attention-only layers was not run; it would cost about three times the attention compute per step). At 2.70 it is still far below the bigram floor, so attention alone does most of the context work; the FFN adds per-token computation on top.
No norm: trains, but worse and more sensitive. 2.546 at lr 3e-3 (+0.27); at lr 1e-3 it falls further behind (3.061 against 2.464 for the normalised baseline at the same rate, root Block lab): the unnormalised stream grows with depth and the update size that suits it is different. At 6 layers it does not diverge; the stability story at depth is Normalisation, residuals and stability.
No position: +0.10, much less than "word order is invisible" suggests. The causal mask leaks order: position t averages over exactly t + 1 tokens, so the model can count (Haviv et al. 2022, arXiv 2203.16634: "causal attention enables the model to infer the number of predecessors that each token can attend to"). It agrees with the Positional Encodings child's NoPE run of the root model (2.3666 on the same 20 windows; on 100 windows this run gives 2.3987 against its 2.389), which also shows what a learned table costs past 256 tokens.
One head: a small cost that depends on the seed. Eight heads of 32 against one head of 256, same parameters and FLOPs: +0.006 at seed 0, +0.063 at seed 1 (mean +0.035; the baseline's own spread is about 0.02). At this size and budget, eight heads buy a few hundredths of a nat; Michel et al. (2019, arXiv 1905.10650) found that "a large percentage of attention heads can be removed at test time without significantly impacting performance". One head did run about a third faster on MPS (55,029 against 40,711 tokens/s, rough), plausibly because fewer, larger kernels suit this GPU (not profiled). What does not transfer: at 4,096 wide a single head would have hd = 4,096 and one attention pattern per layer for everything; real models keep hd at 64 to 256.
What transfers from these toy ablations: the order (residual and attention are essential, the FFN and norm matter, positions and head count matter least at this size) and the known answers (unigram for a broken network, bigram for no attention). What does not: the size of the gaps for a model a thousand times larger trained a thousand times longer.
| Run | Greedy continuation of prompt 7 ("... a rhinoceros named Roxy. Roxy loved to") |
|---|---|
| Baseline | play with his friends, but he was always very careful. One day, Roxy met a little girl named Lily. She was very kind and kind. She said, "Hi, I'm Li... |
| No residual | ............................................................ |
| No norm | play with his friends, but he was always very fast. One day, he saw a big, shiny rock in the ground. He wanted to try it, but he didn't know what to ... |
| No position | play with his friends. One day, Rocery saw a big, scary dog. The dog was scared and ran away. Rocery tried to run away, but he was too fast. Rocery ... |
| One head | play with his friends, but one day, he saw a big, scary dog. Roxy the dog and wanted to play with Roxy the dog, but he was too scared to run away. O... |
| One head, seed 1 | play with his friends. One day, Roxy met a little girl named Lily. She was very happy and said, "Hi, I'm Lily. I am a little girl named Lily. I am a ... |
| No FFN | play with his friends. One day, Rozz was playing in the park. He was having so much fun! Rozz was so excited to play with his friends. He had a fun ... |
| No attention | the park. |
| No residual, lr 1e-3 | ............................................................ |
| No norm, lr 1e-3 | play with his friends. One day, they decided to go on a walk in the park. They went to the park and saw a big, a big, a little girl named Max. The bo... |
| Baseline, lr 1e-3 | (not recorded: a root Block lab run, logged without a checkpoint) |
Greedy and sampled (temperature 0.8, seed 0) continuations of the eight evaluation prompts by the baseline and the ablation picked above, 60 new tokens, cut at the end-of-text token. Real outputs; nothing filtered.
Each was run on the running example by src/zero/mistakes.py (CPU); silent bugs were applied to the trained model at inference, so the change in loss is the bug's alone. The root's Block lab has four more silent attention bugs (no 1/√d scale 1.96 to 2.88, head split without transpose 3.64, merge without transpose 5.03, no causal mask 3.64): not repeated here.
Cross-entropy on (B, T, V) logits. F.cross_entropy(logits, targets) with logits (1, 255, 4,096) and targets (1, 255) reads dimension 1 as the classes:
RuntimeError: Expected target size [1, 4096], got [1, 255]
Flatten first: F.cross_entropy(logits.view(-1, V), targets.view(-1)). If the shapes happen to line up (T = V), it runs and trains the wrong thing.
Merging heads with .view after .transpose.
RuntimeError: view size is not compatible with input tensor's size and stride (at least one dimension spans across two contiguous subspaces). Use .reshape(...) instead.
Use .reshape(B, T, D) or .contiguous().view(B, T, D) (nanoGPT nanoGPT model.py:72).
Using an nn.Linear weight as if it were (in, out).
RuntimeError: mat1 and mat2 shapes cannot be multiplied (4x256 and 1024x256)
nn.Linear(256, 1024).weight has shape (1,024, 256); the layer computes x WT. GPT-2's original checkpoints use a Conv1D that stores (in, out), which is why nanoGPT transposes four weight names when loading them.
Reading past the learned position table.
IndexError: index out of range in self
A 300-token input to a model with a 256-row position table. The message names neither positions nor lengths; nanoGPT crops the context to block_size before every generation step (nanoGPT model.py:314).
Temperature 0 by division.
RuntimeError: probability tensor contains either `inf`, `nan` or element < 0
Logits divided by 0 are plus and minus infinity; the softmax of that is NaN. Temperature 0 means greedy: take the argmax instead.
| Bug (applied to the trained model) | Loss on the running sequence | Leak | Greedy continuation |
|---|---|---|---|
| none (the trained model) | 1.96 | 0 | Ro loved to play in the forest and have fun. One day, Roxy's friend, a little girl |
| masked_fill(future, 0) applied to the weights after softmax | 4.18 | 0.00263 | R R R R R R R R R R R R R R R R R R R R R R R R R |
| future scores set to 0 instead of -inf before softmax | 2.43 | 0.0325 | One day,,,,,,,,,,,,,,,,,,,,,,, |
| softmax(dim=-2): normalised over queries, not keys | 4.27 | 0.0707 | M M M M M M M M M M M M M M M M M M M M M M M M M |
Leak: how far the output logits at position 150 move when only token 200 changes (0 for a causal model). Zeroing future weights after the softmax looks like masking, but the softmax's denominator already summed every future score, so earlier positions still depend on later tokens, and the rows no longer sum to 1.
Training on unshifted targets: the loss goes to zero and the model learns nothing useful. model(x, targets=x) asks every position for its own token, which it can read straight from its embedding. From scratch (batch 8 × 256, lr 1e-3, CPU), the training loss falls from 7.25 to 0.067 in 150 steps, faster than any real run; the held-out loss with correctly shifted targets is 13.36 nats, worse than a uniform guess (8.32), and the greedy continuation of prompt 7 is ".........................". Even the first loss is low (7.25 against 8.36 for real targets): with tied embeddings the output layer scores each position's own token with its own embedding, so the identity is favoured from the start. A loss that drops this fast is a bug, not a success.
The mirror image is shifting twice. Hugging Face's causal-LM loss shifts the labels itself (transformers loss/loss_utils.py:64); if you also shift them, each position is trained to predict the token after next. Scoring the trained tiny GPT that way gives 8.84 nats on the running sequence against 1.96: a different task, not a small error.
Counting tied parameters twice. sum(v.numel() for v in model.state_dict().values()) gives 6,884,608 for a 5,836,032-parameter model (section 7). Count model.parameters(), or, for a checkpoint, check whether lm_head.weight and the embedding hold the same data.
Write the shapes through one attention layer for a batch of B sequences of T tokens. x (B, T, D) → q, k, v (B, T, D) → view (B, T, H, hd) → transpose (B, H, T, hd) → scores q kT (B, H, T, T) → mask and softmax over the last axis → weights × v (B, H, T, hd) → transpose (B, T, H, hd) → reshape (B, T, D) → Wo (B, T, D). With GQA, k and v are (B, Hkv, T, hd) and each serves H / Hkv query heads.
Why divide the scores by √dhead, and what breaks without it? A dot product of hd unit-variance terms has variance hd; unscaled, the softmax saturates onto one key and its gradient vanishes. Measured: standard deviation 5.65 at hd = 32, the largest of 256 weights 0.62 on average unscaled against 0.04 scaled; removing it from the trained tiny GPT raises the running sequence's loss 1.96 to 2.88 (root Block lab).
Count the parameters of a GPT-2 style model in your head. 12 L D2 for the blocks plus V D for the tied embedding (plus positions). GPT-2 small: 12 × 12 × 7682 = 84.9M, plus 50,257 × 768 = 38.6M, plus 1,024 × 768 = 0.8M, about 124.3M; the exact count with biases and LayerNorm terms is 124,439,808.
How many FLOPs to train a 7B dense model on 2T tokens? About 6 N Dtokens = 6 × 7e9 × 2e12 = 8.4e22 FLOPs, plus the attention term (12 L D T per token: for 32 layers, D 4,096, T 4,096 that is 6.4 GFLOPs per token, 15% on top of 6N = 42 GFLOPs). With the attention term, about 9.7e22; at 40% of an H100 SXM's 989 TFLOP/s dense bf16 (NVIDIA's datasheet figure, vendor) that is about 2.4e8 GPU-seconds, roughly 68,000 GPU-hours (calculated); the hardware side is Performance math.
What does the residual connection buy, measured? Without it, this 6-block model at the same budget ends at 6.01, the unigram level (6.01): it learned token frequencies and nothing else. Each sublayer has to rebuild the whole representation instead of adding a correction, and gradients reach the embedding only through twelve stacked layers (Dong et al. 2021: without skip connections and MLPs, attention's output "converges doubly exponentially to a rank-1 matrix").
Why does a causal decoder still work without any position encoding? The mask itself tells a position how many predecessors it has, so order can be inferred (Haviv et al. 2022). Measured here: no positions 2.375 against 2.276 at an equal budget. Without the mask (an encoder), no positions means a bag of words.
Why tie the input and output embeddings, and why do large models stop? Tying saves V D parameters, a large share of a small model (18% here, 21% of SmolLM2-135M) and gives the rare tokens' output rows the gradient of their input use. In an 8B model the table is 6.5% of the weights and untying lets input and output spaces differ: Llama 3.1 8B, Qwen3-8B and Mistral 7B are untied, SmolLM2 and Qwen3-0.6B tied (configs).
Your training loss reaches 0.07 in 150 steps on a language model. What do you check first? The targets: they are probably the inputs, not the inputs shifted by one (measured above: 0.067 train, 13.4 held-out). Then the mask (a missing causal mask lets each position read its own next token; the Families and objectives page measured a leaky model at 0.21 held-out under the leak and 7.02 under the causal mask).
Design: a 125M-parameter decoder for a 4,096-token context on one 24 GB GPU. What do you choose and why? Start from the 2026 default rather than GPT-2: about 12 layers of D 768 (12 × 12 × 7682 = 85M in blocks) with a 32k to 50k tied vocabulary (25 to 38M); RoPE instead of a learned table (no hard length wall, extendable later); pre-norm RMSNorm with QK-norm for stability; SwiGLU at about 8/3 D; GQA with 4 KV heads to cut the cache 3x for serving. At 4,096 tokens the attention term is 12 L D T = 0.45 GFLOPs per token against 6N = 0.75: use FlashAttention or SDPA (never materialise (B, H, T, T)); bf16 weights and activations with fp32 master weights and AdamW states, 16 bytes a parameter, 2 GB, leave the rest to activations with checkpointing if needed. Then verify like this page: initial loss ln V, a falling curve past the unigram and bigram lines, and one ablation to make sure every component pulls its weight.
The tool for every section of the Reading tab: pick a model and a context length, and read each stored weight of one layer with the shape the checkpoint stores, every activation through the layer, the parameter total against the Hugging Face count, the KV cache per token and the forward FLOPs of one token. The formulas are section 10's; the configs are the root's saved config.json files (read 2026-10-18), and every total matches the safetensors count after the stored non-parameters named in section 10, checked by src/zero/accounting.py. Predict first: in one layer of Llama 3.1 8B, is k_proj the same shape as q_proj, and which matrix is largest?
Shapes follow each checkpoint's convention: nn.Linear stores (out, in) and computes x WT; GPT-2 stores its linear layers as Conv1D with weights (in, out). With grouped-query attention, k_proj and v_proj have Hkv × hd outputs, not H × hd: using H here is the classic GQA mistake. Qwen3 adds per-head q and k RMSNorm gains (hd each); OLMo 2 normalises q and k over the full width and puts its norms after the sublayers. Forward FLOPs: 2 per weight touched (every block matrix and the output layer; the embedding lookup is free) plus 4 × L × T × H × hd for the query against T keys and the weights against T values. The scores row is why fused attention kernels never store the (T, T) matrices, and the logits row (B, T, V) is often the largest single activation in training, which is why some trainers compute the loss in chunks. KV cache per token here is one line of arithmetic; sizing at a context length, with every attention design, is the Long context page's KV-cache calculator.
D width, L layers, H query heads, Hkv key-value heads, hd head size, F feed-forward width, V vocabulary.
Links open in a new tab; checked 2026-10-18. Times are estimates (for knowledge base pages, the Reading time their header states where it states one). Outside sources are marked maker (written by the people who built the model or library) or third-party.
The decoder from an empty file in nine steps, each with its figure, shapes and tested code; training, sampling with and without a KV cache, counting by hand, six ablations at an equal budget; mistakes and interview rehearsal in closed blocks. (32 min, plus 22 in closed details)
Every stored weight and activation shape, parameter totals against the Hub, KV bytes and FLOPs per token, for nine real configs and the tiny GPT. (5 min)
The parent: every component's alternatives and costs. Its Block lab follows one token through one block of the same trained model (real vectors, the FLOPs-by-operation calculator); its Config calculator and Inside a real model tabs go from this toy to real checkpoints. (23 min, plus 13 in closed details)
What replaces step 4 in 2026 models: MQA, GQA, MLA, windows, sparse attention, sinks. (37 min, plus 28 in closed details)
What replaces step 2's position table: sinusoidal, RoPE, ALiBi, NoPE, and running past the trained length, on this model. (40 min, plus 21 in closed details)
Step 6 in depth: post-norm, RMSNorm, QK-norm, initialisation and loss spikes. (31 min, plus 15 in closed details)
Step 5 multiplied: routers, balancing, shared experts, expert parallelism, trained on this model. (35 min, plus 21 in closed details)
Where the 4,096 ids come from, and how tokenizers fail. (46 min, plus 15 in closed details)
The KV cache of step 9 at length: memory, compression, local and global attention, effective context. (28 min, plus 13 in closed details)
Replacing attention with SSMs, linear attention and hybrids. (37 min, plus 20 in closed details)
Other masks and losses than step 8's: encoders, encoder-decoders, multi-token prediction, diffusion LMs. (34 min, plus 14 in closed details)
Reading a real model card and config, and the per-layer deltas of 2026 open models. (28 min, plus 9 in closed details)
The 2017 paper: a live toy encoder-decoder in the browser, its tables rebuilt, and the 2017 block morphing into a 2026 one. (about 20 min)
The backward pass this page counts as "twice the forward": Jacobians, the chain rule through a linear layer, softmax and a whole network. (about 32 min)
The training loop at scale: data, optimiser settings, schedules, compute budgets. (about 30 min)
Everything after the logits: temperature, top-k, top-p, min-p, beam search, repetition penalties. (about 22 min)
Step 9's cache in a serving engine. (about 37 min)
GELU, SiLU and the GLU family of step 5. (about 25 min)
From FLOPs and bytes to seconds on real hardware. (about 24 min)
The paper page for the GPT-2 architecture scaled to 175B. (about 21 min)
Karpathy's 330-line GPT-2, the closest relative of this page's file; quoted here at commit 3adf61e. (30 min)
Karpathy's video building the same decoder on Shakespeare, step by step (2023). (1h 56m)
The 2017 encoder-decoder line by line in PyTorch (Harvard NLP). (1h)
Section 2.3 is the pre-norm and scaled initialisation this page uses. (15 min for section 2)
Shazeer's four-page paper behind SwiGLU and the 2/3 width rule. (15 min)
Why residual connections and MLPs are needed, proved (Dong, Cordonnier and Loukas 2021). (40 min)
The production version of every step: GQA, RoPE, RMSNorm, SwiGLU, the cache interface. (30 min)
Code quoted on this page: nanoGPT at commit 3adf61e (2025-11-12) and transformers v5.20.1 (commit 0ea8779, 2026-10-16), located by pattern by src/zero/code_refs.py.