11. The transformer

Why this layer exists

Chapter 10’s head gives each position one weighted average of the value vectors it can see: one softmax row, one mixture. A position that needs two things at once, the token just before it and the subject of its sentence, must split one row of weights between them and receives a blend of both, with every feature of both values averaged by the same weights. Every output is a weighted average of linear projections of the input; the only non-linear step is the choice of weights. And the head cannot tell order: chapter 10 showed that a causal head sees each earlier token and how many there are, but not in which order they came. A usable model needs several lookups per layer, a non-linear computation at each position between lookups, many layers of both with gradients that still reach the first, and a sense of position.

The transformer block supplies these with four pieces around chapter 10’s attention: multi-head attention, several narrow heads side by side; a feed-forward sublayer, chapter 9’s up-project, non-linearity, down-project, applied to every position separately; residual connections, which add each sublayer’s output to its input instead of replacing it; and layer normalisation in front of each sublayer. A position signal is added to the input or rotated into the queries and keys. The model is a stack of identical blocks between an embedding table and an output layer.

The GGUF files llama-server loads store a transformer as these pieces. The GGUF specification names the tensors outside the blocks token_embd, pos_embd (for models with a learned position table), output_norm and output, and the tensors of block N blk.N.attn_norm, blk.N.attn_q, blk.N.attn_k, blk.N.attn_v (or the fused blk.N.attn_qkv), blk.N.attn_output, blk.N.ffn_norm, blk.N.ffn_up and blk.N.ffn_down, each with a .weight and, where the layer has one, a .bias. This chapter’s GPT has one of each, under the names tok, pos, ln_f, head, and per block ln1, attn.query, attn.key, attn.value, attn.proj, ln2, up and down. The specification also names ffn_gate, for the gated feed-forward sublayers many current models use (a third matrix whose output, passed through the non-linearity, multiplies the up-projection’s output elementwise), and a set of _exp variants with a router, ffn_gate_inp, for mixture-of-experts models. In those, the feed-forward sublayer of each block is replaced by many expert feed-forward networks and a small router that sends each token to a few of them. That is what the a3b in a name like straylight’s ornith-1.5-35b-a3b counts, by the convention of releases such as Qwen3-30B-A3B, whose model card gives 30.5B parameters in total and 3.3B activated, from 128 experts of which 8 run per token: the first number is the parameters stored, the second the parameters that compute on each token. Memory scales with the first; the arithmetic per token with the second, and so do the bytes each decoded token reads, which chapter 14 shows is what sets decoding speed.

The chapter builds tinygpt.transformer: layer norm, GELU, rotary position encoding, multi-head attention, the block and the model, a mixture-of-experts feed-forward sublayer, with save and load; and tinygpt.train_gpt, which trains a tokenizer and a model on a text corpus and writes both outside the repository.

Mechanism

Multi-head attention

Split the model width dd into HH heads of width dh=d/Hd_h = d/H. Each head is chapter 10’s causal head with its own projections of shape (d, d_h); the HH outputs, each (B, T, d_h), are concatenated back to (B, T, d) and multiplied by an output projection WO\mathbf{W}_O of shape (d, d) with a bias of shape (d,).

The HH query projections need not be separate matrices. Put them side by side as the column blocks of one (d, d) matrix, WQ=[WQ(1)⋯WQ(H)]\mathbf{W}_Q = [\mathbf{W}_Q^{(1)} \cdots \mathbf{W}_Q^{(H)}]. A matrix product’s column block hh depends only on the matching column block of the right operand, so XWQ=[XWQ(1)⋯XWQ(H)]\mathbf{X}\mathbf{W}_Q = [\mathbf{X}\mathbf{W}_Q^{(1)} \cdots \mathbf{X}\mathbf{W}_Q^{(H)}]: one product of shape (B, T, d) computes every head’s queries, and head hh owns features hdhh\,d_h to (h+1)dh−1(h+1)\,d_h - 1. The same holds for keys and values. What remains is moving the features into place for chapter 10’s attention, which works over any leading axes:

(B,T,d)→(B,T,H,dh)→(B,H,T,dh), (B, T, d) \;\to\; (B, T, H, d_h) \;\to\; (B, H, T, d_h) ,

a reshape and then a swap of axes 1 and 2. The reshape splits the last axis, which in row-major order keeps each head’s dhd_h features together; the transpose puts the head axis in front of time, so the last two axes are (T, d_h) as attention expects. The (T, T) causal mask broadcasts over both leading axes. test_heads_split_and_merge_round_trip checks that heads of a (3, 5, 8) input with H=2H = 2 has shape (3, 2, 5, 4) and that head 1 holds features 4 to 7 exactly. After attention the same two steps run backwards, transpose to (B, T, H, d_h) and reshape to (B, T, d), which is the concatenation. Attention reads dd from the queries’ last axis, so each head’s scores are scaled by 1/dh1/\sqrt{d_h}, the width of its own dot products.

Count the parameters. HH heads each have three (d, d_h) projections, 3ddhH=3d23 d d_h H = 3d^2 weights, and the output projection has d2+dd^2 + d: 4d2+d4d^2 + d in all, 16,448 at d=64d = 64. One head of width dd with the same output projection has exactly as many. The score arithmetic is also the same: HH products of (T, d_h) by (d_h, T) cost HT2dh=T2dH T^2 d_h = T^2 d multiply-adds, as for one head of width dd. The difference is the number of softmax rows. One wide head computes one distribution over positions per query and averages all dd value features with it; HH narrow heads compute HH distributions, each averaging its own dhd_h features, so one head can put its weight on the previous token while another puts its weight on a noun ten positions back, and the output projection mixes what they found. The price is that each head’s score is a bilinear form of rank at most dhd_h instead of dd: a narrower head is coarser at deciding what matches.

Measured on talos (the laptop, an Intel i3-1315U) on Persuasion with the lab’s configuration (512-token BPE, d=64d = 64, two blocks, context 64), trained for 1,000 steps from two seeds and scored on the same 20,000 held-out tokens, with nothing changed but HH: one head of width 64 reaches 3.343 and 3.349, four heads of width 16 reach 3.232 and 3.267, and sixteen heads of width 4 reach 3.273 and 3.279. Several heads beat one by about 0.1 nats at the same parameter count; sixteen heads are no better than four.

The ordering test_multi_head_attention_is_causal_and_shaped checks is the one chapter 10 checked for one head: changing positions 4 and 5 of a six-position input leaves outputs 0 to 3 unchanged. The output projection mixes features within a position, never across positions, so it cannot break causality.

Residual connections

A block computes y=x+f(x)\mathbf{y} = \mathbf{x} + f(\mathbf{x}) instead of y=f(x)\mathbf{y} = f(\mathbf{x}), with x\mathbf{x} and y\mathbf{y} of the same shape, (B, T, d): the sublayer computes a change to its input, not a replacement for it. The line from x\mathbf{x} to the sum is the residual connection, and the running (B, T, d) array that every block reads from and adds to is often called the residual stream.

For one position, with x\mathbf{x} and y\mathbf{y} of shape (d,) and Jf=∂f/∂x\mathbf{J}_f = \partial f / \partial \mathbf{x} of shape (d, d), the Jacobian of the block is

∂y∂x=I+Jf. \frac{\partial \mathbf{y}}{\partial \mathbf{x}} = \mathbf{I} + \mathbf{J}_f .

(With attention, ff at position tt also depends on earlier positions; those Jacobians gain no identity term, and the argument below concerns the path from a position to itself.) Stack LL blocks, xℓ=xℓ−1+fℓ(xℓ−1)\mathbf{x}_\ell = \mathbf{x}_{\ell-1} + f_\ell(\mathbf{x}_{\ell-1}), and write Jℓ\mathbf{J}_\ell for ∂fℓ/∂xℓ−1\partial f_\ell / \partial \mathbf{x}_{\ell-1}. The chain rule multiplies the blocks’ Jacobians, and expanding the product term by term,

∂xL∂x0=(I+JL)⋯(I+J1)=I+∑ℓJℓ+∑ℓ>mJℓJm+⋯+JL⋯J1. \frac{\partial \mathbf{x}_L}{\partial \mathbf{x}_0} = (\mathbf{I} + \mathbf{J}_L)\cdots(\mathbf{I} + \mathbf{J}_1) = \mathbf{I} + \sum_{\ell} \mathbf{J}_\ell + \sum_{\ell > m} \mathbf{J}_\ell \mathbf{J}_m + \cdots + \mathbf{J}_L \cdots \mathbf{J}_1 .

Each term picks, from every factor, either I\mathbf{I} or Jℓ\mathbf{J}_\ell, so there are 2L2^L terms, one for each subset of the blocks. The first is the identity: however small or badly conditioned the Jℓ\mathbf{J}_\ell are, the gradient of the loss with respect to xL\mathbf{x}_L reaches x0\mathbf{x}_0 unchanged through it, and reaches each block’s input through the sum of the blocks above it. Without the residual lines only the last term exists, a product of LL Jacobians, which can shrink or grow geometrically with LL, as chapter 9’s saturated tanh units shrank theirs.

Measured on the tiny corpus’s model with six blocks, the product collapses in the forward direction first. Build the model with rng = np.random.default_rng(0) and, for the version without residuals, keep the same weights and drop the two additions; with the same rng, continuing after the model’s draws, take one batch of 16 windows of 16 tokens from the whole tiny corpus (all 13,332 ids, not the 90% training split) with get_batch; replace the newest token xx of each window with (x+1)modV(x + 1) \bmod V; and compare the final state at that position (after ln_f), as the length of the change divided by the length of the state, averaged over the 16 windows, all at initialisation. With the residual lines the change is 0.215. Without them it is 6.0×10−66.0 \times 10^{-6}: six rounds of attention, each replacing a position by an average over its history, have washed the newest token out, and the model’s output barely depends on what the current token is. That sensitivity is the same Jacobian the gradient travels back through, so the gradient from a prediction back to its own token is of the same order. It is not visible in the size of the weight gradients: each block’s layer norm rescales its input, and the gradient of every block’s up weight, backpropagated from the cross-entropy of the same batch at initialisation, has a similar Frobenius norm with or without residuals (0.70 to 0.95 without them, 0.22 to 0.46 with them, over the six blocks). Trained for 300 steps, two blocks without residual lines end at 1.2310 held out against 1.0179 with them, and six blocks at 2.6165, which is the add-one unigram’s 2.6091: the six-block model learned token frequencies and nothing else. Exercise (d) runs it.

Layer normalisation

For one position’s vector x\mathbf{x} of shape (d,), layer normalisation subtracts the mean of its entries, divides by their standard deviation, then scales and shifts each feature by learned amounts:

μ=1d∑i=1dxi,σ2=1d∑i=1d(xi−μ)2,x^i=xi−μσ2+ϵ,yi=γix^i+βi, \mu = \frac{1}{d}\sum_{i=1}^{d} x_i , \qquad \sigma^2 = \frac{1}{d}\sum_{i=1}^{d} (x_i - \mu)^2 , \qquad \hat{x}_i = \frac{x_i - \mu}{\sqrt{\sigma^2 + \epsilon}} , \qquad y_i = \gamma_i \hat{x}_i + \beta_i ,

with γ\gamma and β\beta of shape (d,), starting at ones and zeros. For a (B, T, d) array this runs independently at each of the BTBT positions, over the last axis: it mixes the features of one position, never different positions or batch rows.

The normalised vector has mean exactly 0:

1d∑ix^i=1σ2+ϵ(1d∑ixi−μ)=μ−μσ2+ϵ=0. \frac{1}{d}\sum_i \hat{x}_i = \frac{1}{\sqrt{\sigma^2 + \epsilon}} \Big(\frac{1}{d}\sum_i x_i - \mu\Big) = \frac{\mu - \mu}{\sqrt{\sigma^2 + \epsilon}} = 0 .

Its variance, with the same 1/d1/d (the biased estimate, which is what mean computes), is

1d∑ix^i2=1σ2+ϵ⋅1d∑i(xi−μ)2=σ2σ2+ϵ, \frac{1}{d}\sum_i \hat{x}_i^2 = \frac{1}{\sigma^2 + \epsilon}\cdot\frac{1}{d}\sum_i (x_i - \mu)^2 = \frac{\sigma^2}{\sigma^2 + \epsilon} ,

which is 1 to within ϵ/σ2\epsilon / \sigma^2. ϵ=10−5\epsilon = 10^{-5} keeps the division finite for a constant vector, where σ2=0\sigma^2 = 0. It is not always negligible: the lab model’s first block reads the sum of two tables, token and position, each drawn with standard deviation 0.02, whose per-position variance averages 7.95×10−47.95 \times 10^{-4} (about 2×0.0222 \times 0.02^2), so at initialisation the normalised variance there is 0.9876; after training the embeddings have grown and it is 0.9998. test_layer_norm_normalizes_last_axis checks mean 0 and variance 1 on inputs of variance about 25.

Normalising removes two degrees of freedom from the vector, its mean and its scale, and a layer might need them. γ\gamma and β\beta give them back as parameters: with γi=σ2+ϵ\gamma_i = \sqrt{\sigma^2 + \epsilon} and βi=μ\beta_i = \mu the layer returns unchanged any input with that mean and variance. What changes is who controls the scale. The residual stream is a sum of every sublayer’s output so far and grows as the model goes deeper: in the trained lab model the mean length of a position’s vector is 1.6 after the embeddings, 20.3 after the first block and 27.6 after the second. Each sublayer reads a normalised copy, so its input has the same scale in every block, and the scale it sees is set by its own γ\gamma, not by how much the blocks below it happened to add.

layer_norm is written with chapter 6’s ops: mean, subtraction, multiplication and a power of −0.5-0.5. Each has a gradient-checked backward rule, so the composed graph needs no new one, and test_layer_norm_gradcheck confirms it. A fused op with a hand-derived backward rule is faster and is exercise (c).

Where the norm goes matters. The original transformer applies it after the residual addition, y=LN(x+f(x))\mathbf{y} = \mathrm{LN}(\mathbf{x} + f(\mathbf{x})), post-norm. Then every block normalises the stream itself, and the identity path of the previous section passes through LL layer norms, whose Jacobians are not the identity. Pre-norm, used here as in GPT-2, normalises only the sublayer’s input:

y=x+f(LN(x)). \mathbf{y} = \mathbf{x} + f(\mathrm{LN}(\mathbf{x})) .

The stream from the embeddings to the last block is then a plain sum, and the I\mathbf{I} term of the expansion is exact. Since nothing normalises the stream itself, the model adds one final layer norm, ln_f (GGUF’s output_norm), between the last block and the output layer. Xiong and colleagues showed that post-norm transformers need the learning rate ramped up from near zero over the first steps, a warm-up, to train stably, and that pre-norm ones train without it; the lab’s runs use a constant rate from step 1.

The feed-forward sublayer

Attention moves information between positions; the feed-forward sublayer computes on each position alone. It is chapter 9’s hidden layer, applied to every one of the BTBT positions with the same weights:

FFN(x)=GELU(xWup+bup)Wdown+bdown,(B,T,d)→(B,T,4d)→(B,T,d), \mathrm{FFN}(\mathbf{x}) = \mathrm{GELU}(\mathbf{x}\mathbf{W}_{\text{up}} + \mathbf{b}_{\text{up}})\,\mathbf{W}_{\text{down}} + \mathbf{b}_{\text{down}} , \qquad (B, T, d) \to (B, T, 4d) \to (B, T, d) ,

with Wup\mathbf{W}_{\text{up}} of shape (d, 4d) and Wdown\mathbf{W}_{\text{down}} of shape (4d, d). The factor of 4 is the original transformer’s (512 to 2,048). The two matrices hold 8d2+5d8d^2 + 5d parameters against attention’s 4d2+d4d^2 + d, two thirds of each block.

The non-linearity is the Gaussian error linear unit:

GELU(x)=xΦ(x),Φ(x)=12(1+erf(x/2)), \mathrm{GELU}(x) = x\,\Phi(x) , \qquad \Phi(x) = \frac{1}{2}\Big(1 + \mathrm{erf}\big(x/\sqrt{2}\big)\Big) ,

where Φ\Phi is the cumulative distribution function of the standard normal: the input, scaled by the probability that a standard normal variable falls below it. For large positive xx, Φ(x)→1\Phi(x) \to 1 and GELU is the identity; for large negative xx it goes to 0. Unlike chapter 9’s tanh it does not saturate for positive inputs, and unlike max(0,x)\max(0, x) it is smooth, with a small negative dip whose minimum is −0.170-0.170 at x≈−0.752x \approx -0.752.

erf is not among chapter 6’s ops. The reference uses the approximation Hendrycks and Gimpel give,

GELU(x)≈12x(1+tanh(2/π(x+0.044715x3))). \mathrm{GELU}(x) \approx \frac{1}{2}\,x\left(1 + \tanh\!\Big(\sqrt{2/\pi}\,\big(x + 0.044715\,x^3\big)\Big)\right) .

The constant 2/π\sqrt{2/\pi} makes the two agree to first order at 0: erf(z)=2π(z−z3/3+⋯)\mathrm{erf}(z) = \frac{2}{\sqrt{\pi}}\big(z - z^3/3 + \cdots\big), so erf(x/2)=2/πx+O(x3)\mathrm{erf}(x/\sqrt{2}) = \sqrt{2/\pi}\,x + O(x^3), and tanh(u)=u+O(u3)\tanh(u) = u + O(u^3) gives the same linear term. The cubic coefficient 0.044715 is fitted. On a grid of 100,001 points over [−5,5][-5, 5], the largest difference between the approximation and xΦ(x)x\Phi(x) is 4.73×10−44.73 \times 10^{-4}, at x=−2.70x = -2.70; at x=1x = 1 the two give 0.84119 and 0.84134. test_gelu_values_and_gradcheck pins the approximation’s values and checks its gradient, which comes from chapter 6’s tanh, power and product.

Position

Chapter 10 showed that a causal head sees the set of earlier tokens but not their order. The model has to be told where each token is. Two ways are built here, selected by GPTConfig.pos.

Learned position embeddings (pos="learned") give each position t<Ct < C, for a maximum context CC, a trained vector: a table P\mathbf{P} of shape (C, d), drawn like the token table from N(0,0.022)N(0, 0.02^2). Chapter 9 drew its embeddings from N(0,1)N(0, 1); 0.02 is the standard deviation GPT-2’s released code uses for its token table. The first block reads the tables only through ln1, which removes their scale, so the first sublayer is blind to it; what the small scale changes is the residual stream, where the sublayers’ outputs are not swamped by the embeddings (in the lab model at initialisation, a position’s vector has mean length 0.23 after the embeddings and 1.72 after the first block). The model’s input is the token embedding plus the row for its position,

xb,t=Eidsb,t+Pt,(B,T,d)+(T,d)→(B,T,d), \mathbf{x}_{b,t} = \mathbf{E}_{\text{ids}_{b,t}} + \mathbf{P}_t , \qquad (B, T, d) + (T, d) \to (B, T, d) ,

with the (T, d) rows broadcast over the batch. Position is now part of every vector, and a head’s projections can use it: a query can, for example, look for keys whose position part marks the position just before its own. The cost is a fixed maximum length. There is no row for position CC, and GPT raises ValueError for longer input, which test_gpt_rejects_sequences_longer_than_context checks. GPT-2’s table (pos_embd in GGUF) has 1,024 rows.

Rotary position embeddings, RoPE (pos="rope"), add nothing to the input. They rotate each head’s queries and keys by angles proportional to their position, after the projections and before the scores. Take a query or key of head width dhd_h (even) at position mm, and group its features in pairs (x2i,x2i+1)(x_{2i}, x_{2i+1}) for i=0,…,dh/2−1i = 0, \ldots, d_h/2 - 1. Rotate pair ii by the angle mθim\theta_i, with

θi=10000−2i/dh,(x2i′x2i+1′)=R(mθi)(x2ix2i+1),R(α)=(cosα−sinαsinαcosα). \theta_i = 10000^{-2i/d_h} , \qquad \begin{pmatrix} x'_{2i} \\ x'_{2i+1} \end{pmatrix} = \mathbf{R}(m\theta_i) \begin{pmatrix} x_{2i} \\ x_{2i+1} \end{pmatrix} , \qquad \mathbf{R}(\alpha) = \begin{pmatrix} \cos\alpha & -\sin\alpha \\ \sin\alpha & \cos\alpha \end{pmatrix} .

The frequencies fall geometrically. In the lab model, dh=16d_h = 16: pair 0 turns by 1 radian per position and repeats every 2π≈6.32\pi \approx 6.3 positions, and pair 7 turns by 10−3.510^{-3.5} radians and repeats every 19,869. Fast pairs distinguish nearby offsets; slow ones change little over a whole window.

What makes this a position encoding is what it does to a score. A 2 × 2 rotation matrix satisfies R(α)⊤=R(−α)\mathbf{R}(\alpha)^\top = \mathbf{R}(-\alpha) (transposing flips the sign of the sines) and R(α)R(β)=R(α+β)\mathbf{R}(\alpha)\mathbf{R}(\beta) = \mathbf{R}(\alpha + \beta) (the angle-addition formulas). Write q(i)\mathbf{q}^{(i)} and k(i)\mathbf{k}^{(i)} for pair ii of a query at position mm and a key at position nn, each of shape (2,). The dot product is a sum over pairs, and for each pair

(R(mθi)q(i))⊤(R(nθi)k(i))=q(i)⊤R(−mθi)R(nθi)k(i)=q(i)⊤R((n−m)θi)k(i). \big(\mathbf{R}(m\theta_i)\mathbf{q}^{(i)}\big)^\top \big(\mathbf{R}(n\theta_i)\mathbf{k}^{(i)}\big) = \mathbf{q}^{(i)\top} \mathbf{R}(-m\theta_i)\mathbf{R}(n\theta_i)\,\mathbf{k}^{(i)} = \mathbf{q}^{(i)\top} \mathbf{R}\big((n - m)\theta_i\big)\,\mathbf{k}^{(i)} .

Summing over ii: the rotated score is the unrotated query against the key rotated by (n−m)θi(n - m)\theta_i. It depends on the positions only through their difference n−mn - m. The same query and key 4 positions apart give the same score at positions (7,3)(7, 3), (4,0)(4, 0) and (12,8)(12, 8), and a different one at (7,4)(7, 4); test_rope_scores_depend_only_on_relative_position checks exactly those. A rotation also preserves length, ∥Rx∥=∥x∥\lVert \mathbf{R}\mathbf{x} \rVert = \lVert \mathbf{x} \rVert, since R⊤R=I\mathbf{R}^\top\mathbf{R} = \mathbf{I}, so RoPE changes the angles between queries and keys and never their sizes; test_rope_preserves_norms_and_gradchecks checks that and that position 0 is left alone. Values are not rotated: position enters only through which keys a query matches.

With no table, a RoPE model has no maximum length of its own: GPTConfig.context bounds its input only because GPT checks it. Whether the scores it learned at offsets up to its training length mean anything at larger offsets is a separate question, which exercise (e) asks of the tiny corpus.

The rotation needs the pair (−x2i+1,x2i)(-x_{2i+1}, x_{2i}) for each pair (x2i,x2i+1)(x_{2i}, x_{2i+1}). Tensor has no op that indexes or permutes features, so rope gets it from a product with a fixed (d_h, d_h) matrix S\mathbf{S}, with S2i+1,2i=−1S_{2i+1, 2i} = -1, S2i,2i+1=1S_{2i, 2i+1} = 1 and zeros elsewhere: (xS)2i=∑kxkSk,2i=−x2i+1(\mathbf{x}\mathbf{S})_{2i} = \sum_k x_k S_{k, 2i} = -x_{2i+1} and (xS)2i+1=x2i(\mathbf{x}\mathbf{S})_{2i+1} = x_{2i}. Then

x′=x⊙c+(xS)⊙s, \mathbf{x}' = \mathbf{x} \odot \mathbf{c} + (\mathbf{x}\mathbf{S}) \odot \mathbf{s} ,

with c\mathbf{c} and s\mathbf{s} of shape (T, d_h) holding cos(mθi)\cos(m\theta_i) and sin(mθi)\sin(m\theta_i) in both columns of pair ii at row mm. Component 2i2i is x2icos−x2i+1sinx_{2i}\cos - x_{2i+1}\sin and component 2i+12i+1 is x2i+1cos+x2isinx_{2i+1}\cos + x_{2i}\sin, the two rows of R\mathbf{R}. The product costs dh2d_h^2 multiply-adds per vector where indexing would cost dhd_h, which at dh=16d_h = 16 does not matter, and its backward rule is chapter 6’s @. Some implementations pair feature ii with feature i+dh/2i + d_h/2 instead of adjacent features; the derivation is the same with the pairs renamed, but weights trained with one pairing are wrong under the other.

The whole model

The figure puts the pieces together: one pre-norm block, read from the bottom, with the shape of the array on every edge.

One pre-norm transformer block, with the shape of the array on every edge Read bottom to top. The block input x has shape (B, T, d). It splits: a bold residual line runs up the left side, and the main path goes through a LayerNorm, shape (B, T, d), to multi-head attention, drawn as four parallel heads, head 1 to head 4, each computing causal attention at width d over H, so each head's output has shape (B, T, d over H). The heads' outputs are concatenated and joined by the output projection, d to d, shape (B, T, d). The first add node sums the attention output with the residual line from x, shape (B, T, d). From there a second bold residual line runs up the right side, and the main path goes through a second LayerNorm, shape (B, T, d), then up, which projects d to 4d, shape (B, T, 4d), then GELU, shape (B, T, 4d), then down, which projects 4d back to d, shape (B, T, d). The second add node sums that with the second residual line. The result, shape (B, T, d), goes to the next block, or after the last block to the final LayerNorm and the output head. residual: x passes through unchanged residual LayerNorm head 1 head 2 head 3 head 4 output projection LayerNorm GELU up (d → 4d) down (4d → d) (B, T, d) (B, T, d) (B, T, d) (B, T, d) (B, T, d) (B, T, 4d) (B, T, 4d) (B, T, d) (B, T, d) (B, T, d/H) each block input x to the next block, or to the final LayerNorm and the head concatenate, then d → d

GPT is: token embedding, plus the position table if there is one; LL blocks; ln_f; and the output layer head, a bias-free Linear from dd to VV. Its input is (B, T) ids with T≤CT \le C, its output (B, T, V) logits, the contract of chapters 8 and 9, so train, evaluate and generate take it unchanged.

Its parameters, for vocabulary VV, context CC, width dd and LL blocks: the token table VdVd; the position table CdCd (learned positions only); per block, two layer norms 2⋅2d2 \cdot 2d, attention 4d2+d4d^2 + d, and the feed-forward pair (4d2+4d)+(4d2+d)(4d^2 + 4d) + (4d^2 + d), a total of 12d2+10d12d^2 + 10d; ln_f 2d2d; and the head dVdV:

N=Vd+Cd+L(12d2+10d)+2d+dV. N = Vd + Cd + L\,(12d^2 + 10d) + 2d + dV .

test_gpt_parameter_count checks it for V=50V = 50, C=16C = 16, d=32d = 32, L=3L = 3. For the lab’s configuration, V=512V = 512, C=64C = 64, d=64d = 64, H=4H = 4, L=2L = 2, it is 32,768+4,096+2×49,792+128+32,768=169,34432{,}768 + 4{,}096 + 2 \times 49{,}792 + 128 + 32{,}768 = 169{,}344; with RoPE, 165,248. At this size the two embedding tables and the head are 41% of the model. The blocks’ 12Ld212Ld^2 outweighs the two VdVd matrices only when 12Ld2≫2Vd12Ld^2 \gg 2Vd, that is 6Ld≫V6Ld \gg V; here 6Ld=7686Ld = 768 against V=512V = 512. The tiny corpus’s model, with V=17V = 17, C=16C = 16 and d=32d = 32, has 26,880.

test_gpt_gradcheck checks the whole model, with each position scheme, at V=5V = 5, C=4C = 4, d=4d = 4, H=2H = 2 and one block: 296 parameters with learned positions, every one perturbed and compared with backpropagation through embedding, layer norm, multi-head attention, RoPE, GELU, both residual additions and the head.

Mixture of experts

The feed-forward sublayer holds two thirds of each block’s weights, and every token is multiplied by all of them. A mixture-of-experts (MoE) sublayer keeps many feed-forward networks, the experts, and sends each token to a few. Storage grows with the number of experts; the arithmetic per token grows only with the number each token uses. GPTConfig(n_experts=E, top_k=k) builds one in every block in place of up and down, and raises ValueError unless 1≤k≤E1 \le k \le E; n_experts=0, the default, is the dense block above.

Routing. Take one position’s normalised vector h\mathbf{h}, shape (d,), the output of ln2. Expert ii, for i=1,…,Ei = 1, \ldots, E, is the sublayer of the previous section with its own weights, FFNi(h)\mathrm{FFN}_i(\mathbf{h}), shape (d,). The router is a bias-free Linear with weight Wr\mathbf{W}_r of shape (d, E), giving one logit per expert, z=hWr\mathbf{z} = \mathbf{h}\mathbf{W}_r, shape (E,). Let KK be the set of the kk experts with the largest logits. The gates are a softmax over those kk logits alone,

gi=ezi∑j∈Kezj for i∈K,gi=0 otherwise,y=∑i∈KgiFFNi(h), g_i = \frac{e^{z_i}}{\sum_{j \in K} e^{z_j}} \text{ for } i \in K , \qquad g_i = 0 \text{ otherwise} , \qquad \mathbf{y} = \sum_{i \in K} g_i\, \mathrm{FFN}_i(\mathbf{h}) ,

with y\mathbf{y} of shape (d,), added to the residual stream as before. The gates are positive and sum to 1 over KK, so y\mathbf{y} is a weighted average of kk experts’ outputs. Setting zi=−∞z_i = -\infty for every expert outside KK and taking a softmax over all EE gives the same numbers, since e−∞=0e^{-\infty} = 0 drops those terms from the sum; this is how Shazeer and colleagues wrote it, as Softmax(KeepTopK(⋅,k))\mathrm{Softmax}(\mathrm{KeepTopK}(\cdot, k)), and Mixtral’s router is the same with k=2k = 2. The figure follows one position through a router with E=4E = 4 and k=2k = 2: the logits (1.3,−0.2,0.8,−1.1)(1.3, -0.2, 0.8, -1.1) keep experts 1 and 3, and e1.3/(e1.3+e0.8)=1/(1+e−0.5)=0.6225e^{1.3}/(e^{1.3} + e^{0.8}) = 1/(1 + e^{-0.5}) = 0.6225.

A mixture-of-experts feed-forward sublayer with four experts and top-2 routing, for one position Read bottom to top. One position's normalised vector h, shape (d,), goes both to the router and to every expert. The router, a projection from d to E, gives four logits, z = (1.3, -0.2, 0.8, -1.1). Top-2 keeps experts 1 and 3 and takes a softmax over their two logits only, so the gates are g = (0.62, 0, 0.38, 0), which sum to 1. Experts 1 and 3, each up from d to 4d, GELU, and down to d, compute their outputs, shape (d,). Experts 2 and 4 have gate 0; an inference engine skips them. Each chosen output is multiplied by its gate, 0.62 and 0.38, and the two products are added. The sum, shape (d,), goes to the block's residual addition. top-2, softmax expert 1 expert 2 expert 3 expert 4 router (d → E) z = (1.3, −0.2, 0.8, −1.1) g = (0.62, 0, 0.38, 0) (d,) (d,) (d,) (d,) × 0.62 × 0.38 h, one position after the second LayerNorm to the block's residual addition gate 0: skipped gate 0: skipped

What the router learns from. The set KK changes only when two logits cross, so for a small change in z\mathbf{z} it is constant, and the gates are a smooth function of the kept logits. Write ui=FFNi(h)\mathbf{u}_i = \mathrm{FFN}_i(\mathbf{h}), a=∂L/∂y\mathbf{a} = \partial L / \partial \mathbf{y} (both (d,)) and si=a⋅uis_i = \mathbf{a} \cdot \mathbf{u}_i, how much the loss changes per unit of gate ii. The softmax Jacobian of chapter 10, restricted to KK, is ∂gi/∂zj=gi(δij−gj)\partial g_i / \partial z_j = g_i(\delta_{ij} - g_j) for i,j∈Ki, j \in K, so for j∈Kj \in K

∂L∂zj=∑i∈Ksigi(δij−gj)=gj(sj−∑i∈Kgisi), \frac{\partial L}{\partial z_j} = \sum_{i \in K} s_i\, g_i (\delta_{ij} - g_j) = g_j\Big(s_j - \sum_{i \in K} g_i s_i\Big) ,

and ∂L/∂zj=0\partial L / \partial z_j = 0 for every jj outside KK. The router raises the logit of a chosen expert whose output helps more than the gate-weighted average of the chosen, and lowers the others. It gets no signal about the experts it did not choose. With k=1k = 1 the single gate is ezj/ezj=1e^{z_j}/e^{z_j} = 1 whatever zjz_j is, the bracket is sj−sj=0s_j - s_j = 0, and the router learns nothing from the loss at all; test_router_learns_from_the_loss_only_when_top_k_exceeds_one checks both cases. The Switch Transformer, which routes each token to one expert, avoids this by using the full softmax probability pi=ezi/∑j=1Eezjp_i = e^{z_i} / \sum_{j=1}^{E} e^{z_j} as the gate instead of renormalising over KK.

Active and total parameters. Count one block. The two layer norms and attention are shared by every token, 4d+4d2+d4d + 4d^2 + d. The router has dEdE weights. Each expert has the dense sublayer’s 8d2+5d8d^2 + 5d, so the block stores E(8d2+5d)E(8d^2 + 5d) expert parameters and a token uses k(8d2+5d)k(8d^2 + 5d) of them: a fraction k/Ek/E of the feed-forward weights is active per token. For the whole model, with the embedding tables and head as before,

Ntotal=Vd+Cd+L(5d+4d2+dE+E(8d2+5d))+2d+dV,Nactive=Ntotal−L(E−k)(8d2+5d), N_{\text{total}} = Vd + Cd + L\big(5d + 4d^2 + dE + E(8d^2 + 5d)\big) + 2d + dV , \qquad N_{\text{active}} = N_{\text{total}} - L\,(E - k)(8d^2 + 5d) ,

and test_gpt_moe_parameter_count checks the first. The active count keeps the embedding tables, as published counts do, although a lookup multiplies nothing (chapter 3). For V=512V = 512, C=64C = 64, d=32d = 32, L=2L = 2, E=4E = 4 and k=2k = 2, Ntotal=110,464N_{\text{total}} = 110{,}464 and Nactive=77,056N_{\text{active}} = 77{,}056; the dense model of the same width has 60,096.

The reader’s ornith-1.5-35b-a3b is such a model at scale. Its config.json on Hugging Face (repository ornith-ai/Ornith-1.5-35B-A3B, revision 10fbf86, fetched 2026-09-29) gives num_experts 256 and num_experts_per_tok 8 in each of 40 layers of width 2,048, experts of inner width 512 (moe_intermediate_size), and a shared expert of the same width that every token uses, so a token runs through nine expert sublayers per layer. Its experts are gated sublayers, each three matrices of 2,048×5122{,}048 \times 512 weights (ffn_gate_exp, ffn_up_exp and ffn_down_exp in the GGUF specification’s list of tensor names; the files llama.cpp writes store each layer’s experts stacked in one tensor per matrix, blk.N.ffn_gate_exps, blk.N.ffn_up_exps and blk.N.ffn_down_exps, by gguf-py’s constants.py at commit da89bb3), 3,145,728 weights per expert. The routed experts hold 40×256×3,145,728=32.2×10940 \times 256 \times 3{,}145{,}728 = 32.2 \times 10^9 weights, about 90% of the 35.95 billion parameters the repository’s weights hold, and a token uses 8/256=1/328/256 = 1/32 of them, 1.0×1091.0 \times 10^9. Removing the 248 unused experts per layer leaves 4.7×1094.7 \times 10^9, and that still counts parts ordinary text decoding does not run: the model also ships a vision encoder and a multi-token-prediction layer (mtp_num_hidden_layers 1) with experts of its own. The model card’s “~3B activated parameters per token” is those 1.0 billion routed weights plus what every text token runs through: the attention layers, the shared experts, the routers, the embeddings and the head. The attention layers are not all chapter 10’s: the same file’s layer_types make every fourth layer full attention and the other 30 of the 40 linear-attention recurrences, a hybrid design chapter 15 reads. The experts are the same in every layer.

Computed densely, for clarity. MoE computes every expert for every position and multiplies each output by its gate, which is 0 for the E−kE - k experts outside KK. The result is exactly y\mathbf{y}, the mask is a constant array, and the gradient comes from chapter 6’s ops with no new backward rule: test_moe_gradcheck checks it through the router, the experts and the balance loss below. The cost is E/kE/k times the arithmetic the sublayer needs. An inference engine computes only the kk chosen experts, and chapter 12’s forward_cached does the same; chapter 14 shows that it is also what an MoE’s decoding speed depends on.

Expert collapse. Nothing in the loss asks the router to spread tokens. Shazeer and colleagues observed that the gating network “tends to converge to a state where it always produces large weights for the same few experts. This imbalance is self-reinforcing, as the favored experts are trained more rapidly and thus are selected even more by the gating network.” An expert that is rarely chosen gets few gradient steps and stays poor, so it stays unchosen; its weights are stored and never used. The Switch Transformer adds an auxiliary loss. Over a batch of NN positions, let fif_i be the share of the NkNk expert assignments that went to expert ii, and PiP_i the mean over positions of the router’s full softmax probability pn,ip_{n,i}:

fi=1Nk∑n=1N1[i∈Kn],Pi=1N∑n=1Npn,i,Laux=E∑i=1EfiPi, f_i = \frac{1}{Nk}\sum_{n=1}^{N} \mathbf{1}[i \in K_n] , \qquad P_i = \frac{1}{N}\sum_{n=1}^{N} p_{n,i} , \qquad \mathcal{L}_{\text{aux}} = E \sum_{i=1}^{E} f_i P_i ,

with f\mathbf{f} and P\mathbf{P} of shape (E,), each summing to 1. (The paper routes to one expert, k=1k = 1, where fif_i is the fraction of tokens; dividing by kk keeps ∑ifi=1\sum_i f_i = 1 for any kk.) The counts fif_i come from a top-kk selection, a step function of the logits, and have no gradient, so the loss’s only path to the router is through P\mathbf{P}, and along it the loads act as constant weights: ∂Laux/∂Pi=Efi\partial \mathcal{L}_{\text{aux}} / \partial P_i = E f_i. Each PiP_i is a mean of softmax outputs, ∂Pi/∂zn,j=1Npn,i(δij−pn,j)\partial P_i / \partial z_{n,j} = \frac{1}{N} p_{n,i}(\delta_{ij} - p_{n,j}) by chapter 10’s Jacobian over all EE logits, and the chain rule for position nn gives

∂Laux∂zn,j=∑iEfi⋅1Npn,i(δij−pn,j)=EN(fjpn,j−pn,j∑ifipn,i)=ENpn,j(fj−∑ifipn,i): \frac{\partial \mathcal{L}_{\text{aux}}}{\partial z_{n,j}} = \sum_i E f_i \cdot \frac{1}{N} p_{n,i}(\delta_{ij} - p_{n,j}) = \frac{E}{N}\Big(f_j\, p_{n,j} - p_{n,j} \sum_{i} f_i\, p_{n,i}\Big) = \frac{E}{N}\, p_{n,j}\Big(f_j - \sum_{i} f_i\, p_{n,i}\Big) :

gradient descent lowers the logit of every expert whose load fjf_j is above the probability-weighted average load ∑ifipn,i\sum_i f_i\, p_{n,i} and raises the others. The loss pushes router probability away from the experts that are receiving the most tokens now, and with the probability, at the next top-kk, the tokens. That is the mechanism that balances the load, and when the load is balanced it stops: with every fi=1/Ef_i = 1/E, the bracket is 1/E−1E∑ipn,i=01/E - \frac{1}{E}\sum_i p_{n,i} = 0 for every expert at every position, whatever the probabilities are.

The loss’s value is not itself a measure of balance, and an uneven load does not always score worse than a uniform one. With P\mathbf{P} uniform it is E∑ifi/E=1E \sum_i f_i / E = 1 whatever the loads are. With f≠P\mathbf{f} \ne \mathbf{P} it can go below 1. Take E=2E = 2, k=1k = 1 and four positions: three with router probabilities (0.525,0.475)(0.525, 0.475), each sent to its more probable expert 1, and one with (0.00005,0.99995)(0.00005, 0.99995), sent to expert 2. Then f=(0.75,0.25)\mathbf{f} = (0.75, 0.25) and P=(0.394,0.606)\mathbf{P} = (0.394, 0.606), and Laux=2(0.75×0.394+0.25×0.606)=0.894\mathcal{L}_{\text{aux}} = 2(0.75 \times 0.394 + 0.25 \times 0.606) = 0.894 (test_aux_falls_below_one_when_loads_and_probabilities_differ builds this case in MoE): expert 1 takes three quarters of the tokens with under two fifths of the mean probability, because the positions it takes are nearly undecided. Uniform balance is the loss’s minimum only along the diagonal f=P\mathbf{f} = \mathbf{P}, where each expert’s share of the tokens equals its mean probability. There the loss is E∑iPi2E \sum_i P_i^2, and the Cauchy–Schwarz inequality applied to P\mathbf{P} and the all-ones vector, (∑iPi⋅1)2≤(∑iPi2)(∑i12)\big(\sum_i P_i \cdot 1\big)^2 \le \big(\sum_i P_i^2\big)\big(\sum_i 1^2\big), with ∑iPi=1\sum_i P_i = 1 on the left and EE in the last sum, gives 1≤E∑iPi21 \le E \sum_i P_i^2, with equality exactly when P\mathbf{P} is parallel to the ones vector, Pi=1/EP_i = 1/E for every ii. The Switch Transformer paper says the loss “encourages uniform routing since it is minimized under a uniform distribution” and that “the P-vector is differentiable, but the f-vector is not” (Section 2.2); the first holds on that diagonal, and the gradient above is what moves the router toward it. Multiplying by EE makes the uniform value 1 for any number of experts. At the other end, every token sent to the same kk experts by a router certain of them gives E/kE/k, which is EE for k=1k = 1; test_aux_is_one_under_uniform_routing_and_larger_when_collapsed checks both ends with k=1k = 1. Training adds αLaux\alpha\,\mathcal{L}_{\text{aux}} to the cross-entropy, summed over blocks by GPT.aux_loss(); the Switch Transformer used α=10−2\alpha = 10^{-2}, as the lab does.

Measured. On Persuasion, with the lab’s tokenizer and context and two blocks, an MoE of width 32 with E=4E = 4 and k=2k = 2 (Ntotal=110,464N_{\text{total}} = 110{,}464, Nactive=77,056N_{\text{active}} = 77{,}056) was trained against dense models of widths 36 and 40, whose 71,064 and 82,800 parameters bracket its active count (no width matches it exactly: the dense block’s sublayer is fixed at 4d4d), all for 500 steps from seed 0 with α=10−2\alpha = 10^{-2}. The lab section below shows the run: held-out 3.8037 for width 36, 3.7161 for width 40, and 3.7390 for the MoE, between the two. Over 1,000 steps and two seeds, in a separate sweep on straylight on the same data, the order held: width 36 reached 3.4629 and 3.4514, the MoE 3.4597 and 3.4232, width 40 3.3963 and 3.4371, and a dense model of width 48, whose 108,576 parameters roughly match the MoE’s total, 3.3314 and 3.3740. At this size an MoE performs about like a dense model of its active size and well short of one of its stored size; an MoE with E=8E = 8 (177,536 stored, 77,312 active) reached 3.4273 and 3.3875 in the same sweep, level with width 40. The balance loss did not help held-out loss here: without it the two seeds reached 3.4121 and 3.4292. What it changes is the load, which exercise (g) reads. Each MoE step took 109 ms against 43 and 49 for the dense models, on straylight, because every expert is computed.

Training

The model trains with chapter 8’s train and chapter 9’s Adam, at a learning rate of 3×10−33 \times 10^{-3}, and is scored with chapter 8’s evaluate. It does not start near uniform, as chapter 9 arranged for its MLP. The head is a plain Linear whose input, the output of ln_f, has unit variance across its dd coordinates, so by chapter 9’s derivation the logits start with variance 1/31/3 across the vocabulary (0.333 measured on the lab model), and chapter 9’s expansion of the loss predicts a first loss about 12⋅13=0.17\frac{1}{2} \cdot \frac{1}{3} = 0.17 above logV\log V. The lab model scores 6.379 on its held-out tokens at initialisation, 0.14 above log512=6.238\log 512 = 6.238. It costs one step: Adam’s first update moves every weight by about the learning rate whatever the size of its gradient, and after it the held-out loss is 6.147, already below logV\log V.

The tiny corpus. test_gpt_learns_the_tiny_corpus trains the d=32d = 32, H=4H = 4, two-block model for 300 steps of 16 windows of 16 tokens and requires a held-out loss below 1.1. The reference reaches 1.0179 with learned positions and 1.0220 with RoPE, against 1.3689 for chapter 8’s trained bigram and 0.9933 for chapter 9’s MLP. The transformer does not beat the MLP here, for two reasons. The grammar in make_tiny_corpus.py gives it nothing to find: the next token’s distribution is fixed by the last three tokens (after a noun, only the token before its determiner, . or a verb, says whether the noun was the subject or the object; chapter 9 works through the cases), and the MLP with n=3n = 3 sees all three. And the two numbers are not scored alike. Chapter 9 scored the MLP on windows of 64, so only the first positions of 21 windows lacked history; the transformer, whose context is 16, is scored on windows of 16, and 84 windows start cold. Scored on windows of 16, the same MLP gets 1.0212, between the two transformers. Longer training helps the transformer a little: 1,000 steps of 32 windows reach 1.0074 with learned positions and 1.0104 with RoPE.

Persuasion. test_gpt_beats_unigram_on_persuasion trains a 300-token BPE on the first 30,000 characters of data/persuasion.txt, which encode to 20,567 tokens, holds out the last 10%, and trains the same small model for 100 steps on windows of 32. It must beat the add-one unigram’s held-out cross-entropy by 0.3 nats; the reference scores 3.6279 against 4.2053. The whole lab file takes about 18 seconds.

The lab’s run, train_gpt on all of Persuasion with its defaults (a 512-token BPE, d=64d = 64, four heads, two blocks, context 64, 2,000 steps of 16 windows), is shown in the lab section below. It ends at 3.012 nats per token on 20,000 held-out tokens, the first 20,000 of the last 10%. On the same tokens, scored with every token’s actual predecessor rather than in windows, an add-one unigram gets 5.238 and an add-one counting bigram 3.954. Chapter 8’s exercise (f) scored the whole 10%, 21,389 tokens, with the same tokenizer: 5.2352 for the unigram, 3.9509 for the add-one bigram and 3.7726 for its trained bigram, the strongest of the three baselines.

Threads. numpy’s matrix products call OpenBLAS, which by default splits each product across every hardware thread. The products in this model are small, 1,024 rows of 64 by a (64, 64) matrix for a projection, and the cost of waking and synchronising the threads for each one exceeds the arithmetic saved. On talos, the machine this chapter was run on, an 8-thread laptop processor (a 13th-generation Intel Core i3-1315U), 60 training steps of the lab model take a median 313 ms per step with the default and 96 ms with OPENBLAS_NUM_THREADS=1, over five runs of each. The book’s training commands set it.

Memory. Chapter 8’s free_graph unlinks each step’s graph so reference counting frees it at once. The lab model shows why that is not optional. Each step’s graph holds the activations of every op, many of them (16, 64, 256) arrays in the feed-forward sublayer and (16, 4, 64, 64) score arrays in attention. Without free_graph, measured with the lab model on Persuasion’s tokens and one OpenBLAS thread, resident memory is 1,173 MB after 10 steps and 4,410 MB after 30. From there it grows slowly, to 4,772 MB at step 150: the cycle collector is now reclaiming old graphs about as fast as new ones are abandoned, with gigabytes of them waiting at any moment. With it, the same 60 steps peak at 248 MB.

Training on your own notes

train_gpt accepts a directory as its corpus: every .org, .md and .txt file under it, recursively, in sorted order, joined with blank lines. Point it at ~/org and it trains a tokenizer and a model on your notes. Undecodable bytes are replaced with U+FFFD rather than stopping the run (test_load_corpus_tolerates_invalid_utf8), since a notes directory accumulates files in older encodings.

What it writes is private data. A language model is trained to assign high probability to its training text, and a small model trained for thousands of steps on a small corpus can reproduce stretches of it when sampled or prompted with its beginning. The tokenizer leaks too: its merges are the most frequent byte sequences of the corpus, and in a notes directory those include names, project names and whatever else recurs. So train_gpt refuses to write inside the repository, or inside any git work tree: it resolves OUT_DIR and raises SystemExit before reading the corpus if the path is the repository root or below it, or if it or any directory above it holds a .git. test_refuses_to_write_inside_the_repository tries an absolute path, a relative one, one through .., one through a symbolic link and the root itself, and checks that nothing is created; test_refuses_to_write_inside_any_git_work_tree covers other repositories. The tests never touch ~/org; the lab section describes what to look for.

Walkthrough

The reference modules are py/tinygpt/transformer.py and py/tinygpt/train_gpt.py.

def layer_norm(x, gamma, beta, eps=1e-5):
    """Normalize the last axis of x to mean 0, variance 1, then scale by gamma and shift by beta."""
    mu = x.mean(axis=-1, keepdims=True)                 # (..., 1)
    xc = x - mu
    var = (xc * xc).mean(axis=-1, keepdims=True)        # (..., 1), biased: divides by d
    return xc * (var + eps) ** -0.5 * gamma + beta      # (..., d)


class LayerNorm:
    def __init__(self, d):
        self.gamma = Tensor(np.ones(d))
        self.beta = Tensor(np.zeros(d))

    def parameters(self):
        return [self.gamma, self.beta]

    def __call__(self, x):
        return layer_norm(x, self.gamma, self.beta)

layer_norm normalises the last axis whatever the leading axes are. mean(axis=-1, keepdims=True) keeps a length-1 axis so the (..., 1) mean and variance broadcast back against the (..., d) input, and chapter 6’s _unbroadcast sums their gradients over the reduced axis. The variance is computed from the centred values xc, the biased 1/d1/d form derived above. (var + eps) ** -0.5 is chapter 6’s power op. gamma and beta, shape (d,), broadcast over every position. LayerNorm holds the two parameter vectors in the order gamma, beta.

def gelu(x):
    """GELU, tanh approximation: 0.5 x (1 + tanh(sqrt(2/pi) (x + 0.044715 x^3)))."""
    return 0.5 * x * (1.0 + ((x + 0.044715 * x ** 3) * np.sqrt(2.0 / np.pi)).tanh())

The tanh approximation, term by term. The constants are Python floats, so each product lifts them into constant Tensors, and the gradient reaches x through every place it appears, the linear factor and both terms of the tanh’s argument, which chapter 6’s accumulation adds.

def _rope_tables(positions, d, base=10000.0):
    theta = base ** (-np.arange(0, d, 2) / d)              # (d/2,) one frequency per pair
    angles = np.outer(positions, theta)                    # (T, d/2)
    cos = np.repeat(np.cos(angles), 2, axis=-1)            # (T, d): both members of a pair
    sin = np.repeat(np.sin(angles), 2, axis=-1)
    swap = np.zeros((d, d))                                # (x @ swap)[2i] = -x[2i+1], [2i+1] = x[2i]
    swap[np.arange(1, d, 2), np.arange(0, d, 2)] = -1.0
    swap[np.arange(0, d, 2), np.arange(1, d, 2)] = 1.0
    return cos, sin, swap


def rope(x, positions, base=10000.0):
    """Rotate each pair (x[2i], x[2i+1]) of x (..., T, d) by angle position * base^(-2i/d)."""
    cos, sin, swap = _rope_tables(np.asarray(positions), x.shape[-1], base)
    return x * cos + (x @ swap) * sin

_rope_tables builds the three constants for positions of any shape (T,) and head width d: theta has one frequency per pair, (d/2,); np.outer gives the (T, d/2) angles; np.repeat(..., 2, axis=-1) writes each pair’s cosine and sine into both of its columns, (T, d); and swap is the matrix S\mathbf{S}. Chapter 12’s KV cache imports it. rope works on any (..., T, d) Tensor: the (T, d) tables broadcast over the leading axes, and x @ swap is a product with a constant, whose gradient to x is gS⊤\mathbf{g}\mathbf{S}^\top, the inverse rotation of the pair.

class MultiHeadAttention:
    """n_heads heads of width d_model / n_heads side by side, then one output projection.

    causal=False drops the mask, so every position reads every other (chapter 15's encoder).
    """

    def __init__(self, cfg, rng, causal=True):
        d = cfg.d_model
        self.n_heads, self.rope, self.causal = cfg.n_heads, cfg.pos == "rope", causal
        self.query = Linear(d, d, rng, bias=False)
        self.key = Linear(d, d, rng, bias=False)
        self.value = Linear(d, d, rng, bias=False)
        self.proj = Linear(d, d, rng)

    def parameters(self):
        return [p for m in (self.query, self.key, self.value, self.proj) for p in m.parameters()]

    def heads(self, x):
        """(B, T, d) -> (B, H, T, d / H): split the last axis into heads, move heads before time."""
        B, T, d = x.shape
        return x.reshape(B, T, self.n_heads, d // self.n_heads).transpose(1, 2)

    def __call__(self, x):
        B, T, d = x.shape
        q, k, v = self.heads(self.query(x)), self.heads(self.key(x)), self.heads(self.value(x))
        if self.rope:
            q, k = rope(q, np.arange(T)), rope(k, np.arange(T))
        y = attention(q, k, v, causal_mask(T) if self.causal else None)  # (B, H, T, d / H)
        return self.proj(y.transpose(1, 2).reshape(B, T, d))

__init__ draws the four projections from rng in the order query, key, value, output; the first three have no bias, like chapter 10’s head, and proj has one. heads is the reshape and transpose derived above; reshape(B, T, self.n_heads, d // self.n_heads) splits the feature axis and transpose(1, 2) swaps time and heads. RoPE, when configured, rotates q and k after the split, at head width, with positions 0,…,T−10, \ldots, T-1. attention is chapter 10’s function on (B, H, T, d_h) arrays with the (T, T) mask broadcast over batch and heads; causal, true by default and drawing nothing from rng, is the switch chapter 15’s encoder turns off, passing no mask at all. The last line merges the heads, (B, H, T, d_h) to (B, T, H, d_h) to (B, T, d), and projects.

class MoE:
    """n_experts feed-forward sublayers and a router; each position uses the top_k its router scores highest.

    Every expert is computed for every position and weighted by its gate, zero for the experts not
    chosen: exact gradients from existing ops, at n_experts / top_k times the arithmetic an engine does.
    """

    def __init__(self, cfg, rng):
        d, E, h = cfg.d_model, cfg.n_experts, 4 * cfg.d_model
        self.top_k = cfg.top_k
        self.router = Linear(d, E, rng, bias=False)
        self.up = Tensor(rng.uniform(-d ** -0.5, d ** -0.5, size=(E, d, h)))     # Linear's init, per expert
        self.up_bias = Tensor(np.zeros((E, h)))
        self.down = Tensor(rng.uniform(-h ** -0.5, h ** -0.5, size=(E, h, d)))
        self.down_bias = Tensor(np.zeros((E, d)))
        self.aux = None                                   # load-balancing loss of the last call

    def parameters(self):
        return [self.router.weight, self.up, self.up_bias, self.down, self.down_bias]

    def __call__(self, x):
        B, T, d = x.shape
        E, N, k = self.up.shape[0], B * T, self.top_k
        x = x.reshape(N, d)                                          # every position is independent
        z = self.router(x)                                           # (N, E) router logits
        top = np.argsort(-z.data, axis=-1, kind="stable")[:, :k]     # (N, k) chosen experts
        keep = np.zeros((N, E))
        np.put_along_axis(keep, top, 1.0, axis=-1)                   # constant 0/1 mask
        e = (z - z.data.max(axis=-1, keepdims=True)).exp()           # (N, E), shifted by a constant
        gates = e * keep / (e * keep).sum(axis=-1, keepdims=True)    # softmax over the k chosen
        probs = e / e.sum(axis=-1, keepdims=True)                    # softmax over all E
        load = keep.mean(axis=0) / k                                 # (E,) share of assignments, sums to 1
        self.aux = (probs.mean(axis=0) * load).sum() * E             # Switch Transformer's balance loss
        u = gelu(x.reshape(1, N, d) @ self.up + self.up_bias.reshape(E, 1, 4 * d))   # (E, N, 4d)
        y = u @ self.down + self.down_bias.reshape(E, 1, d)          # (E, N, d): every expert's output
        w = gates.transpose(0, 1).reshape(E, N, 1)                   # (E, N, 1)
        return (y * w).sum(axis=0).reshape(B, T, d)

The experts are stored stacked, up of shape (E, d, 4d) and down of shape (E, 4d, d), drawn with Linear’s bound for their input width, with biases (E, 4d) and (E, d), so that one batched product computes every expert: x.reshape(1, N, d) @ self.up broadcasts the (1, N, d) positions against the E matrices and gives (E, N, 4d), and chapter 6’s _unbroadcast sums the gradient back over the expert axis to the positions. The positions are flattened to (N, d), N=BTN = BT, since routing treats each one alone. The top-kk choice is made on the logits’ numbers, z.data, with a stable sort so that ties go to the lower index, and written as a 0/1 array keep of shape (N, E) with np.put_along_axis. The exponentials are shifted by each row’s maximum, a constant, as chapter 10’s softmax is; gates multiplies them by keep and renormalises, which is the masked softmax, and probs is the full softmax the balance loss needs. load is f\mathbf{f}, a numpy array and so a constant, and self.aux is E∑ifiPiE \sum_i f_i P_i, kept on the layer for GPT.aux_loss to collect. The gates are moved to (E, N, 1) so they broadcast over each expert’s d outputs, and the sum over the expert axis is y\mathbf{y} for every position at once. test_moe_matches_its_definition compares the result, and the balance loss, with a loop over positions that runs only the chosen experts, for k=1k = 1, 2 and 3.

class Block:
    """Pre-norm transformer block: x + attn(norm(x)), then x + mlp(norm(x)), the mlp dense or MoE."""

    def __init__(self, cfg, rng):
        d = cfg.d_model
        self.ln1, self.attn, self.ln2 = LayerNorm(d), MultiHeadAttention(cfg, rng), LayerNorm(d)
        if cfg.n_experts:
            self.moe = MoE(cfg, rng)
        else:
            self.moe, self.up, self.down = None, Linear(d, 4 * d, rng), Linear(4 * d, d, rng)

    def parameters(self):
        ffn = [self.moe] if self.moe is not None else [self.up, self.down]
        return [p for m in (self.ln1, self.attn, self.ln2, *ffn) for p in m.parameters()]

    def __call__(self, x):
        x = x + self.attn(self.ln1(x))                    # tokens exchange information
        h = self.ln2(x)                                   # each position computes on its own
        return x + (self.moe(h) if self.moe is not None else self.down(gelu(self.up(h))))

The block is the two equations of the pre-norm design. The feed-forward sublayer is the dense pair up and down when cfg.n_experts is 0, with moe set to None, and an MoE otherwise; a dense block draws exactly the weights it drew before MoE existed, which test_dense_blocks_draw_exactly_the_weights_they_drew_before_moe pins. parameters() lists ln1, the four attention projections, ln2, then up and down or the MoE’s five arrays, in the order _forward_with in the lab’s gradient check replaces them.

class GPT:
    """Token (and learned position) embeddings, n_layers blocks, a final norm, and the output head."""

    def __init__(self, cfg, rng):
        self.cfg = cfg
        self.tok = Tensor(rng.normal(0.0, 0.02, size=(cfg.vocab_size, cfg.d_model)))
        self.pos = Tensor(rng.normal(0.0, 0.02, size=(cfg.context, cfg.d_model))) if cfg.pos == "learned" else None
        self.blocks = [Block(cfg, rng) for _ in range(cfg.n_layers)]
        self.ln_f = LayerNorm(cfg.d_model)
        self.head = Linear(cfg.d_model, cfg.vocab_size, rng, bias=False)

    def parameters(self):
        ps = [self.tok] + ([self.pos] if self.pos is not None else [])
        for m in self.blocks + [self.ln_f, self.head]:
            ps += m.parameters()
        return ps

    def aux_loss(self):
        """Sum of the MoE blocks' load-balancing losses from the last call of the model (forward_cached
        sets none), so call it after one; 0 for a dense model."""
        return sum((b.moe.aux for b in self.blocks if b.moe is not None), Tensor(0.0))

    def free_aux(self):
        """Release the graphs behind the MoE blocks' balance losses; their values stay readable."""
        for b in self.blocks:
            if b.moe is not None and b.moe.aux is not None:
                free_graph(b.moe.aux)

    def __call__(self, ids):
        ids = np.asarray(ids, dtype=np.int64)            # (B, T)
        if ids.ndim != 2 or 0 in ids.shape:
            raise ValueError(f"ids must have shape (B, T) with B, T >= 1, got {ids.shape}")
        T = ids.shape[1]
        if T > self.cfg.context:
            raise ValueError(f"sequence length {T} exceeds context {self.cfg.context}")
        if ids.min() < 0 or ids.max() >= self.cfg.vocab_size:
            raise ValueError(f"token ids must lie in [0, {self.cfg.vocab_size}), got {ids.min()}..{ids.max()}")
        x = embedding(self.tok, ids)                     # (B, T, d)
        if self.pos is not None:
            x = x + embedding(self.pos, np.arange(T))    # (T, d) broadcasts over the batch
        for block in self.blocks:
            x = block(x)
        return self.head(self.ln_f(x))                   # (B, T, V)

GPT.__init__ draws the token table, then the position table if there is one, then the blocks in order, then the head, all from the one rng, so a seed fixes the whole model. __call__ rejects windows longer than context, and ids outside [0,V)[0, V), before doing any work (numpy would read id −1-1 as the table’s last row), looks up the tokens, adds embedding(self.pos, np.arange(T)), the first TT rows of the position table (chapter 8’s embedding again; the addition’s _unbroadcast sums the gradient of the (T, d) rows over the batch), runs the blocks, and applies ln_f and the head. aux_loss sums the balance losses the MoE blocks kept from the last forward pass, and is a constant 0 for a dense model. Chapter 8’s train adds α\alpha times aux_loss() to the cross-entropy when it is given aux_weight=alpha, as the lab’s measurement below does. With the default of 0 it trains an MoE model on the cross-entropy alone, with nothing pushing the router toward balance, and each step’s balance-loss graph, which lies outside the loss that free_graph releases, is released by GPT.free_aux, which chapter 8’s train, evaluate and generate call through free_aux; the value stays readable. train_gpt builds dense models only. save writes each parameter as an array p0, p1, … in parameters() order next to the configuration as JSON, and load rebuilds a model of that configuration and overwrites its parameters, raising ValueError for a file without the configuration or with arrays that do not match it; test_save_and_load_round_trip checks that the reloaded model computes identical logits, and test_moe_save_and_load_round_trip the same for an MoE model. A file saved before GPTConfig had n_experts and top_k has a configuration without them, and loads as a dense model through the fields’ defaults (test_load_accepts_a_file_saved_before_the_moe_fields).

def load_corpus(path):
    """The text of a file, or of every .org/.md/.txt file under a directory, in sorted order.

    Hidden files and directories (.git, .trash, ...) are skipped; suffixes match in any case;
    invalid UTF-8 becomes U+FFFD and a leading byte-order mark is dropped.
    """
    path = pathlib.Path(path).expanduser()
    if not path.exists():
        raise FileNotFoundError(f"corpus not found: {path}")
    if path.is_file():
        files = [path]
    else:
        files = sorted(p for p in path.rglob("*")
                       if p.is_file() and p.suffix.lower() in SUFFIXES
                       and not any(part.startswith(".") for part in p.relative_to(path).parts))
    text = "\n\n".join(p.read_text(encoding="utf-8-sig", errors="replace") for p in files)
    if not text.strip():
        raise ValueError(f"no text found under {path}")
    return text

A missing path is an error at once. A file is read as is; a directory is walked with rglob and filtered by suffix, in any case (.MD counts), skipping any path with a component that starts with a dot, so .git, editor backups and trash directories stay out; sorting the paths makes the corpus, and so the tokenizer and the run, the same on every invocation. The utf-8-sig codec drops a leading byte-order mark, and errors="replace" turns invalid UTF-8 into U+FFFD. A corpus that is empty or only whitespace is an error, since BPE training and get_batch would fail on it later with a less useful message.

def check_out_dir(out):
    """Refuse an output directory inside this repository or inside any git work tree."""
    if out == REPO or REPO in out.parents:
        raise SystemExit(f"refusing to write {out}: it is inside the repository {REPO}")
    for d in [out, *out.parents]:
        if (d / ".git").exists():
            raise SystemExit(f"refusing to write {out}: it is inside the git work tree {d}")

REPO is computed from the tinygpt package the script imports (py/tinygpt/__init__.py, two directories up), not from the script’s own path, so a copy of train_gpt.py saved elsewhere still knows where the repository is. main passes the resolved path: resolve() makes it absolute and follows symbolic links, so neither ../ nor a link into the repository gets past the first test. The second walks up from OUT_DIR through every parent and refuses if any holds .git, a directory in a clone or a file in a git worktree.

def main(argv=None):
    args = parse_args(argv)
    out = pathlib.Path(args.out_dir).expanduser().resolve()
    check_out_dir(out)

    text = load_corpus(args.corpus)
    tok = BPE.train(text, args.vocab)
    ids = np.array(tok.encode(text))
    cut = int(0.9 * len(ids))
    train_ids, held_out = ids[:cut], ids[cut:cut + 20_000]  # score at most 20k held-out tokens
    if len(train_ids) <= args.context or len(held_out) < 2:
        raise SystemExit(f"{len(ids)} tokens is too few for a 90/10 split with context {args.context}")
    print(f"{len(text)} characters, {len(ids)} tokens, vocab {tok.vocab_size}")

    rng = np.random.default_rng(args.seed)
    cfg = GPTConfig(tok.vocab_size, args.context, args.d_model, args.heads, args.layers, args.pos)
    model = GPT(cfg, rng)
    opt = Adam(model.parameters(), args.lr)
    start, done = time.time(), 0
    while done < args.steps:  # chapter 8's train, in chunks of eval_every steps
        n = min(args.eval_every, args.steps - done)
        losses = train(model, opt, train_ids, n, args.context, args.batch, rng)
        done += n
        print(f"step {done:5d}  train {np.mean(losses):.3f}  held-out {evaluate(model, held_out, args.context):.3f}"
              f"  {time.time() - start:.0f}s", flush=True)

    out.mkdir(parents=True, exist_ok=True)  # only now: a run that fails leaves no directory behind
    tok.save(out / "tokenizer.json")
    save(model, out / "model.npz")
    prompt = ids[cut:cut + 8].tolist()
    sample = generate(model, prompt, args.context - len(prompt), args.context, rng)
    print("sample:", tok.decode(prompt + sample))
    return 0

main checks the output directory first. Then it trains the tokenizer on the whole corpus, encodes it, holds out the last 10% (scoring at most its first 20,000 tokens, to keep each evaluation to a few seconds on a large corpus), and refuses a corpus too short to split, all before it creates the output directory, so a failed run leaves nothing behind. Training is chapter 8’s train, called once per report with --eval-every steps (fewer for the last chunk); the optimizer and rng carry over between calls, so the run is the same as one call of steps steps. After each chunk it prints the step, the mean training loss of the chunk, the held-out loss and the elapsed time. The tokenizer is trained on the held-out text as well; it learns which byte sequences are frequent, not what follows what, so this does not let the model see its test predictions. At the end it saves both files and prints a sample continuing the first 8 held-out tokens to the full context.

Exercises

(a) Chapter 14 drafts for the lab model with a smaller one: V=512V = 512, C=64C = 64, d=32d = 32, H=4H = 4, L=1L = 1, learned positions. Count its parameters, the fraction in the embedding tables and the head, and its size relative to the lab model’s 169,344.

Answer

Token table Vd=512×32=16,384Vd = 512 \times 32 = 16{,}384. Position table Cd=64×32=2,048Cd = 64 \times 32 = 2{,}048. One block, 12d2+10d=12,288+320=12,60812d^2 + 10d = 12{,}288 + 320 = 12{,}608: layer norms 4d=1284d = 128, attention 4d2+d=4,1284d^2 + d = 4{,}128, feed-forward 8d2+5d=8,3528d^2 + 5d = 8{,}352. ln_f, 2d=642d = 64. Head, dV=16,384dV = 16{,}384. Total:

16,384+2,048+12,608+64+16,384=47,488, 16{,}384 + 2{,}048 + 12{,}608 + 64 + 16{,}384 = 47{,}488 ,

which sum(p.data.size for p in GPT(GPTConfig(512, 64, d_model=32, n_heads=4, n_layers=1), rng).parameters()) confirms. The tables and the head hold 16,384+2,048+16,384=34,81616{,}384 + 2{,}048 + 16{,}384 = 34{,}816, 73.3% of the model, against 41% for the lab model: halving dd halves the tables but quarters each block, and the draft has one block instead of two, so the vocabulary-sized matrices dominate. The draft is 28.0% of the target’s parameters. Per token it does less than that share of the target’s work, since the embedding lookup is a copy and only the head and the block multiply (chapter 3): 12,608+16,384=28,99212{,}608 + 16{,}384 = 28{,}992 weights in products against the target’s 99,584+32,768=132,35299{,}584 + 32{,}768 = 132{,}352, 21.9%.

(b) Some implementations pair feature ii with feature i+dh/2i + d_h/2 instead of with its neighbour. Prove that this half-split pairing also gives scores that depend only on n−mn - m, and show numerically that a query rotated with one pairing and a key with the other does not.

Answer

Let P\mathbf{P} be the (dh,dh)(d_h, d_h) permutation matrix that reorders the features 0,dh/2,1,dh/2+1,…0, d_h/2, 1, d_h/2 + 1, \ldots into positions 0,1,2,3,…0, 1, 2, 3, \ldots, so that the half-split pairs of x\mathbf{x} are the adjacent pairs of Px\mathbf{P}\mathbf{x}. The half-split rotation is then Rm′=P⊤RmP\mathbf{R}'_m = \mathbf{P}^\top \mathbf{R}_m \mathbf{P}: permute, rotate adjacent pairs, permute back. A permutation matrix has PP⊤=I\mathbf{P}\mathbf{P}^\top = \mathbf{I}, so

(Rm′q)⋅(Rn′k)=q⊤P⊤Rm⊤PP⊤RnPk=(Pq)⊤Rm⊤Rn(Pk)=(Pq)⋅(Rn−mPk), (\mathbf{R}'_m\mathbf{q}) \cdot (\mathbf{R}'_n\mathbf{k}) = \mathbf{q}^\top \mathbf{P}^\top \mathbf{R}_m^\top \mathbf{P}\mathbf{P}^\top \mathbf{R}_n \mathbf{P} \mathbf{k} = (\mathbf{P}\mathbf{q})^\top \mathbf{R}_m^\top \mathbf{R}_n (\mathbf{P}\mathbf{k}) = (\mathbf{P}\mathbf{q}) \cdot (\mathbf{R}_{n-m}\mathbf{P}\mathbf{k}) ,

using Rm⊤Rn=Rn−m\mathbf{R}_m^\top\mathbf{R}_n = \mathbf{R}_{n-m} from the text: a function of q\mathbf{q}, k\mathbf{k} and n−mn - m. With the adjacent pairing on the query and the half-split one on the key, the score is q⊤Rm⊤P⊤RnPk\mathbf{q}^\top \mathbf{R}_m^\top \mathbf{P}^\top \mathbf{R}_n \mathbf{P} \mathbf{k}: Rm\mathbf{R}_m and P⊤RnP\mathbf{P}^\top\mathbf{R}_n\mathbf{P} rotate different pairs of features, so they do not combine into one rotation by n−mn - m.

import numpy as np

from tinygpt.transformer import rope

d = 16
perm = np.stack([np.arange(d // 2), np.arange(d // 2) + d // 2], axis=1).ravel()  # 0, 8, 1, 9, ...


def rope_half(x, positions):
    """Pair feature i with feature i + d/2: the adjacent-pair rope on permuted features."""
    y = np.empty_like(x)
    y[..., perm] = rope(x[..., perm], positions)
    return y


rng = np.random.default_rng(0)
q, k = rng.normal(size=(1, d)), rng.normal(size=(1, d))
for m, n in [(3, 5), (10, 12), (40, 42)]:
    half = (rope_half(q, [m]) @ rope_half(k, [n]).T).item()
    mixed = (rope(q, [m]) @ rope_half(k, [n]).T).item()
    print(f"m={m:2d} n={n:2d}  half-split {half:+.6f}  adjacent query, half-split key {mixed:+.6f}")
m= 3 n= 5  half-split +4.014120  adjacent query, half-split key +3.283555
m=10 n=12  half-split +4.014120  adjacent query, half-split key +0.457110
m=40 n=42  half-split +4.014120  adjacent query, half-split key +3.273102

Run from py/ with PYTHONPATH=.. At an offset of 2 the half-split score is the same at every absolute position; the mixed score changes with the absolute position, which is the property RoPE exists to remove. A model’s weights are trained under one pairing, so a loader that applies the other feeds every layer queries and keys the weights were not trained on. llama.cpp names the adjacent pairing LLAMA_ROPE_TYPE_NORM and the half-split one LLAMA_ROPE_TYPE_NEOX, and llama_model_rope_type picks one per model architecture (as of commit da89bb3).

(c) Derive layer norm’s backward rule by hand: given g=∂L/∂y\mathbf{g} = \partial L / \partial \mathbf{y} for one position, shape (d,), find ∂L/∂x\partial L / \partial \mathbf{x}, ∂L/∂γ\partial L / \partial \gamma and ∂L/∂β\partial L / \partial \beta. Implement it as a fused Tensor op and check it with gradcheck and against the composed graph.

Answer

From yi=γix^i+βiy_i = \gamma_i\hat{x}_i + \beta_i: ∂L/∂βi=gi\partial L/\partial\beta_i = g_i and ∂L/∂γi=gix^i\partial L/\partial\gamma_i = g_i\hat{x}_i, each summed over positions for the shared parameters. Let g^i=giγi\hat{g}_i = g_i\gamma_i, the gradient at x^\hat{\mathbf{x}}, and s=σ2+ϵs = \sqrt{\sigma^2 + \epsilon}. Then x^i=(xi−μ)/s\hat{x}_i = (x_i - \mu)/s depends on xjx_j directly and through μ\mu and ss:

∂μ∂xj=1d,∂σ2∂xj=2d∑k(xk−μ)(δkj−1d)=2d(xj−μ),∂s∂xj=12s⋅2d(xj−μ)=x^jd, \frac{\partial \mu}{\partial x_j} = \frac{1}{d} , \qquad \frac{\partial \sigma^2}{\partial x_j} = \frac{2}{d}\sum_k (x_k - \mu)\Big(\delta_{kj} - \frac{1}{d}\Big) = \frac{2}{d}(x_j - \mu) , \qquad \frac{\partial s}{\partial x_j} = \frac{1}{2s}\cdot\frac{2}{d}(x_j - \mu) = \frac{\hat{x}_j}{d} ,

using ∑k(xk−μ)=0\sum_k (x_k - \mu) = 0. So

∂x^i∂xj=δij−1/ds−xi−μs2⋅x^jd=1s(δij−1d−x^ix^jd), \frac{\partial \hat{x}_i}{\partial x_j} = \frac{\delta_{ij} - 1/d}{s} - \frac{x_i - \mu}{s^2}\cdot\frac{\hat{x}_j}{d} = \frac{1}{s}\Big(\delta_{ij} - \frac{1}{d} - \frac{\hat{x}_i\hat{x}_j}{d}\Big) ,

and summing against g^i\hat{g}_i,

∂L∂xj=1s(g^j−1d∑ig^i−x^j⋅1d∑ig^ix^i). \frac{\partial L}{\partial x_j} = \frac{1}{s}\Big(\hat{g}_j - \frac{1}{d}\sum_i \hat{g}_i - \hat{x}_j\cdot\frac{1}{d}\sum_i \hat{g}_i\hat{x}_i\Big) .

The gradient at x^\hat{\mathbf{x}} loses its mean and its component along x^\hat{\mathbf{x}}, the two directions normalisation removes, and is divided by ss.

import numpy as np

from tinygpt.autograd import Tensor, gradcheck
from tinygpt.transformer import layer_norm


def layer_norm_fused(x, gamma, beta, eps=1e-5):
    """layer_norm as one op, with the hand-derived backward rule."""
    mu = x.data.mean(axis=-1, keepdims=True)
    inv = 1.0 / np.sqrt(x.data.var(axis=-1, keepdims=True) + eps)   # 1 / sigma, (..., 1)
    xhat = (x.data - mu) * inv                                         # (..., d)
    out = Tensor(xhat * gamma.data + beta.data, (x, gamma, beta), "layer_norm")

    def backward():
        g = out.grad                                                   # (..., d)
        lead = tuple(range(g.ndim - 1))
        gamma.grad += (g * xhat).sum(axis=lead)
        beta.grad += g.sum(axis=lead)
        gh = g * gamma.data                                            # dL/dxhat
        x.grad += inv * (gh - gh.mean(-1, keepdims=True) - xhat * (gh * xhat).mean(-1, keepdims=True))

    out._backward = backward
    return out


rng = np.random.default_rng(0)
x, g, b, w = rng.normal(size=(2, 3, 5)), rng.normal(size=5), rng.normal(size=5), rng.normal(size=(2, 3, 5))
gradcheck(lambda x, g, b: (layer_norm_fused(x, g, b) * w).sum(), [x, g, b])
print("fused layer norm passes gradcheck")
ts = [Tensor(a) for a in (x, g, b)]
(layer_norm(*ts) * w).sum().backward()
fs = [Tensor(a) for a in (x, g, b)]
(layer_norm_fused(*fs) * w).sum().backward()
print("largest difference from the composed graph:", max(np.abs(a.grad - c.grad).max() for a, c in zip(ts, fs)))
fused layer norm passes gradcheck
largest difference from the composed graph: 4.440892098500626e-16

The two agree to rounding. The fused op records one node where the composed version records twelve (each mean is a sum and a scaling, the subtraction a negation and an addition, then the square, the addition of ϵ\epsilon, the power, two products and the addition of β\beta), and keeps one (..., d) array, x^\hat{\mathbf{x}}, for its backward pass instead of several.

(d) Remove both residual connections from the block, keeping everything else, and train on the tiny corpus for 300 steps, with two blocks and with six. Compare with the full block.

Answer
import pathlib

import numpy as np

from tinygpt.mlp import Adam
from tinygpt.nn import evaluate, train
from tinygpt.transformer import GPT, Block, GPTConfig, gelu

tokens = pathlib.Path("data/tiny-corpus.txt").read_text().split()
vocab = sorted(set(tokens))
ids = np.array([vocab.index(t) for t in tokens])
cut = int(0.9 * len(ids))
train_ids, test_ids = ids[:cut], ids[cut:]


class NoResidualBlock(Block):
    def __call__(self, x):
        x = self.attn(self.ln1(x))
        return self.down(gelu(self.up(self.ln2(x))))


for layers in [2, 6]:
    for name in ["residual", "no residual"]:
        rng = np.random.default_rng(0)
        model = GPT(GPTConfig(len(vocab), 16, d_model=32, n_heads=4, n_layers=layers), rng)
        if name == "no residual":
            for b in model.blocks:
                b.__class__ = NoResidualBlock  # same weights, no residual lines
        losses = train(model, Adam(model.parameters(), lr=3e-3), train_ids, 300, 16, 16, rng)
        print(f"{layers} layers, {name:11s}: train loss, steps 41-60 {np.mean(losses[40:60]):.4f}  "
              f"held-out {evaluate(model, test_ids, 16):.4f}", flush=True)
2 layers, residual   : train loss, steps 41-60 1.4439  held-out 1.0179
2 layers, no residual: train loss, steps 41-60 1.9395  held-out 1.2310
6 layers, residual   : train loss, steps 41-60 1.4541  held-out 1.0291
6 layers, no residual: train loss, steps 41-60 2.6039  held-out 2.6165

Changing each block’s class keeps the weights the full model drew, so each pair of runs starts from identical parameters and sees identical batches. The first column, the mean training loss over steps 41 to 60, shows the split is there early: over steps 41 to 60 the six-block model without residuals already averages 2.60, near where it ends, while the other three average between 1.44 and 1.94 and are still falling. With two blocks the model without residuals still learns, but ends 0.21 nats worse. With six it does not learn: 2.6165 is the add-one unigram’s 2.6091, so the model predicts token frequencies whatever the context. The mechanism section measured why at initialisation: without the identity path, six rounds of attention, each replacing a position by an average over its history, wash the current token out, and changing it moves the final state by 6.0×10−66.0 \times 10^{-6} of its length, against 0.215 with residuals. The gradient that would teach the model to use the current token passes back through the same Jacobian. With residuals, six blocks do slightly worse than two in 300 steps (1.0291 against 1.0179): the grammar needs no depth.

(e) Build a RoPE model with context=32, train it on windows of 16, and evaluate it on windows of 8, 16 and 32. Why can a learned-position model with a 16-row table not even run on the longer windows?

Answer
import pathlib

import numpy as np

from tinygpt.mlp import Adam
from tinygpt.nn import evaluate, train
from tinygpt.transformer import GPT, GPTConfig

tokens = pathlib.Path("data/tiny-corpus.txt").read_text().split()
vocab = sorted(set(tokens))
ids = np.array([vocab.index(t) for t in tokens])
cut = int(0.9 * len(ids))
train_ids, test_ids = ids[:cut], ids[cut:]

rng = np.random.default_rng(0)
model = GPT(GPTConfig(len(vocab), 32, d_model=32, n_heads=4, n_layers=2, pos="rope"), rng)
train(model, Adam(model.parameters(), lr=3e-3), train_ids, 300, 16, 16, rng)
for T in [8, 16, 32]:
    print(f"RoPE, trained on windows of 16, held-out on windows of {T:2d}: {evaluate(model, test_ids, T):.4f}")
rng = np.random.default_rng(0)
model = GPT(GPTConfig(len(vocab), 16, d_model=32, n_heads=4, n_layers=2), rng)
train(model, Adam(model.parameters(), lr=3e-3), train_ids, 300, 16, 16, rng)
try:
    evaluate(model, test_ids, 32)
except ValueError as e:
    print("learned:", e)
RoPE, trained on windows of 16, held-out on windows of  8: 1.0637
RoPE, trained on windows of 16, held-out on windows of 16: 1.0220
RoPE, trained on windows of 16, held-out on windows of 32: 1.0212
learned: sequence length 32 exceeds context 16

A RoPE model has no parameter whose shape depends on the context, so context=32 draws exactly the weights context=16 would, and the windows-of-16 score equals the lab test’s RoPE result. On windows of 32 it scores slightly better, 1.0212, without ever having seen an offset above 15. That is the evaluation, not generalisation: every window starts with a position that has no history, and windows of 32 have half as many of those. The tiny grammar never needs an offset above 2 (the next token depends on the last three), so the offsets the model never trained on carry nothing it needs, and relative scores let it apply what it learned at small offsets at every position. Nothing in training constrains the scores at offsets it never saw, so on text whose dependencies reach past the training length there is no such guarantee. Windows of 8 are worse, 1.0637: the first two positions of every window see less history than the grammar uses, and windows of 8 have twice as many of those as windows of 16.

The learned model’s position table has 16 rows. Position 16 has no row, and GPT refuses before looking it up; without the check, embedding(self.pos, np.arange(32)) would raise an index error. There is no vector for the model to use at a position it never trained, not even a bad one.

(f) Estimate the forward-pass FLOPs per token of the lab configuration at T=64T = 64, as twice the non-embedding parameter count plus the attention term, using chapter 3’s count of 2 FLOPs per multiply-add.

Answer

Chapter 3’s rule: one token through a weight matrix costs two FLOPs per weight. The non-embedding parameters are 169,344−32,768−4,096=132,480169{,}344 - 32{,}768 - 4{,}096 = 132{,}480 (the two blocks, ln_f and the head; the tables are looked up, not multiplied), so the first term is 2×132,480=264,9602 \times 132{,}480 = 264{,}960 FLOPs. The layer norms and biases in that count do one or two operations per parameter rather than a multiply-add per weight per token, so it overstates slightly; counting only the matrices, 2×(2×12×642+64×512)=262,1442 \times (2 \times 12 \times 64^2 + 64 \times 512) = 262{,}144.

The attention term is the part that is not a weight. Per layer, a query against TT keys costs TdhT d_h multiply-adds per head for the scores and TdhT d_h for the weighted sum of values, 2Td2Td multiply-adds over all heads, 4Td4Td FLOPs. For two layers at T=64T = 64, d=64d = 64:

4×64×64×2=32,768 FLOPs. 4 \times 64 \times 64 \times 2 = 32{,}768 \text{ FLOPs} .

The total is 264,960+32,768=297,728≈3.0×105264{,}960 + 32{,}768 = 297{,}728 \approx 3.0 \times 10^5 FLOPs per token, 11% of it attention. The reference computes the full T×TT \times T score matrix and masks half of it, so this is what it does; a causal implementation that skips the masked half does 4(t+1)d4(t + 1)d FLOPs per layer at position tt, averaging 2(T+1)d2(T + 1)d over a window, 16,640 for both layers. The attention term grows with TT and the parameter term does not: for a model of this width at T=1,024T = 1{,}024 attention would be 4×1,024×64×2=524,2884 \times 1{,}024 \times 64 \times 2 = 524{,}288 FLOPs per token, twice the rest of the model.

(g) Train the lab’s MoE without the balance loss: in /tmp/moe_lab.py, from the lab section, replace the list runs by [("MoE, no balance loss", dict(d_model=32, n_experts=4, top_k=2), 0.0)]. Compare the expert shares and the held-out loss with the run that has it, and explain why the router can still learn to spread tokens.

Answer
MoE, no balance loss  total 110,464  active 77,056  held-out 3.7453    99 ms/step
    block 0: share of assignments per expert 0.31 0.18 0.32 0.20
    block 1: share of assignments per expert 0.31 0.18 0.44 0.07

Run on straylight in 51 seconds. Without the balance loss the load is uneven: in the second block (the printout numbers blocks and experts from 0, so this is its block 1) the third expert receives 44% of the assignments and the fourth 7%, against 23% and 29% with it. Nothing has collapsed. With k=2k = 2 every position uses two experts, and the router’s gradient, derived in the text, raises the logit of a chosen expert whose output helps more than the other chosen one’s: an expert that is chosen as second for some tokens still gets gradient and can win them. What the router never learns about is an expert it never chooses, and over 500 steps at this scale none fell out entirely. The held-out loss is 3.7453 against 3.7390, a difference smaller than the spread between seeds in the text’s sweep, where the runs without the balance loss were the better pair. At this scale the balance loss buys even use of the stored weights, not a better model; in the Switch Transformer, which gives each expert a fixed capacity of tokens per batch and passes the overflow through the residual line unprocessed, it also keeps tokens from being dropped.

Lab

Implement layer_norm, LayerNorm, gelu, rope, MultiHeadAttention, MoE, Block and GPT in py/labs/ch11/starter.py, following its docstring for the attribute names and the order of parameters(); GPTConfig, save, load and GPT.free_aux are provided. Draw the parameters in the order the reference does (token table, position table, then each block’s projections in the order query, key, value, output, up, down, or in an MoE block query, key, value, output, the router, the stacked up, the stacked down, then the head) if you want its numbers exactly. Run

make lab CH=11 IMPL=mine

until it passes. Read py/labs/ch11/test_lab.py first. It checks each piece alone (layer norm’s statistics, constant rows and gradient, GELU’s values, RoPE’s angles, norms and relative scores, the head split, causality), checks that multi-head attention, the block and the model compute exactly their definitions from the named parameters, gradchecks the whole model with both position schemes, pins the parameter count and the save/load round trip, checks the mixture of experts against a per-position loop over the chosen experts for k=1k = 1, 2 and 3 and gradchecks it with its balance loss, checks its initial bounds from both sides, its gates at router logits of ±8,000 in different rows (one shift for the whole batch underflows to 0/0), and the uneven load with a balance loss below 1 from the text, checks that its router learns from the loss only when k>1k > 1, pins its parameter count and save/load, and trains: two 300-step runs on the tiny corpus, which must reach a held-out loss below 1.1, a 300-step MoE run of width 16 that must do the same, and the acceptance test, test_gpt_beats_unigram_on_persuasion, a 100-step run on the first 30,000 characters of Persuasion that must beat the add-one unigram by 0.3 nats.

Then train the lab model on all of Persuasion. From py/:

OPENBLAS_NUM_THREADS=1 PYTHONPATH=. uv run python -m tinygpt.train_gpt data/persuasion.txt /tmp/tinygpt-persuasion

It took about three and a half minutes on talos and printed:

464441 characters, 213887 tokens, vocab 512
step   250  train 4.506  held-out 3.890  23s
step   500  train 3.639  held-out 3.616  48s
step   750  train 3.352  held-out 3.392  73s
step  1000  train 3.137  held-out 3.232  97s
step  1250  train 2.986  held-out 3.155  121s
step  1500  train 2.892  held-out 3.088  145s
step  1750  train 2.804  held-out 3.043  170s
step  2000  train 2.753  held-out 3.012  195s
sample: rick, or some opintter, I saw it will say, escare with
huper house. By the you were and gratifeal at Uppercross in my bide;

Keep /tmp/tinygpt-persuasion: chapter 12’s sampler and chapter 14’s quantizer load this model and tokenizer, and every later figure computed from it, in chapters 12 to 15 and chapter 21’s decoding lab, is this file’s, the one trained on talos. Retrained on another CPU, the weights can differ in their last bits (chapter 16 explains why: the same sums, grouped differently). On the five machines of the reader’s fleet this log printed identically, and a model retrained on straylight reproduced the later chapters’ printed figures exactly; a model trained elsewhere can make them differ slightly. train_gpt imports the reference GPT; to train yours, copy py/tinygpt/train_gpt.py outside the repository and change its import to from labs.ch11.starter import GPT, GPTConfig, save.

  • The first line is the corpus and the tokenizer. 464,441 characters in 213,887 tokens, 2.17 characters per token. A 512-token vocabulary is small: 256 of its entries are the single bytes, and the 256 merges cover only the most frequent words and pieces.
  • Held-out loss falls at every report, fast at first (0.27 nats between steps 250 and 500) and slowly at the end (0.03 between 1,750 and 2,000). It is still falling: 2,000 steps show the model 2,000 × 16 × 64 = 2,048,000 tokens, about ten passes over the training text, and the curve has not levelled off. From step 750 on the training loss is below the held-out loss, and the gap widens to 0.26 nats by step 2,000: the model fits the training text better than it generalises.
  • The sample is locally English. Word pieces combine into real words and word-like non-words (“opintter”, “gratifeal”), commas and capitals appear, and a place from the book, Uppercross, appears. Nothing is coherent over more than a few words. A model with 169,344 parameters, trained for a few minutes, has learned spelling and some syntax; the sample is a single draw at temperature 1, which chapter 12 shows how to control.

Optionally, train on your own notes:

OPENBLAS_NUM_THREADS=1 PYTHONPATH=. uv run python -m tinygpt.train_gpt ~/org /tmp/tinygpt-org --steps 4000

The first line tells you the corpus size. Compare it with Persuasion’s: on a smaller corpus, watch for the held-out loss levelling off while the training loss keeps falling, the overfitting of chapter 9, which says more steps are only memorising. Look at the sample for your own recurring vocabulary: headings, tags, TODO keywords, names. Those are what the tokenizer merges into single tokens and what the model can reproduce, and they are why /tmp/tinygpt-org stays out of the repository and off any machine you would not copy the notes themselves to. Try --pos rope on the same corpus and compare the held-out loss at each report.

Then train a mixture of experts against the dense models that bracket its active size. Save as /tmp/moe_lab.py:

import pathlib
import time

import numpy as np

from tinygpt.bpe import BPE
from tinygpt.mlp import Adam
from tinygpt.nn import evaluate, train
from tinygpt.transformer import GPT, GPTConfig

tok = BPE.load("/tmp/tinygpt-persuasion/tokenizer.json")
ids = np.array(tok.encode(pathlib.Path("data/persuasion.txt").read_text()))
cut = int(0.9 * len(ids))
train_ids, held_out = ids[:cut], ids[cut:cut + 20_000]
STEPS = 500


class CountingRouter:
    """Wraps a router: returns its logits unchanged and counts which top-k experts each position gets."""

    def __init__(self, router, n_experts, k):
        self.router, self.k, self.counts = router, k, np.zeros(n_experts)

    def __call__(self, x):
        z = self.router(x)                                                  # (N, E)
        np.add.at(self.counts, np.argsort(-z.data, axis=-1, kind="stable")[:, :self.k].ravel(), 1)
        return z


runs = [("dense, d=36", dict(d_model=36), 0.0),
        ("dense, d=40", dict(d_model=40), 0.0),
        ("MoE, E=4, top-2", dict(d_model=32, n_experts=4, top_k=2), 0.01)]
for name, kw, alpha in runs:
    rng = np.random.default_rng(0)
    cfg = GPTConfig(tok.vocab_size, 64, n_heads=4, n_layers=2, **kw)
    model = GPT(cfg, rng)
    opt = Adam(model.parameters(), 3e-3)
    start = time.time()
    train(model, opt, train_ids, STEPS, 64, 16, rng, aux_weight=alpha)    # alpha is 0 for the dense runs
    ms = (time.time() - start) / STEPS * 1000
    total = sum(p.data.size for p in model.parameters())
    idle = sum((cfg.n_experts - cfg.top_k) * sum(p.data[0].size for p in b.moe.parameters()[1:])
               for b in model.blocks if b.moe is not None)
    for b in model.blocks:
        if b.moe is not None:
            b.moe.router = CountingRouter(b.moe.router, cfg.n_experts, cfg.top_k)
    loss = evaluate(model, held_out, 64)
    print(f"{name:20s}  total {total:7,d}  active {total - idle:6,d}  held-out {loss:.4f}  {ms:4.0f} ms/step")
    for i, b in enumerate(model.blocks):
        if b.moe is not None:
            shares = b.moe.router.counts / b.moe.router.counts.sum()
            print(f"    block {i}: share of assignments per expert " + " ".join(f"{s:.2f}" for s in shares))

and run it from py/, after the training run above (it reuses that run’s tokenizer):

OPENBLAS_NUM_THREADS=1 PYTHONPATH=. uv run python /tmp/moe_lab.py

It printed, in 103 seconds on straylight:

dense, d=36           total  71,064  active 71,064  held-out 3.8037    43 ms/step
dense, d=40           total  82,800  active 82,800  held-out 3.7161    49 ms/step
MoE, E=4, top-2       total 110,464  active 77,056  held-out 3.7390   109 ms/step
    block 0: share of assignments per expert 0.24 0.25 0.22 0.29
    block 1: share of assignments per expert 0.25 0.23 0.23 0.29
  • The training loop is chapter 8’s train with aux_weight, which adds α=0.01\alpha = 0.01 times the balance loss for the MoE; for the dense models α\alpha is 0 and train computes the cross-entropy alone. Every run starts from default_rng(0) and draws its batches from the same generator after its own initialisation, so the batches differ between models of different sizes; the two-seed sweep in the Mechanism section is the check that the order is not an accident of one draw.
  • The counts come from a wrapped router. After training, CountingRouter replaces each block’s router: MoE calls it like the Linear it replaces, it returns the same logits, and on the way it records each position’s top-kk with the same stable sort. evaluate then runs the held-out tokens through as usual. Each block’s shares sum to 1 over its 4 experts; with the balance loss they lie between 0.22 and 0.29, against a uniform 0.25.
  • The MoE is slower per step here and would be faster in an engine. It computes all four experts, twice the feed-forward arithmetic of its two active ones (chapter 12’s forward_cached computes only those), and its (E, N, 4d) intermediate arrays are four times those of a dense block of the same width.

Further reading

  • Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser and Illia Polosukhin, “Attention Is All You Need”, NeurIPS (2017). Multi-head attention (section 3.2.2), the position-wise feed-forward sublayer with dff=4dd_{ff} = 4d (3.3), the post-norm residual block (3.1), and sinusoidal position encodings, with learned ones reported to perform nearly identically (3.5 and Table 3, row E).
  • Kaiming He, Xiangyu Zhang, Shaoqing Ren and Jian Sun, “Deep Residual Learning for Image Recognition”, CVPR (2016). Residual connections, introduced to train convolutional networks of over a hundred layers, with the observation that deeper plain networks train to a higher training error than shallower ones.
  • Jimmy Lei Ba, Jamie Ryan Kiros and Geoffrey E. Hinton, “Layer Normalization” (2016). Normalisation over the features of one example instead of over the batch, with the learned gain and bias.
  • Ruibin Xiong, Yunchang Yang, Di He, Kai Zheng, Shuxin Zheng, Chen Xing, Huishuai Zhang, Yanyan Lan, Liwei Wang and Tie-Yan Liu, “On Layer Normalization in the Transformer Architecture”, ICML (2020). Why post-norm transformers need learning-rate warm-up and pre-norm ones train without it, from the size of the gradients near the output at initialisation.
  • Dan Hendrycks and Kevin Gimpel, “Gaussian Error Linear Units (GELUs)” (2016). The definition xΦ(x)x\Phi(x), its motivation, and the tanh approximation used here.
  • Jianlin Su, Yu Lu, Shengfeng Pan, Ahmed Murtadha, Bo Wen and Yunfeng Liu, “RoFormer: Enhanced Transformer with Rotary Position Embedding” (2021). Rotary position embeddings, the relative-position derivation, and the frequencies 10000−2i/d10000^{-2i/d}.
  • Alec Radford, Jeffrey Wu, Rewon Child, David Luan, Dario Amodei and Ilya Sutskever, “Language Models are Unsupervised Multitask Learners” (2019). GPT-2: a decoder-only transformer language model, with layer norm moved to the input of each sub-block and a final layer norm after the last block (section 2.3), the design GPT follows.
  • Noam Shazeer, Azalia Mirhoseini, Krzysztof Maziarz, Andy Davis, Quoc Le, Geoffrey Hinton and Jeff Dean, “Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer”, ICLR (2017). The top-kk gate Softmax(KeepTopK(⋅,k))\mathrm{Softmax}(\mathrm{KeepTopK}(\cdot, k)) with trainable noise, the observation that routing collapses onto a few experts and reinforces itself, and auxiliary losses for balanced importance and load.
  • William Fedus, Barret Zoph and Noam Shazeer, “Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient Sparsity”, Journal of Machine Learning Research 23 (2022). Routing each token to one expert with the router probability as its gate, expert capacity and dropped tokens, and the balance loss αN∑ifiPi\alpha N \sum_i f_i P_i with α=10−2\alpha = 10^{-2} (Section 2.2).
  • Albert Q. Jiang, Alexandre Sablayrolles, Antoine Roux, Arthur Mensch and others, “Mixtral of Experts” (2024). A decoder in which every feed-forward sublayer is 8 experts with the gate Softmax(TopK(xWg))\mathrm{Softmax}(\mathrm{TopK}(\mathbf{x}\mathbf{W}_g)) and K=2K = 2, the form built here.

results matching ""

    No results matching ""