11  A small transformer

This chapter puts the parts of the book together into one model: a language model with 4192 parameters that learns to generate names one letter at a time. It is a transformer, a network in which attention (Chapter 10) lets each position of a sequence draw on earlier positions, and an MLP then processes each position on its own. It has the shape of Andrej Karpathy’s microgpt (Karpathy 2026a), a single file of Python that defines the model and trains it with Adam, computing each gradient by reverse mode on a graph of linked nodes (Section 4.8). We have checked every architectural detail stated below against that source (Karpathy 2026b).

Two ingredients are new. Call each stage of the network that has its own parameters, such as the attention stage or the MLP, a block. RMS normalisation rescales a vector to a fixed size before a block uses it, and residual connections add each block’s output to its input instead of replacing it. Both change how gradients flow, and both have short exact descriptions in terms of Jacobians. The rest of the chapter writes down the complete model, counts its parameters, explains the value of the loss before training and the effect of the sampling temperature, and proves that storing the keys and values of earlier positions during generation computes exactly what causal attention computes.

11.1 RMS normalisation

The vectors inside a network change size as they pass through it. A linear map with large weights stretches them, and a sum of many terms grows with the number of terms. If the next layer is to receive inputs on the same scale whatever happened before, something has to divide each vector by a measure of its size. The question is which measure, and what to do with vectors whose size is close to zero.

A natural measure for a vector of \(n\) components is the root mean square of its components: the square root of the mean of their squares. For \(\mathbf{x} = (1, -1, 2, 0)\) the squares are \(1, 1, 4, 0\), their mean is \(1.5\), and the root mean square is \(\sqrt{1.5} \approx 1.2247\). Dividing by it gives \[ \frac{\mathbf{x}}{\sqrt{1.5}} \approx (0.8165, -0.8165, 1.6330, 0), \] a vector whose components have root mean square exactly 1. The vector \(10\mathbf{x} = (10, -10, 20, 0)\) has root mean square \(10\sqrt{1.5}\), and dividing gives the same result: the division removes the size of the vector and keeps its direction.

The obvious definition, \(\mathbf{x}\) divided by its root mean square, fails at \(\mathbf{0}\), where it divides by zero, and it cannot be repaired there by a choice of value. Along the line \(\mathbf{x} = (t, 0, 0, 0)\) the root mean square is \(|t|/2\), so the quotient is \((2, 0, 0, 0)\) for every \(t > 0\) and \((-2, 0, 0, 0)\) for every \(t < 0\): it jumps as \(t\) passes through \(0\), and so it is not continuous, let alone differentiable, at \(\mathbf{0}\). A gradient method needs a differentiable function, and the remedy is to add a small positive constant under the square root.

Definition 11.1 (RMS normalisation) Let \(n \ge 1\) and \(\varepsilon > 0\). For \(\mathbf{x}\in\mathbb{R}^n\) let \(\mu(\mathbf{x}) = \frac1n\sum_{i=1}^n x_i^2 = \|\mathbf{x}\|^2/n\), the mean of the squares of the components. The RMS normalisation of \(\mathbf{x}\) is \[ \operatorname{rms}(\mathbf{x}) = \frac{\mathbf{x}}{\sqrt{\mu(\mathbf{x}) + \varepsilon}} . \]

In words: divide every component of \(\mathbf{x}\) by the same positive number, the root mean square of the components with \(\varepsilon\) added under the square root. The denominator is at least \(\sqrt\varepsilon\), so \(\operatorname{rms}\) is defined on all of \(\mathbb{R}^n\), and \(\operatorname{rms}(\mathbf{0}) = \mathbf{0}\). The model of this chapter uses \(n = 16\) and \(\varepsilon = 10^{-5}\), and multiplies the result by nothing: there is no learned gain, a vector of weights that some models multiply the result by componentwise. Since \(\mu(\operatorname{rms}(\mathbf{x})) = \mu(\mathbf{x})/(\mu(\mathbf{x}) + \varepsilon)\), the root mean square of the output is slightly below 1, and far below 1 when \(\mu(\mathbf{x})\) is comparable with \(\varepsilon\).

Example 11.1 For \(\mathbf{x} = (1, -1, 2, 0)\) and \(\varepsilon = 10^{-5}\), the denominator is \(\sqrt{1.50001}\) instead of \(\sqrt{1.5}\), so each component of the result above changes by a factor \(\sqrt{1.5/1.50001} \approx 1 - 3.3\times10^{-6}\). For \(\mathbf{x} = (t, 0, 0, 0)\) the result is \((t/\sqrt{t^2/4 + \varepsilon}, 0, 0, 0)\), which passes continuously through \(\mathbf{0}\) at \(t = 0\) and is close to \((\pm2, 0, 0, 0)\) once \(|t|\) is large compared with \(\sqrt\varepsilon\).

The Jacobian

Reverse mode (Theorem 4.1) passes the gradient of the loss back through every function in the model, and for that it needs each function’s Jacobian. For RMS normalisation the Jacobian treats increments in two directions differently, and a small case shows how. Take \(n = 2\), a deliberately large \(\varepsilon = 1\) so that the effect is visible, and \(\mathbf{x} = (1, 0)\). Then \(\mu(\mathbf{x}) = 1/2\) and \(\operatorname{rms}(\mathbf{x}) = (1, 0)/\sqrt{3/2} \approx (0.8165, 0)\).

  • An increment of \(0.01\) in \(x_2\), perpendicular to \(\mathbf{x}\), changes the output by about \((0.0000, 0.008165)\): the increment passes through multiplied by \(0.8165 = (3/2)^{-1/2}\), because to first order it does not change \(\mu\).
  • An increment of \(0.01\) in \(x_1\), along \(\mathbf{x}\), changes the output by about \((0.005416, 0)\): a factor \(0.54\), smaller, because enlarging \(\mathbf{x}\) also enlarges the denominator.

With \(\varepsilon = 0\) the second factor would be exactly \(0\), since then scaling \(\mathbf{x}\) does not change the output at all. The theorem gives both factors in general.

Theorem 11.1 (Jacobian of RMS normalisation) Let \(n \ge 1\) and \(\varepsilon > 0\), let \(\operatorname{rms}\) be RMS normalisation on \(\mathbb{R}^n\) with this \(\varepsilon\), and write \(s(\mathbf{x}) = (\mu(\mathbf{x}) + \varepsilon)^{-1/2}\). Then \(\operatorname{rms}\) is differentiable on \(\mathbb{R}^n\), with \[ J_{\operatorname{rms}}(\mathbf{x}) = s\,I - \frac{s^3}{n}\,\mathbf{x}\mathbf{x}^\top = s\Bigl(I - \frac{\mathbf{x}\mathbf{x}^\top}{\|\mathbf{x}\|^2 + n\varepsilon}\Bigr), \qquad s = s(\mathbf{x}). \tag{11.1}\] The matrix is symmetric. For \(\mathbf{x} \ne \mathbf{0}\), every non-zero vector perpendicular to \(\mathbf{x}\) is an eigenvector with eigenvalue \(s\), and \(\mathbf{x}\) is an eigenvector with eigenvalue \(\varepsilon s^3\).

Entry \((i, j)\) of this matrix is the rate at which output component \(i\) changes per unit increment of input component \(j\). The term \(sI\) says that each input component, on its own, passes to the same output component scaled by \(s\); the term \(-(s^3/n)\mathbf{x}\mathbf{x}^\top\), whose entry \((i, j)\) is \(-s^3x_ix_j/n\), corrects every output component for the change in the common denominator. In the example above, \(s = (3/2)^{-1/2} \approx 0.8165\) and \(\varepsilon s^3 = (2/3)^{3/2} \approx 0.5443\).

Proof. Component \(i\) of \(\operatorname{rms}(\mathbf{x})\) is \(x_i\,s(\mathbf{x})\). The function \(\mu\) is a polynomial and \(\mu + \varepsilon \ge \varepsilon > 0\), so \(s\) has continuous partial derivatives \[ \frac{\partial s}{\partial x_j} = -\frac12(\mu + \varepsilon)^{-3/2}\,\frac{2x_j}{n} = -\frac{s^3x_j}{n} . \] By the product rule, \(\partial(x_is)/\partial x_j = \delta_{ij}s - s^3x_ix_j/n\), where \(\delta_{ij}\) is \(1\) if \(i = j\) and \(0\) otherwise. These partial derivatives are continuous, so by Theorem 1.6 and Theorem 1.5 \(\operatorname{rms}\) is differentiable with the Jacobian in Equation 11.1. The second form follows from \(s^2 = n/(\|\mathbf{x}\|^2 + n\varepsilon)\).

If \(\mathbf{y}\cdot\mathbf{x} = 0\) then \(J\mathbf{y} = s\mathbf{y} - (s^3/n)\mathbf{x}(\mathbf{x}\cdot\mathbf{y}) = s\mathbf{y}\). For \(\mathbf{x}\) itself, \[ J\mathbf{x} = s\mathbf{x} - \frac{s^3}{n}\|\mathbf{x}\|^2\mathbf{x} = s^3\Bigl(\frac{1}{s^2} - \mu\Bigr)\mathbf{x} = \varepsilon s^3\,\mathbf{x}, \] because \(1/s^2 = \mu + \varepsilon\).

In reverse mode every intermediate vector \(\mathbf{v}\) carries an adjoint \(\bar{\mathbf{v}}\) (Definition 4.1), the gradient of the loss \(L\) with respect to \(\mathbf{v}\), and reverse mode (Theorem 4.1) obtains the adjoint of a function’s input by multiplying the adjoint of its output by the transposed Jacobian. Write \(\mathbf{y} = \operatorname{rms}(\mathbf{x})\). Since \(J\) is symmetric, \(\bar{\mathbf{x}} = J^\top\bar{\mathbf{y}} = J\bar{\mathbf{y}}\), that is, \[ \bar{\mathbf{x}} = s\,\bar{\mathbf{y}} - \frac{s^3}{n}\,(\mathbf{x}\cdot\bar{\mathbf{y}})\,\mathbf{x} . \] The gradient keeps its component perpendicular to \(\mathbf{x}\), scaled by \(s\), and almost loses its component along \(\mathbf{x}\), which \(J\) scales by \(\varepsilon s^3\) instead. A change of \(\mathbf{x}\) along itself only changes its size, and normalisation removes size.

Scaling and the effect of \(\varepsilon\)

The point of normalising is that the output should not depend on the size of the input. With \(\varepsilon = 0\) that would hold exactly; the question is how much \(\varepsilon\) spoils it. Take again \(\mathbf{x} = (1, -1, 2, 0)\), with \(\mu(\mathbf{x}) = 1.5\), and \(\varepsilon = 10^{-5}\). For \(10\mathbf{x}\) the denominator is \(\sqrt{150 + 10^{-5}} = 10\sqrt{1.5 + 10^{-7}}\), so the output is \(\mathbf{x}/\sqrt{1.5 + 10^{-7}}\): the same as normalising \(\mathbf{x}\) with \(\varepsilon\) replaced by \(10^{-7}\). For \(0.001\mathbf{x}\) the output is \(\mathbf{x}/\sqrt{1.5 + 10}\), the same as normalising \(\mathbf{x}\) with \(\varepsilon = 10\), and it is only \(\sqrt{1.5/11.5} \approx 0.36\) times the output for \(\mathbf{x}\) itself. Write \(\operatorname{rms}_\varepsilon\) when the value of \(\varepsilon\) matters.

Theorem 11.2 (Scaling) Let \(\varepsilon > 0\), \(c > 0\) and \(\mathbf{x}\in\mathbb{R}^n\).

  1. \(\operatorname{rms}_\varepsilon(c\mathbf{x}) = \operatorname{rms}_{\varepsilon/c^2}(\mathbf{x})\).

  2. If \(\mathbf{x} \ne \mathbf{0}\), then \(\operatorname{rms}_\varepsilon(\mathbf{x}) = \lambda\,\mathbf{x}/\sqrt{\mu(\mathbf{x})}\) with \[ \lambda = \sqrt{\frac{\mu(\mathbf{x})}{\mu(\mathbf{x}) + \varepsilon}}, \qquad 1 - \frac{\varepsilon}{2\mu(\mathbf{x})} \le \lambda < 1 . \]

Proof.

  1. \(\mu(c\mathbf{x}) = c^2\mu(\mathbf{x})\), so \[ \operatorname{rms}_\varepsilon(c\mathbf{x}) = \frac{c\mathbf{x}}{\sqrt{c^2\mu(\mathbf{x}) + \varepsilon}} = \frac{c\mathbf{x}}{c\sqrt{\mu(\mathbf{x}) + \varepsilon/c^2}} = \operatorname{rms}_{\varepsilon/c^2}(\mathbf{x}) . \]

  2. The formula for \(\lambda\) is a rearrangement of the definition, and \(\lambda < 1\) because \(\varepsilon > 0\). Put \(r = \varepsilon/\mu(\mathbf{x}) > 0\), so that \(\lambda^2 = 1/(1 + r)\). If \(r > 2\) the lower bound \(1 - r/2\) is negative and there is nothing to prove. If \(0 < r \le 2\), then \(1 - r/2 \ge 0\) and \[ \Bigl(1 - \frac r2\Bigr)^2(1 + r) = 1 - \frac{r^2(3 - r)}{4} \le 1, \] so \((1 - r/2)^2 \le \lambda^2\), and taking square roots gives \(1 - r/2 \le \lambda\).

So normalisation is invariant under positive scaling exactly when \(\varepsilon = 0\). With \(\varepsilon > 0\), scaling \(\mathbf{x}\) by \(c\) has the same effect as replacing \(\varepsilon\) by \(\varepsilon/c^2\): enlarging the input weakens \(\varepsilon\), and shrinking it strengthens \(\varepsilon\). By (b), \(\varepsilon\) shrinks the output by a relative amount of at most \(\varepsilon/(2\mu(\mathbf{x}))\). For inputs whose mean square is large compared with \(\varepsilon\) this is negligible. For inputs of mean square comparable with \(\varepsilon\) it is not, and as \(\mathbf{x} \to \mathbf{0}\) the output tends to \(\mathbf{0}\) instead of jumping between vectors of root mean square 1. That continuity at \(\mathbf{0}\) is what \(\varepsilon\) buys.

In the model of Section 11.3, the first vector normalised is the sum of two vectors of 16 parameters each (a row of the token embedding and a row of the position embedding). Before training, every parameter is drawn independently with mean 0 and variance \(0.08^2\), so each component of the sum has variance \(2\times0.08^2 = 0.0128\). Then \(\mu \approx 0.0128\) and \(\varepsilon/(2\mu) \approx 3.9\times10^{-4}\): at the start of training, \(\varepsilon\) shrinks this vector by less than \(0.04\%\).

Layer normalisation

RMS normalisation is a simplification of the older layer normalisation (Ba et al. 2016), which GPT-2, the language model whose design this chapter’s model follows, uses (Radford et al. 2019). The difference shows when the same constant is added to every component. Ignoring \(\varepsilon\), RMS normalisation sends \((1, 2, 3)\) to about \((0.463, 0.926, 1.389)\) and \((11, 12, 13)\) to about \((0.915, 0.998, 1.081)\): the shift by 10 changes the result. Layer normalisation first subtracts the mean of the components, which turns both vectors into \((-1, 0, 1)\), and then divides by the root mean square of what remains, \(\sqrt{2/3}\), giving \((-1.225, 0, 1.225)\) for both.

Definition 11.2 (Layer normalisation) Let \(n \ge 1\) and \(\varepsilon > 0\). For \(\mathbf{x}\in\mathbb{R}^n\) let \(m(\mathbf{x}) = \frac1n\sum_i x_i\) be the mean of the components and \(v(\mathbf{x}) = \frac1n\sum_i (x_i - m(\mathbf{x}))^2\) their variance. The layer normalisation of \(\mathbf{x}\), with gain \(\mathbf{g}\) and bias \(\mathbf{b}\) in \(\mathbb{R}^n\), is the vector with components \[ \operatorname{LN}(\mathbf{x})_i = g_i\,\frac{x_i - m(\mathbf{x})}{\sqrt{v(\mathbf{x}) + \varepsilon}} + b_i . \]

In words: subtract the mean, divide by the standard deviation (with \(\varepsilon\) added to the variance), then scale component \(i\) by \(g_i\) and shift it by \(b_i\). In a network \(\mathbf{g}\) and \(\mathbf{b}\) are parameters, learned with the rest. With \(\mathbf{g} = \mathbf{1}\) and \(\mathbf{b} = \mathbf{0}\) it is RMS normalisation applied to the centred vector \(\mathbf{x} - m(\mathbf{x})\mathbf{1}\), because the variance of \(\mathbf{x}\) is the mean square of the centred vector (Exercise 11.3). So layer normalisation is unchanged when the same constant is added to every component of \(\mathbf{x}\), and RMS normalisation is not; on vectors with mean zero the two agree. Zhang and Sennrich (2019) propose RMS normalisation on the hypothesis that the rescaling, not the centring, is what helps training, and they report comparable accuracy at lower cost. microgpt drops the gain as well, so its normalisations have no parameters.

11.2 Residual connections

A deep network is a composition of many functions, one per block, and by the chain rule (Theorem 2.1) the derivative of the loss with respect to the input of the first block is a product of one Jacobian per block. A product of many factors can be very small. In one dimension, ten blocks \(x \mapsto 0.1x\) in a row have derivative \(0.1^{10} = 10^{-10}\): an increment at the bottom of the stack has almost no effect at the top, and gradient descent barely changes the parameters of the early blocks. Now let each block add its output to its input instead, \(x \mapsto x + 0.1x\). Ten of these have derivative \(1.1^{10} \approx 2.59\), of the same order as \(1\), because each factor is \(1\) plus something small instead of something small.

Definition 11.3 (Residual connection) Let \(U \subseteq \mathbb{R}^n\) and \(F\colon U\to\mathbb{R}^n\). The residual block built from \(F\) is the map \(R\colon U\to\mathbb{R}^n\), \(R(\mathbf{x}) = \mathbf{x} + F(\mathbf{x})\). The added term \(\mathbf{x}\) is the residual connection, and \(F\) is the block.

The block \(F\) computes a correction to its input instead of a replacement for it. He et al. (2016) introduced residual connections for image recognition, where they made networks with over a hundred layers trainable. Their effect on derivatives takes one line.

Theorem 11.3 (Jacobian of a residual block) Let \(U\subseteq\mathbb{R}^n\) be open, let \(F\colon U\to\mathbb{R}^n\) be differentiable at \(\mathbf{a}\in U\), and let \(R(\mathbf{x}) = \mathbf{x} + F(\mathbf{x})\). Then \(R\) is differentiable at \(\mathbf{a}\) and \[ J_R(\mathbf{a}) = I + J_F(\mathbf{a}) . \] If also \(\ell\colon\mathbb{R}^n\to\mathbb{R}\) is differentiable at \(R(\mathbf{a})\) and \(L(\mathbf{x}) = \ell(R(\mathbf{x}))\), then with \(\bar{\mathbf{y}} = \nabla\ell(R(\mathbf{a}))\), \[ \nabla L(\mathbf{a}) = \bar{\mathbf{y}} + J_F(\mathbf{a})^\top\bar{\mathbf{y}} . \tag{11.2}\]

Proof. For \(\mathbf{h}\) small enough that \(\mathbf{a} + \mathbf{h}\in U\), \[ R(\mathbf{a}+\mathbf{h}) - R(\mathbf{a}) - (I + J_F(\mathbf{a}))\mathbf{h} = F(\mathbf{a}+\mathbf{h}) - F(\mathbf{a}) - J_F(\mathbf{a})\mathbf{h} . \] The right side is the remainder of \(F\), which divided by \(\|\mathbf{h}\|\) tends to \(\mathbf{0}\), so \(I + J_F(\mathbf{a})\) satisfies Equation 1.2 for \(R\). By Theorem 2.1, \(J_L(\mathbf{a}) = J_\ell(R(\mathbf{a}))\,(I + J_F(\mathbf{a}))\), and transposing this row gives Equation 11.2.

In the language of reverse mode, the adjoint \(\bar{\mathbf{y}}\) arriving at the output of the block reaches the input unchanged along the identity path, and the block adds its own contribution \(J_F^\top\bar{\mathbf{y}}\). However small \(J_F\) is, even zero, the gradient passes through. It can vanish only if the block’s contribution cancels it exactly, \(J_F^\top\bar{\mathbf{y}} = -\bar{\mathbf{y}}\), and a block with \(\|J_F\|_F < 1\) (in the norm defined next) cannot do that (Exercise 11.8). The difference matters when a network stacks many blocks. To make it quantitative we need a measure of the size of a matrix, and the Frobenius norm of Lemma 1.1 serves: for an \(m\times n\) matrix \(A = (a_{ij})\), \(\|A\|_F = \bigl(\sum_{i,j}a_{ij}^2\bigr)^{1/2}\), the Euclidean norm of the \(mn\) entries written as one long vector, and \(\|A\mathbf{x}\| \le \|A\|_F\,\|\mathbf{x}\|\) for every \(\mathbf{x}\in\mathbb{R}^n\). For example, \(A = \begin{pmatrix}1 & 2\\ 0 & 1\end{pmatrix}\) has \(\|A\|_F = \sqrt6\), and \(A^2 = \begin{pmatrix}1 & 4\\ 0 & 1\end{pmatrix}\) has \(\|A^2\|_F = \sqrt{18} \approx 4.24\), below \(\|A\|_F^2 = 6\). The norm of a product never exceeds the product of the norms.

Lemma 11.1 For matrices \(A\) (\(m\times n\)) and \(B\) (\(n\times p\)), \(\|AB\|_F \le \|A\|_F\,\|B\|_F\), and \(\|A^\top\|_F = \|A\|_F\).

Proof. Column \(j\) of \(AB\) is \(A\mathbf{b}_j\), where \(\mathbf{b}_j\) is column \(j\) of \(B\). By Lemma 1.1, \(\|A\mathbf{b}_j\|^2 \le \|A\|_F^2\|\mathbf{b}_j\|^2\), and summing over \(j\) gives \(\|AB\|_F^2 \le \|A\|_F^2\|B\|_F^2\). The second claim holds because \(A\) and \(A^\top\) have the same entries.

Corollary 11.1 (Stacked residual blocks) Let \(R_k(\mathbf{x}) = \mathbf{x} + F_k(\mathbf{x})\) for \(k = 1, \dots, K\), with each \(F_k\) differentiable on \(\mathbb{R}^n\). Fix \(\mathbf{x}_0\), let \(\mathbf{x}_k = R_k(\mathbf{x}_{k-1})\), let \(J_k = J_{F_k}(\mathbf{x}_{k-1})\), and let \(G = R_K\circ\dots\circ R_1\).

  1. \(J_G(\mathbf{x}_0) = (I + J_K)\cdots(I + J_1) = \sum_S J_S\), where the sum is over all \(2^K\) subsets \(S\) of \(\{1, \dots, K\}\) and \(J_S\) is the product of the \(J_k\) with \(k \in S\) in decreasing order of \(k\), with \(J_\emptyset = I\).

  2. If \(\|J_k\|_F \le \delta_k\) for each \(k\), then \[ \|J_G(\mathbf{x}_0) - I\|_F \le \prod_{k=1}^K (1 + \delta_k) - 1 \le e^{\delta_1 + \dots + \delta_K} - 1 . \]

  3. Under the hypothesis of (b), for a loss \(L(\mathbf{x}) = \ell(G(\mathbf{x}))\) with \(\ell\colon\mathbb{R}^n\to\mathbb{R}\) differentiable at \(\mathbf{x}_K\) and \(\bar{\mathbf{x}}_K = \nabla\ell(\mathbf{x}_K)\), the gradient \(\bar{\mathbf{x}}_0 = \nabla L(\mathbf{x}_0)\) satisfies \(\|\bar{\mathbf{x}}_0 - \bar{\mathbf{x}}_K\| \le \bigl(e^{\delta_1 + \dots + \delta_K} - 1\bigr)\|\bar{\mathbf{x}}_K\|\).

Proof.

  1. The first equality is Theorem 2.1 applied \(K - 1\) times with Theorem 11.3. Expanding the product by distributivity chooses, in each factor, either \(I\) or \(J_k\), and the choices correspond to subsets \(S\) (the set of \(k\) where the expansion takes \(J_k\)).

  2. By (a), \(J_G - I\) is the sum of \(J_S\) over non-empty \(S\). The Frobenius norm is the Euclidean norm of the matrix written as one long vector, so it satisfies the triangle inequality, and with Lemma 11.1, \[ \|J_G - I\|_F \le \sum_{S \ne \emptyset}\prod_{k\in S}\delta_k = \prod_{k=1}^K(1 + \delta_k) - 1 , \] where the equality is the same expansion of a product, now of numbers. Finally \(1 + \delta \le e^\delta\) for every real \(\delta\).

  3. \(\bar{\mathbf{x}}_0 = J_G^\top\bar{\mathbf{x}}_K\) by Theorem 2.1, so \(\bar{\mathbf{x}}_0 - \bar{\mathbf{x}}_K = (J_G - I)^\top\bar{\mathbf{x}}_K\), and Lemma 1.1 with Lemma 11.1 and (b) gives the bound.

Part (a) is the chain rule as a sum over paths (Theorem 2.2): each subset \(S\) is a route through the stack that enters the blocks in \(S\) and skips the others, and the route that skips every block carries the identity. Without the identity paths the Jacobian would be the single product \(J_K\cdots J_1\), whose norm is at most \(\delta_1\cdots\delta_K\); when every \(\delta_k\) is at most some \(\delta < 1\) this is at most \(\delta^K\), which tends to \(0\) as \(K\) grows, and gradients at the bottom of a deep stack become too small to train on. With residual connections, part (c) says that small blocks leave the gradient nearly unchanged instead.

Example 11.2 Take \(n = 2\), \(K = 2\) and two blocks with the same Jacobian \(N = \begin{pmatrix}0 & 1\\ 0 & 0\end{pmatrix}\). Without residual connections the Jacobian of the composition is \(N^2 = 0\): no gradient at all reaches the input, although each block alone has a non-zero Jacobian. With them it is \((I + N)^2 = I + 2N = \begin{pmatrix}1 & 2\\ 0 & 1\end{pmatrix}\), which is invertible.

11.3 The complete model

The previous chapters supply every part of the model; this section says exactly how they fit together, as one function from a sequence of symbols to predictions. As in Chapter 9, the symbols are tokens, the elements of a finite vocabulary \(V\) (Definition 9.1). Here \(|V| = 27\): the letters a to z, numbered \(0\) to \(25\) in alphabetical order, and the boundary token \(\diamond\), numbered 26, which marks the start and the end of a name. The name emma becomes the sequence \(\diamond, \mathtt{e}, \mathtt{m}, \mathtt{m}, \mathtt{a}, \diamond\), that is, \(26, 4, 12, 12, 0, 26\). At each position the model produces a vector of 27 logits, one real number per token, and the softmax of that vector, \(\operatorname{softmax}(\mathbf{z})_i = e^{z_i}/\sum_j e^{z_j}\) (see Definition 8.5), is the model’s probability distribution for the next token. A larger logit means a more probable token, and only differences between logits matter (Theorem A.3).

The other parts come from chapters 7 to 10.

  • A token embedding (Definition 9.6) represents each token by a learned vector, here in \(\mathbb{R}^{16}\); the width \(d = 16\) is the length of the vector that represents each position throughout the model.
  • Attention (Definition 10.1) computes, at each position \(t\), three vectors from the vector there: a query \(\mathbf{q}_t\), a key \(\mathbf{k}_t\) and a value \(\mathbf{v}_t\). Position \(t\) gives position \(j\) a weight that grows with the score \(\mathbf{q}_t\cdot\mathbf{k}_j\) (the weights are a softmax of the scores), and its output is the weighted average of the values. The causal mask (Definition 10.3) gives weight zero to positions \(j > t\), so no position sees later ones.
  • Multi-head attention (Definition 10.4) splits the query, key and value vectors into \(h\) consecutive pieces of length \(d_h = d/h\), the heads, runs attention separately on each piece, and places the \(h\) outputs one after another. Here \(h = 4\) and \(d_h = 4\).
  • An MLP (Definition 7.3) applies a matrix, then \(\operatorname{relu}(x) = \max(x, 0)\) (Definition 7.2) to each component, then a second matrix. Here the intermediate hidden vector has \(64 = 4d\) components.

The model reads at most 16 tokens, its context length (Definition 10.5), and has a single layer in the sense used for transformers: one attention block followed by one MLP block. (A layer of an MLP in Definition 7.1 is a smaller unit, one affine map and one activation function.) Its parameters are nine matrices, with no bias vectors and no normalisation gains:

  • \(E\) (\(27\times16\)), the token embedding (Definition 9.6): row \(x\) is the vector that represents token \(x\), and \(E_x\) denotes that row written as a column, the embedding \(\mathbf{u}_x\) of that definition. The rows of \(E\), like those of \(W_U\), are numbered 0 to 26 to match the tokens.
  • \(P\) (\(16\times16\)), the position embedding matrix, written \(E_{\mathrm{pos}}\) in Definition 10.5: row \(t\), written \(P_t\), is the vector added at position \(t\) (written \(\mathbf{p}_t\) in that definition; here \(\mathbf{p}_t\) is the model’s probability vector at position \(t\)).
  • \(W_Q\), \(W_K\), \(W_V\) (each \(16\times16\)): row \(i\) of \(W_Q\) gives component \(i\) of a query as a linear combination of the 16 components of the vector at that position, and likewise for keys and values.
  • \(W_O\) (\(16\times16\)): row \(i\) gives component \(i\) of the attention output as a linear combination of the 16 components of the four head outputs, so it mixes the heads.
  • \(W_1\) (\(64\times16\)) and \(W_2\) (\(16\times64\)): the two matrices of the MLP. Row \(i\) of \(W_1\) gives hidden component \(i\) before the ReLU; row \(i\) of \(W_2\) gives output component \(i\) from the 64 hidden components.
  • \(W_U\) (\(27\times16\)), the output matrix: row \(i\), dotted with the final vector at a position, gives the logit of token \(i\).

A vector \(\mathbf{q}\in\mathbb{R}^{16}\) splits into four heads, \(\mathbf{q}^{(i)} = (q_{4i-3}, \dots, q_{4i})\) for \(i = 1, \dots, 4\).

Definition 11.4 (The model) Let the parameters be matrices \(E\), \(P\), \(W_Q\), \(W_K\), \(W_V\), \(W_O\), \(W_1\), \(W_2\), \(W_U\) of the shapes listed above. For tokens \(x_1, \dots, x_T\) in \(\{0, \dots, 26\}\) with \(T \le 16\), and each position \(t = 1, \dots, T\), the model computes: \[ \begin{aligned} \mathbf{r}^{(0)}_t &= \operatorname{rms}(E_{x_t} + P_t) &&\text{embedding}\\ \mathbf{u}_t &= \operatorname{rms}(\mathbf{r}^{(0)}_t), \quad \mathbf{q}_t = W_Q\mathbf{u}_t, \quad \mathbf{k}_t = W_K\mathbf{u}_t, \quad \mathbf{v}_t = W_V\mathbf{u}_t &&\text{queries, keys, values}\\ \boldsymbol{\alpha}^{(i)}_t &= \operatorname{softmax}\Bigl( \frac{\mathbf{q}^{(i)}_t\cdot\mathbf{k}^{(i)}_1}{2}, \dots, \frac{\mathbf{q}^{(i)}_t\cdot\mathbf{k}^{(i)}_t}{2}\Bigr) &&\text{head } i = 1, \dots, 4\\ \mathbf{o}^{(i)}_t &= \sum_{j=1}^t \alpha^{(i)}_{tj}\,\mathbf{v}^{(i)}_j, \qquad \mathbf{o}_t = \bigl(\mathbf{o}^{(1)}_t, \dots, \mathbf{o}^{(4)}_t\bigr) &&\text{attention output}\\ \mathbf{r}^{(1)}_t &= \mathbf{r}^{(0)}_t + W_O\,\mathbf{o}_t &&\text{attention block}\\ \mathbf{r}^{(2)}_t &= \mathbf{r}^{(1)}_t + W_2\operatorname{relu}\bigl(W_1\operatorname{rms}(\mathbf{r}^{(1)}_t)\bigr) &&\text{MLP block}\\ \mathbf{z}_t &= W_U\,\mathbf{r}^{(2)}_t &&\text{logits} \end{aligned} \] with \(\operatorname{rms}\) as in Definition 11.1 (\(n = 16\), \(\varepsilon = 10^{-5}\)), \(\alpha^{(i)}_{tj}\) component \(j\) of \(\boldsymbol\alpha^{(i)}_t\), and \(\mathbf{o}_t\in\mathbb{R}^{16}\) the four head outputs placed one after another. The model’s distribution for the next token is \(\mathbf{p}_t = \operatorname{softmax}(\mathbf{z}_t)\).

Read from top to bottom, the equations say: represent token \(x_t\) at position \(t\) by the sum of two embedding rows and normalise it; let each head compare the query of position \(t\) with the keys of positions \(1\) to \(t\) and average their values with the resulting weights; add the mixed head outputs to the vector; add the output of the MLP; and multiply by \(W_U\) to get one logit per token. Only the attention line lets position \(t\) see other positions.

The divisor 2 in the attention scores is \(\sqrt{d_h}\). When the components of a query and a key are independent with mean 0 and variance 1, their dot product of \(d_h\) terms has variance \(d_h\), and dividing by \(\sqrt{d_h}\) brings the variance of the score back to 1 (Theorem 10.1). The attention line is causal multi-head attention (Definition 10.4, Definition 10.3): head \(i\) uses rows \(4i - 3\) to \(4i\) of \(W_Q\), \(W_K\) and \(W_V\) as its own query, key and value matrices, the weights \(\alpha^{(i)}_{tj}\) for \(j > t\) are zero, and \(W_O\) mixes the concatenated head outputs. The source counts positions from 0; here they run from 1, so \(P_t\) is row \(t\) of \(P\) in this book’s numbering.

Several details differ from GPT-2 (Radford et al. 2019), and each is visible in the equations. The vectors \(\mathbf{r}^{(0)}_t\), \(\mathbf{r}^{(1)}_t\), \(\mathbf{r}^{(2)}_t\), the successive states of the vector that represents position \(t\), form the residual stream at position \(t\). Each block reads a normalised copy of the stream and adds its output back. That is the arrangement of GPT-2, which moved normalisation from after the residual sum (Vaswani et al. 2017) to the input of each block. GPT-2 also normalises the stream once more before the output matrix; this model does not, so \(\mathbf{z}_t\) is a linear function of \(\mathbf{r}^{(2)}_t\). Instead, this model normalises the embedding sum before it enters the stream, so the stream starts with root mean square close to 1. It replaces layer normalisation by RMS normalisation without gain, and GELU (a smooth function close to ReLU) by ReLU. It has no biases. The output matrix \(W_U\) is a separate parameter, not a copy of \(E\).

The two blocks are residual blocks in the sense of Section 11.2. For the attention block the map \(F\) acts on the whole sequence \((\mathbf{r}^{(0)}_1, \dots, \mathbf{r}^{(0)}_T)\in\mathbb{R}^{16T}\), because position \(t\) attends to earlier positions, and Theorem 11.3 applies in \(\mathbb{R}^{16T}\). The normalisation sits inside \(F\), so the identity path from \(\mathbf{r}^{(0)}_t\) to \(\mathbf{r}^{(2)}_t\) passes through no normalisation and no matrix. The adjoint of the logits reaches \(\mathbf{r}^{(0)}_t\) as \(W_U^\top\bar{\mathbf{z}}_t\) plus the corrections from the two blocks.

The vector \(\mathbf{u}_t\) normalises a vector that is already normalised. In the forward pass this changes little: by Theorem 11.2 the mean square of \(\mathbf{r}^{(0)}_t\) is \(\mu/(\mu + \varepsilon)\), just below 1, and normalising it again multiplies it by a number close to 1 (Exercise 11.4). In the backward pass it does more: by Theorem 11.1 its Jacobian nearly removes the component of the adjoint along \(\mathbf{r}^{(0)}_t\), while the identity path keeps it.

The equations translate directly into array code. The function below computes every position at once, as matrices whose row \(t\) holds the vectors for position \(t\), and it implements the causal mask by setting the scores for \(j > t\) to \(-\infty\) before the softmax, so that their weights are \(e^{-\infty} = 0\). As in Equation 10.2, Q, K and V hold the queries, keys and values, so in the code V is the matrix of values, not the vocabulary.

import numpy as np

def rms_rows(X, eps=1e-5):
    """RMS-normalise each row of X."""
    return X / np.sqrt(np.mean(X**2, axis=-1, keepdims=True) + eps)

def logits(theta, tokens):
    """Logits z_1, ..., z_T (as rows) for a list of token numbers."""
    T = len(tokens)
    R0 = rms_rows(theta["E"][tokens] + theta["P"][:T])
    U = rms_rows(R0)
    Q, K, V = U @ theta["WQ"].T, U @ theta["WK"].T, U @ theta["WV"].T
    later = np.triu(np.ones((T, T), dtype=bool), k=1)   # entries with j > t
    O = np.zeros((T, 16))
    for j in range(4):
        c = slice(4 * j, 4 * j + 4)              # the columns of head j
        S = Q[:, c] @ K[:, c].T / 2.0  # scores q_t . k_j / sqrt(4)
        S[later] = -np.inf
        A = np.exp(S - S.max(axis=1, keepdims=True))
        A = A / A.sum(axis=1, keepdims=True)             # row t is alpha_t
        O[:, c] = A @ V[:, c]
    R1 = R0 + O @ theta["WO"].T
    R2 = R1 + np.maximum(rms_rows(R1) @ theta["W1"].T, 0.0) @ theta["W2"].T
    return R2 @ theta["WU"].T

Counting the parameters

Theorem 11.4 (Parameter count) The model has exactly 4192 parameters, distributed as follows.

Matrix Role Shape Entries
\(E\) token embedding \(27\times16\) 432
\(P\) position embedding \(16\times16\) 256
\(W_Q\), \(W_K\), \(W_V\) queries, keys, values \(16\times16\) each 768
\(W_O\) attention output \(16\times16\) 256
\(W_1\) MLP, first layer \(64\times16\) 1024
\(W_2\) MLP, second layer \(16\times64\) 1024
\(W_U\) output \(27\times16\) 432
total 4192

Proof. The parameters are the entries of the nine matrices of Definition 11.4: the normalisations have no gain and there are no biases, so nothing else changes in training. An \(m\times n\) matrix has \(mn\) entries, which gives the last column, and \(432 + 256 + 768 + 256 + 1024 + 1024 + 432 = 4192\).

The embeddings hold 688 parameters, the attention block 1024, the MLP block 2048 and the output matrix 432, so almost half the parameters sit in the MLP. The parameter vector \(\boldsymbol\theta\) of the model lies in \(\mathbb{R}^{4192}\).

11.4 Training

Training adjusts the parameters so that the model’s predictions match real names, and it needs a single number that measures the mismatch. For emma the model makes five predictions, one per position: \(\diamond\) followed by \(\mathtt{e}\), then \(\mathtt{e}\) by \(\mathtt{m}\), \(\mathtt{m}\) by \(\mathtt{m}\), \(\mathtt{m}\) by \(\mathtt{a}\), and \(\mathtt{a}\) by \(\diamond\). If it gave each correct token probability \(1/2\), the average of \(-\ln\) of these probabilities would be \(\ln 2 \approx 0.693\); if it gave each probability \(1/27\), as a model that knows nothing might, the average would be \(\ln 27 \approx 3.296\). That average is the loss of Definition 9.5.

In general, a name \(c_1c_2\cdots c_m\) becomes the token sequence \(x_1 = \diamond\), \(x_{i+1} = c_i\) for \(i = 1, \dots, m\), and \(x_{m+2} = \diamond\), numbered as in Definition 9.3. The model predicts each token from those before it. With \(T = \min(16, m + 1)\) predictions, the loss on the name is the average cross-entropy (Definition 8.3) \[ L(\boldsymbol\theta) = \frac1T\sum_{t=1}^T -\ln p_{t,\,x_{t+1}}, \tag{11.3}\] where \(p_{t,\,x}\) is component \(x\) of \(\mathbf{p}_t\) and \(\boldsymbol\theta\in\mathbb{R}^{4192}\) is the parameter vector of Section 11.3.1. The names in the training list have at most 15 letters (the source notes this), so \(T = m + 1\) and the last prediction is always the closing boundary token: the model learns where names end as well as how they start. The minimum in \(T\) only matters for longer documents, whose last targets the model never sees. By the chain rule of probability (Theorem 9.1), \(TL\) is minus the logarithm of the probability that the model assigns to the whole name, closing boundary included, and \(e^{L}\) is the perplexity of the model on it (Definition 9.5).

By Theorem 8.5, the adjoint of the logits at position \(t\) is \(\bar{\mathbf{z}}_t = (\mathbf{p}_t - \mathbf{e}_{x_{t+1}})/T\), where \(\mathbf{e}_x\) is the standard basis vector of token \(x\). Reverse mode carries these 27-component vectors back through the equations of Definition 11.4 to all 4192 parameters at once (Theorem 4.1).

Training runs Adam (Definition 6.7). Adam keeps, for each parameter, two exponential moving averages (Definition 6.6): \(m\) of its recent gradients, with decay rate \(\beta_1\), and \(v\) of their squares, with decay rate \(\beta_2\). It corrects both for their bias towards the starting value \(0\) (Theorem 6.9), giving \(\hat m\) and \(\hat v\), and subtracts the learning rate times \(\hat m/(\sqrt{\hat v} + \epsilon)\) from the parameter, so each parameter’s step is scaled by the recent size of its own gradients. Here \(\beta_1 = 0.85\), \(\beta_2 = 0.99\) and \(\epsilon = 10^{-8}\) (a different constant from the \(\varepsilon\) of RMS normalisation), and training runs for 1000 steps. Each step \(k = 1, \dots, 1000\), numbered as in Definition 6.7, takes one name from a shuffled list and computes \(L\) and its gradient, and Adam then updates \(\boldsymbol\theta\) with learning rate \[ \eta_k = 0.01\Bigl(1 - \frac{k - 1}{1000}\Bigr), \] which falls linearly from \(0.01\) at the first step to \(10^{-5}\) at the last, as in Section 6.6. (The source numbers the steps from 0.) There is no batching: each gradient comes from a single name. The list holds 32,033 names (Karpathy 2026a), so 1000 steps use about 3% of it, each name at most once. Adam keeps two numbers per parameter, so the optimiser state is \(2\times4192 = 8384\) numbers.

The source computes each softmax after subtracting the largest logit, and it treats that maximum as a constant in the computational graph. This does not change the derivative: subtracting a constant from every component does not change the softmax at all (Theorem A.3), so the two computations define the same function of the logits.

The loss before training

Before training, the loss tells us nothing about names, but its value is a useful test of an implementation, and Example 8.5 estimates it. A model that gives each of the 27 tokens probability \(1/27\) has loss \(\ln 27 \approx 3.296\). The book’s model starts close to that model, because every weight starts as an independent random sample with mean 0 and standard deviation \(\sigma_w = 0.08\), so the logits are small. Small random logits raise the expected loss above \(\ln 27\), and the second-order Taylor expansion of log-sum-exp in that example puts the excess at about \(\frac12\cdot\frac{26}{27}\cdot0.08^2\cdot16 \approx 0.049\), for an expected loss of about \(3.35\). The expansion comes with no bound on its error. The theorem below replaces it by inequalities that hold for the model of Definition 11.4.

Making this precise for the model needs random variables that can take any real value. Definition 7.4 defines the normal distribution \(N(\mu, s^2)\) through its density \(\varphi\): a random variable \(w\) with this distribution has mean \(\mu\) and variance \(s^2\), and \(\mathbb{E}[g(w)] = \int_{-\infty}^\infty g(t)\varphi(t)\,dt\) whenever \(\int_{-\infty}^\infty |g(t)|\varphi(t)\,dt\) is finite. microgpt draws every weight from \(N(0, 0.08^2)\), independently of the others. The proof also uses the rule that the expectation of a product of independent random variables is the product of their expectations, when these exist. Theorem 6.2 proves it for two random variables on a finite probability space, induction on the number of factors extends it to more (with Lemma 6.1), and as Section 7.5 notes it holds for random variables with densities too. The density gives one formula that the proof below uses: if \(w\) has distribution \(N(0, \sigma^2)\) and \(c\) is a real number, then, completing the square, \[ \mathbb{E}\bigl[e^{cw}\bigr] = \int_{-\infty}^\infty \frac{e^{cw - w^2/(2\sigma^2)}}{\sqrt{2\pi}\,\sigma}\,dw = e^{c^2\sigma^2/2}\int_{-\infty}^\infty \frac{e^{-(w - c\sigma^2)^2/(2\sigma^2)}}{\sqrt{2\pi}\,\sigma}\,dw = e^{c^2\sigma^2/2}, \tag{11.4}\] since the last integrand is the density of \(N(c\sigma^2, \sigma^2)\).

Theorem 11.5 (Loss at initialisation) In the model of Definition 11.4, fix the tokens and every parameter except \(W_U\), and let the entries of \(W_U\) be independent random variables with distribution \(N(0, \sigma_w^2)\), \(\sigma_w > 0\). Then at each position \(t\), with \(\mathbf{r} = \mathbf{r}^{(2)}_t\) and \(\ell_t = -\ln p_{t,\,x_{t+1}}\), \[ \ln 27 \;\le\; \mathbb{E}[\ell_t] \;\le\; \ln 27 + \frac{\sigma_w^2\|\mathbf{r}\|^2}{2} . \] The same bounds hold for the expected loss \(\mathbb{E}[L]\) of Equation 11.3, with \(\|\mathbf{r}\|^2\) replaced by the average of \(\|\mathbf{r}^{(2)}_t\|^2\) over \(t\).

Proof. The vector \(\mathbf{r}\) does not involve \(W_U\), so it stays fixed. Write \(\mathbf{w}_i\) for row \(i\) of \(W_U\) (as a column), so that \(z_i = \mathbf{w}_i\cdot\mathbf{r}\), and let \(y = x_{t+1}\). Then \[ \ell_t = \ln\sum_{i} e^{z_i} - z_y , \] with the sum over the 27 tokens.

Lower bound. Let \(\bar z = \frac1{27}\sum_i z_i\). The tangent line to the exponential at \(\bar z\) lies below it: \(e^{z} \ge e^{\bar z}(1 + z - \bar z)\) for all \(z\). Summing over the 27 values \(z_i\) gives \(\sum_i e^{z_i} \ge 27e^{\bar z}\), so \(\ell_t \ge \ln 27 + \bar z - z_y\). Each \(z_i\) has expectation \(\sum_j r_j\,\mathbb{E}[(\mathbf{w}_i)_j] = 0\), so taking expectations gives \(\mathbb{E}[\ell_t] \ge \ln 27\).

Upper bound. The tangent line to the logarithm at \(m > 0\) lies above it: \(\ln Y \le \ln m + (Y - m)/m\) for \(Y > 0\). Take \(Y = \sum_i e^{z_i}\) and \(m = \mathbb{E}[Y]\); taking expectations, \(\mathbb{E}[\ln Y] \le \ln\mathbb{E}[Y]\). The entries of \(\mathbf{w}_i\) are independent, so by Equation 11.4 \[ \mathbb{E}\bigl[e^{z_i}\bigr] = \prod_{j=1}^{16}\mathbb{E}\bigl[e^{r_j(\mathbf{w}_i)_j}\bigr] = \prod_{j=1}^{16}e^{r_j^2\sigma_w^2/2} = e^{\sigma_w^2\|\mathbf{r}\|^2/2}, \] and \(\mathbb{E}[Y] = 27e^{\sigma_w^2\|\mathbf{r}\|^2/2}\). With \(\mathbb{E}[z_y] = 0\) this gives the upper bound. The statement for \(L\) follows by averaging over \(t\), since expectation is linear.

How large is \(\|\mathbf{r}^{(2)}_t\|^2\) at initialisation? By Theorem 11.2, \(\|\mathbf{r}^{(0)}_t\|^2 = 16\lambda^2\) is just below 16. The two blocks add \(W_O\mathbf{o}_t\) and \(W_2\mathbf{g}_t\), with \(\mathbf{g}_t\) the MLP’s hidden vector. Since \(W_O\) is independent of \(\mathbf{r}^{(0)}_t\) and \(\mathbf{o}_t\) and has mean zero, the cross term \(\mathbb{E}[\mathbf{r}^{(0)}_t\cdot W_O\mathbf{o}_t]\) vanishes, and likewise for \(W_2\), so \[ \mathbb{E}\|\mathbf{r}^{(2)}_t\|^2 = \mathbb{E}\|\mathbf{r}^{(0)}_t\|^2 + \mathbb{E}\|W_O\mathbf{o}_t\|^2 + \mathbb{E}\|W_2\mathbf{g}_t\|^2 . \] Over 400 random initialisations, averaged over the positions of the name “isabella”, the three terms are about 16.0, 0.06 and 0.33, so \(\|\mathbf{r}^{(2)}_t\|^2 \approx 16.4\) and the gap \(\sigma_w^2\|\mathbf{r}\|^2/2\) in Theorem 11.5 is about \(0.052\). The expected initial loss therefore lies between \(3.296\) and about \(3.35\). A direct simulation, averaging the loss of Equation 11.3 over 400 random initialisations and a dozen names, gives \(3.35\), at the top of that range and in agreement with the estimate of Example 8.5; the standard deviation of a single document’s loss is about 0.14. The microgpt post reports a loss of 3.37 at the first step, consistent with this, and about 2.37 after 1000 steps (Karpathy 2026a).

11.5 Sampling and temperature

After training, the model generates a name by sampling. It starts with \(x_1 = \diamond\) at position 1, computes \(\mathbf{z}_1\), draws \(x_2\) at random from a distribution built from \(\mathbf{z}_1\), feeds \(x_2\) back in at position 2, and continues until it draws \(\diamond\) or has drawn 16 tokens. The letters drawn before the boundary token form the name, so a sample has at most 16 letters. The distribution is not \(\operatorname{softmax}(\mathbf{z}_t)\) itself but \(\operatorname{softmax}(\mathbf{z}_t/T)\) for a temperature \(T > 0\); microgpt uses \(T = 0.5\). (In this section \(T\) is the temperature, not the length of a sequence.)

Dividing the logits by \(T\) multiplies all their differences by \(1/T\). For \(T < 1\) this exaggerates the differences and concentrates the probability on the likeliest tokens; for \(T > 1\) it flattens the distribution.

Example 11.3 Let \(\mathbf{z} = (2, 1, 0)\). At \(T = 1\) the probabilities are \((0.665, 0.245, 0.090)\); at \(T = 0.5\) they are \(\operatorname{softmax}(4, 2, 0) = (0.867, 0.117, 0.016)\); at \(T = 0.1\) the first is \(0.99995\); and at \(T = 100\) they are \((0.3367, 0.3333, 0.3300)\), close to uniform.

As \(T\) falls the distribution approaches the standard basis vector \(\mathbf{e}_1\), the one-hot vector (Section 8.6) that puts probability 1 on the token with the largest logit, and as \(T\) grows it approaches the uniform distribution. The limits are exact, and the only subtlety is a tie for the largest logit.

Theorem 11.6 (Temperature limits) Let \(\mathbf{z}\in\mathbb{R}^n\) and, for \(T > 0\), \(\mathbf{p}(T) = \operatorname{softmax}(\mathbf{z}/T)\). Let \(M = \max_i z_i\), let \(A = \{i : z_i = M\}\) be the set of positions where the maximum is attained, and let \(k\) be the number of elements of \(A\).

  1. As \(T\to\infty\), \(\mathbf{p}(T) \to \frac1n\mathbf{1}\), the uniform distribution.

  2. As \(T\to0\) through positive values, \(p_i(T) \to 1/k\) for \(i \in A\) and \(p_i(T) \to 0\) for \(i \notin A\). In particular, if the maximum is attained at a single position \(i^*\), then \(\mathbf{p}(T) \to \mathbf{e}_{i^*}\).

Proof.

  1. For each \(i\), \(z_i/T \to 0\), so \(e^{z_i/T} \to 1\) by continuity of the exponential. The denominator \(\sum_j e^{z_j/T}\) tends to \(n\), which is not \(0\), so \(p_i(T) \to 1/n\).

  2. Multiplying the numerator and denominator of \(p_i(T)\) by \(e^{-M/T}\), \[ p_i(T) = \frac{e^{(z_i - M)/T}}{\sum_{j=1}^n e^{(z_j - M)/T}} . \] For \(j\in A\) the term \(e^{(z_j - M)/T}\) equals \(1\) for every \(T\). For \(j\notin A\), \(z_j - M < 0\), so \((z_j - M)/T \to -\infty\) as \(T \to 0\) and \(e^{(z_j - M)/T} \to 0\). So the denominator tends to \(k \ge 1\), and the numerator tends to \(1\) if \(i\in A\) and to \(0\) otherwise.

When several logits tie for the maximum, the limit at low temperature is uniform over the tied tokens: the temperature cannot break a tie. At \(T = 1\) the model samples from its own distribution \(\mathbf{p} = \operatorname{softmax}(\mathbf{z})\), and in general \(\operatorname{softmax}(\mathbf{z}/T)\) is proportional to the vector of powers \(p_i^{1/T}\) (Exercise 11.6). At \(T = 0.5\) the model samples token \(i\) with probability proportional to \(p_i^2\).

11.6 Caching keys and values

Generating a name token by token seems to require running the model on the whole prefix \(x_1, \dots, x_t\) at every step \(t\). For a name of 16 tokens that means processing \(1 + 2 + \dots + 16 = 136\) positions, although only 16 of them are new: at step 3, for example, the keys and values of positions 1 and 2 are the same ones already computed at steps 1 and 2. The repeated work is unnecessary. Everything in Definition 11.4 except attention works on one position at a time, and by Theorem 10.2 causal attention at position \(t\) needs only the query of position \(t\) and the keys and values of positions \(1\) to \(t\). So a program can keep the key–value cache of Section 10.3, a list of the key and value vectors of the positions seen so far, and process each new position once.

Definition 11.5 (Cached evaluation) Given tokens \(x_1, \dots, x_T\) in \(\{0, \dots, 26\}\) with \(T \le 16\), the cached evaluation of the model starts with an empty list \(C\) and, for \(t = 1, \dots, T\) in turn:

  1. computes \(\mathbf{r}^{(0)}_t\), \(\mathbf{u}_t\), \(\mathbf{q}_t\), \(\mathbf{k}_t\) and \(\mathbf{v}_t\) from \(x_t\) and \(t\) by the formulas of Definition 11.4, and appends \((\mathbf{k}_t, \mathbf{v}_t)\) to \(C\);
  2. computes \(\hat{\mathbf{o}}_t\) by the attention formulas of Definition 11.4, using \(\mathbf{q}_t\) and every pair in \(C\);
  3. computes \(\hat{\mathbf{r}}^{(1)}_t\), \(\hat{\mathbf{r}}^{(2)}_t\) and \(\hat{\mathbf{z}}_t\) from \(\mathbf{r}^{(0)}_t\) and \(\hat{\mathbf{o}}_t\) by the remaining formulas.

Theorem 11.7 (Caching computes causal attention) Take the model of Definition 11.4 with any values of its parameters. For every \(T \le 16\) and tokens \(x_1, \dots, x_T\), the cached evaluation of Definition 11.5 gives \(\hat{\mathbf{z}}_t = \mathbf{z}_t\) for \(t = 1, \dots, T\), where \(\mathbf{z}_t\) are the logits of Definition 11.4 computed for the whole sequence, and \(\mathbf{z}_t\) depends only on \(x_1, \dots, x_t\).

Proof. In Definition 11.4, \(\mathbf{r}^{(0)}_t\), \(\mathbf{u}_t\), \(\mathbf{q}_t\), \(\mathbf{k}_t\) and \(\mathbf{v}_t\) are functions of \(x_t\) and \(t\) alone, and \(\mathbf{r}^{(1)}_t\), \(\mathbf{r}^{(2)}_t\) and \(\mathbf{z}_t\) are functions of \(\mathbf{r}^{(0)}_t\) and \(\mathbf{o}_t\) alone. Only \(\mathbf{o}_t\) involves other positions. The output \(\mathbf{o}^{(i)}_t\) of head \(i\) is causal self-attention of width 4 with its own rows of \(W_Q\), \(W_K\) and \(W_V\) (Definition 10.4), applied to \(\mathbf{u}_1, \dots, \mathbf{u}_T\). By Theorem 10.2, applied to each head, \(\mathbf{o}^{(i)}_t\) is the unmasked attention of \(\mathbf{q}^{(i)}_t\) over the pairs \((\mathbf{k}^{(i)}_j, \mathbf{v}^{(i)}_j)\) with \(j \le t\), and it depends only on \(\mathbf{u}_1, \dots, \mathbf{u}_t\). Hence \(\mathbf{z}_t\) is a function of \(x_1, \dots, x_t\), which proves the second claim.

At step \(t\) of the cached evaluation, after the append, \(C\) holds exactly the \(t\) pairs \((\mathbf{k}_j, \mathbf{v}_j)\) for \(j = 1, \dots, t\), in order, each computed from \(x_j\) and \(j\) by the same formula as in the whole-sequence computation and therefore equal to it. Step 1 computes the same \(\mathbf{r}^{(0)}_t\) and \(\mathbf{q}_t\). Step 2 computes, in each head, the attention of \(\mathbf{q}^{(i)}_t\) over these \(t\) pairs, which is \(\mathbf{o}^{(i)}_t\) by the first part of the proof, so \(\hat{\mathbf{o}}_t = \mathbf{o}_t\). Step 3 then gives \(\hat{\mathbf{z}}_t = \mathbf{z}_t\).

With several layers the keys and values of layer \(l\) come from the residual stream after layer \(l - 1\), which depends on earlier positions, so they are no longer functions of \(x_t\) and \(t\) alone. The same argument then runs by induction on \(t\), and within each \(t\) by induction on the layer: once the cached and whole-sequence values agree at all positions before \(t\), they agree at position \(t\) layer by layer.

The theorem matters for generation and for training. In generation, the token drawn at step \(t\) comes from the softmax of \(\mathbf{z}_t\) divided by the temperature (Section 11.5), and \(\mathbf{z}_t\) is the same whether computed with the cache or from scratch, so caching changes the cost and not the distribution of the samples. In training, microgpt computes the loss with the cache too, one position at a time. The cached and whole-sequence computations define the same function \(L(\boldsymbol\theta)\), so they have the same gradient, and reverse mode may differentiate through the cache like any other computation. Since appending tokens never changes the logits at earlier positions, one pass over a name trains all of its predictions.

11.7 What the small model leaves out

The model computes the same kind of function as production language models, at a much smaller size, and several things are missing.

Tokenisation. The model reads single characters from a vocabulary of 27. GPT-2 reads text as bytes merged into frequent sequences by byte-pair encoding (Sennrich et al. 2016), with a vocabulary of 50,257 tokens (Radford et al. 2019). A token is then often a whole word or a piece of one, and the embedding and output matrices, each \(|V|\times d\), become large.

Size. The model has one layer of width 16 and a context of 16 positions. The four GPT-2 models have 12 to 48 layers, widths 768 to 1600, a context of 1024 tokens, and between 117 million and 1542 million parameters (Radford et al. 2019). More layers means more residual blocks in the stack of Corollary 11.1.

Batching. Each training step here uses one name, processed one position at a time. Production training computes all positions of a sequence at once with the causal mask, as in the array code of Section 11.3, and averages the gradient over many sequences per step (GPT-2 used 512). Theorem 11.7 is what makes the all-at-once form give the same loss.

Other components. GPT-2 uses layer normalisation with gain and bias, biases in its linear maps, the GELU activation in place of ReLU, and a final normalisation before the output matrix. Production systems also train in lower-precision arithmetic than the 64-bit floating point used here (Appendix A).

11.8 Notes and further reading

Karpathy (2026a) walks through the code of the model line by line; the code is Karpathy (2026b). Radford et al. (2019) describes GPT-2, and Vaswani et al. (2017) the original transformer, with normalisation after each residual sum. Xiong et al. (2020) compare the two placements of normalisation and show that placing it at the input of each block, as this model does, gives better-behaved gradients at initialisation. Layer normalisation is from Ba et al. (2016) and RMS normalisation from Zhang and Sennrich (2019); residual connections are from He et al. (2016). Byte-pair encoding for text comes from Sennrich et al. (2016).

11.9 Exercises

Exercise 11.1 Let \(n = 2\), \(\varepsilon = 1/2\) and \(\mathbf{x} = (3, 4)\). Compute \(\operatorname{rms}(\mathbf{x})\) and its Jacobian at \(\mathbf{x}\), and check that the Jacobian has eigenvalues \(s\) and \(\varepsilon s^3\) as Theorem 11.1 says.

Exercise 11.2 Let \(\mathbf{y} = \operatorname{rms}(\mathbf{x})\) and let \(\bar{\mathbf{x}} = J^\top\bar{\mathbf{y}}\), with \(J\) the Jacobian of Theorem 11.1. Show that \(\mathbf{x}\cdot\bar{\mathbf{x}} = \varepsilon s^3\,(\mathbf{x}\cdot\bar{\mathbf{y}})\). Deduce that if \(\varepsilon\) were \(0\) (and \(\mathbf{x}\ne\mathbf{0}\)) the gradient with respect to \(\mathbf{x}\) would always be perpendicular to \(\mathbf{x}\), and explain this from Theorem 11.2.

Exercise 11.3 Let \(C = I - \frac1n\mathbf{1}\mathbf{1}^\top\), the \(n\times n\) centring matrix. Show that \(C\mathbf{x} = \mathbf{x} - m(\mathbf{x})\mathbf{1}\) and \(v(\mathbf{x}) = \mu(C\mathbf{x})\), so that layer normalisation with \(\mathbf{g} = \mathbf{1}\) and \(\mathbf{b} = \mathbf{0}\) is \(\operatorname{rms}\circ C\). Find its Jacobian and show that it sends \(\mathbf{1}\) to \(\mathbf{0}\).

Exercise 11.4  

  1. Show that \(\operatorname{rms}(\operatorname{rms}(\mathbf{x})) = c\,\operatorname{rms}(\mathbf{x})\) with \(c = \bigl(\mu/(\mu + \varepsilon) + \varepsilon\bigr)^{-1/2}\), where \(\mu = \mu(\mathbf{x})\).

  2. Show that \(c = 1\) exactly when \(\mu = 1 - \varepsilon\).

  3. For \(\mu = 1\) and \(\varepsilon = 10^{-5}\), show that \(c^2 = (1 + \varepsilon)/(1 + \varepsilon + \varepsilon^2)\) and that \(1 - c\) is about \(5\times10^{-11}\).

Exercise 11.5 Generalise Theorem 11.4 to a model with vocabulary size \(|V|\), context length \(n_c\), width \(d\), \(K\) layers (each with its own attention and MLP blocks, as in Definition 11.4) and MLP width \(4d\). Show that the number of parameters is \(2|V|d + n_cd + 12Kd^2\) and that it does not depend on the number of heads. How many parameters does the model have with \(d = 32\) and \(K = 2\), other sizes unchanged?

Exercise 11.6 Let \(\mathbf{p} = \operatorname{softmax}(\mathbf{z})\). Show that for every \(T > 0\), \[ \operatorname{softmax}(\mathbf{z}/T)_i = \frac{p_i^{1/T}}{\sum_j p_j^{1/T}} . \] Find the sampling distribution at \(T = 0.5\) when \(\mathbf{p} = (0.5, 0.3, 0.2)\).

Exercise 11.7 Let \(\mathbf{z} = (1, 3, 3, 0)\). Find the limits of \(\operatorname{softmax}(\mathbf{z}/T)\) as \(T\to0\) and as \(T\to\infty\), and its value at \(T = 1/\ln 2\).

Exercise 11.8 Let \(F\colon\mathbb{R}^n\to\mathbb{R}^n\) be differentiable at \(\mathbf{a}\) with \(\|J_F(\mathbf{a})\|_F < 1\). Show that the Jacobian \(I + J_F(\mathbf{a})\) of the residual block is invertible. Give an example with \(\|J_F(\mathbf{a})\|_F = 1\) where it is not.

Exercise 11.9 Extend Exercise 10.5 to the model of Definition 11.4. Count only the multiplications in attention scores (\(\mathbf{q}^{(i)}_t\cdot\mathbf{k}^{(i)}_j\), \(d_h\) each) and in weighted sums of values (\(d_h\) per head for each \(j\)). Show that generating \(n\) positions with the cache costs \(d\,n(n+1)\) such multiplications, while recomputing all positions from scratch at every step costs \(d\,n(n+1)(n+2)/3\). Evaluate both for \(d = n = 16\).