Lecture 5 — The Transformer
Project connection. Project Step 5 assembles the full architecture and verifies its parameter count. The course configuration is .
Chapter overview. One attention head supplies one content-dependent average of a low-dimensional view of the residual stream. A transformer runs several such heads, applies a nonlinear MLP independently at each position, and places both operations on residual branches. LayerNorm controls the feature scale presented to each branch. Stacking these blocks between embedding and unembedding maps gives the complete decoder-only generative pretrained transformer (GPT) used in the project.
0. Architectural notation
Let be the maximum supported sequence length, the current sequence length, the residual-stream width, the number of heads, and the number of transformer blocks. Assume divides and define
As in Lecture 4, matrices in store feature vectors as rows. Every attention head is causally masked unless explicitly stated otherwise.
A LayerNorm map acts independently on each row: it centers the feature coordinates, rescales by their root mean square, and then applies learned coordinatewise gains and shifts. Section 4 gives its exact formula and geometry.
1. Multi-head attention
For head , let
and let
be the scaled dot-product attention map of Lecture 4. Let be the output projection.
Definition 1.1 (multi-head attention). The multi-head attention map is
where the bracket denotes concatenation along the feature dimension.
Partition vertically into blocks , so . Let be the attention matrix of head .
Proposition 1.2 (additive head decomposition). Multi-head attention can be written as
Moreover, .
Proof. If , block matrix multiplication gives
Substitution yields the formula. The rank of a product is at most its inner dimension.
The score matrix of head is
Thus is a rank-at-most- bilinear form controlling the attention pattern, while is a rank-at-most- map controlling the information written to the stream.
Remark 1.3 (QK and OV circuits). In the transformer-circuits terminology, the QK circuit specifies where to read and the OV circuit specifies what to write. The individual factorizations are not identifiable. For example, for invertible , replacing by and by preserves .
Remark 1.4 (role of multiple heads). One full-width head supplies one attention distribution per query position. Splitting the same projection budget among heads supplies independently learned distributions, each with a low-rank read/write channel. The parameter count remains . The inductive bias, meaning a structural preference built into the model class, changes from one high-dimensional lookup to several parallel low-dimensional lookups.
2. The position-wise MLP
Let be the hidden width, let , , and let , . Let be the GELU activation, where is the standard normal cumulative distribution function.
Definition 2.1 (MLP sublayer). The position-wise MLP is
applied independently with the same parameters to every row of the residual stream. The course model uses .
Remark 2.2 (division of labor). Attention is the only sublayer that communicates between sequence positions. The MLP performs a learned nonlinear feature transformation at each position separately. Attention is itself nonlinear through its softmax, and LayerNorm is also nonlinear; the precise claim is that the MLP is the dedicated position-wise feature computation that can move beyond the convex-hull restriction on the current attention values.
With , the two weight matrices contain parameters and the biases contain . This exceeds the approximately attention parameters in each block.
3. Residual connections and pre-normalization
Let and be two LayerNorm maps.
Definition 3.1 (pre-norm transformer block). A transformer block maps to by
The additions are residual connections. A map of the form
has Jacobian
Remark 3.2 (discrete dynamical system). The update resembles a forward Euler step for an ordinary differential equation . Under this analogy, depth plays the role of time and the residual stream is the evolving state.
Remark 3.3 (gradient path). A residual connection supplies an exact identity term in every block Jacobian. If the residual derivatives are controlled, the product of block Jacobians is a product of perturbations of the identity rather than arbitrary matrices. This architecture mitigates vanishing and exploding gradients; the residual formula alone does not guarantee that every is small.
Remark 3.4 (communication channel). Every sublayer reads the same running state and adds an increment. Features written by an early block can therefore be read by a later block. The width is the linear bandwidth of this channel, although superposition—encoding features in nonorthogonal directions—can represent more features than coordinates (Lecture 8). This additive structure underlies the path decompositions used in mechanistic interpretability.
Empirical aside 3.5 (small residual updates). In many trained models, individual branch updates are small relative to the stream. In that regime blocks are approximately composable, and dropping one block may have a modest effect. This is an observed property, not a consequence of the residual formula alone.
Aside 3.5 (pre-norm versus post-norm). The original transformer used , called post-norm. GPT-2-style pre-norm uses , preserving an unnormalized identity path around the branch. The course project uses pre-norm.
4. LayerNorm geometry
For , define its coordinate mean and variance by
Let denote coordinatewise multiplication, let , and fix a small numerical constant .
Definition 4.1 (LayerNorm). With learned vectors , define
It is applied separately to each sequence position.
Proposition 4.2 (projection and radial rescaling). Assume . Set , , and , and restrict to nonconstant . Then the normalization map is the composition of:
- orthogonal projection onto ; and
- radial projection onto the sphere of radius in that hyperplane.
Its image is
which is a -dimensional sphere.
Proof. The map is the orthogonal projection onto : it is self-adjoint and idempotent, with kernel . Let . Then
The unit sphere in a -dimensional vector space has dimension .
Remark 4.3 (scale invariance). Under the idealized hypotheses of the proposition, for . Consequently, the normalized sublayer input depends on direction rather than positive scale. A nonzero makes this invariance only approximate near zero variance, while learned and restore coordinatewise scale and shift after normalization.
Aside 4.4 (LayerNorm versus BatchNorm). BatchNorm uses statistics across examples in a minibatch. LayerNorm uses coordinates within one position, so its output does not depend on which other examples share the batch and remains defined at batch size one. RMSNorm omits mean centering and retains only radial rescaling.
5. The GPT specification
Let be the token embedding matrix and the learned positional embedding matrix. For tokens , define
For , define
Finally, with a final LayerNorm and unembedding matrix , define logits
and next-token probabilities
Remark 5.1 (causality). Token and positional embeddings, LayerNorm, MLPs, residual additions, and unembedding act position-wise. The only cross-position operation is attention, whose causal mask satisfies Lecture 4, Proposition 4.3. Composition therefore makes each logit row a function only of .
Theorem 5.2 (exact parameter count). Assume , biases on the MLP maps and attention output projection, and no biases on , or . Then the number of trainable scalar parameters is
Equivalently, it is
Proof. Across all heads, the query, key, and value matrices contain parameters. The output projection contributes , so attention contributes . The MLP weights contribute , and its biases contribute . Each LayerNorm has gains and shifts, so two contribute . Add the embedding, final-normalization, and unembedding terms.
For :
| component | parameters | share |
|---|---|---|
| token and positional embeddings | 16,512 | 2.0% |
| attention in all blocks | 262,656 | 32.2% |
| MLPs in all blocks | 526,848 | 64.5% |
| block LayerNorms | 2,048 | 0.3% |
| final LayerNorm and unembedding | 8,576 | 1.0% |
| total | 816,640 | 100% |
The leading block term is ; biases and normalization parameters add .
Project aside 5.2 (initialization). There are residual writes. Under the approximation that their contributions are independent with comparable variance, scaling each branch’s output projection by keeps their accumulated variance of order one. Lecture 6 derives this bookkeeping. The course model begins with loss near , as expected for nearly uniform predictions.
Aside 5.3 (weight tying). GPT-2 identifies the unembedding with the transpose of the token embedding, . The course’s baseline count keeps them separate so that the accounting is explicit.
6. Computational cost
A forward pass on a length- sequence has the leading operation counts
| component | leading cost |
|---|---|
| query, key, value, and output projections | |
| attention scores and value aggregation | |
| MLP sublayers |
Thus total cost is . The attention term becomes dominant when is large relative to .
Rule-of-thumb aside 6.1. Dense transformer training is often estimated as floating-point operations: roughly two operations per forward multiply—accumulate and about twice the forward cost for the two backward derivatives. The approximation ignores attention’s non-parameterized work and hardware details; Exercise 8 asks for its derivation and limitations.
Summary
Multi-head attention is an additive sum of low-rank head contributions. Each head has a QK circuit controlling its attention pattern and an OV circuit controlling its write to the stream. Position-wise MLPs supply the dedicated nonlinear feature transformation at each token. Residual connections create identity gradient paths and a shared evolving state. Idealized LayerNorm projects to and rescales to a -sphere. These components give a complete causal GPT with exactly 816,640 parameters in the course configuration and leading cost .
Exercises (paired with Step 5)
A star marks a Project Step 5 task.
- ★ Re-derive Theorem 5.2 using the bias conventions in your code and
verify the result against
numel()exactly. - ★ Prove end-to-end causality of the GPT specification and verify it by perturbing future tokens.
- Prove Proposition 1.2. Describe the non-identifiability of the QK factorization. For a generic fixed QK matrix, compute the dimension of the set of factor pairs that represent it.
- Prove Proposition 4.2 and its positive-scale invariance consequence. Discuss weight decay immediately before a LayerNorm.
- Recount the parameters under weight tying .
- Prove and . Explain how multiple heads alter, but do not remove, these constraints.
- Compare the Jacobians of one pre-norm and one post-norm residual block.
- Derive the training-cost rule and identify regimes in which attention’s term invalidates it.
Pointers
Vaswani et al., Attention Is All You Need (2017); Radford et al., GPT-2 (2019); Ba, Kiros, and Hinton, Layer Normalization (2016); He et al., Deep Residual Learning (2015); Elhage et al., A Mathematical Framework for Transformer Circuits (2021); Phuong and Hutter, arXiv:2207.09238. See also bbycroft.net/llm, the resources page, and Project Step 5.