Chapter 1 · Core Transformer Components¶
1.1 How is self-attention computed, and what are its time and memory complexity? ★★★¶
One-sentence answer
Self-attention first projects each token's vector into a query, a key and a value, then takes the dot product of the query with every key and divides by \(\sqrt{d_k}\) to get scores, turns the scores into weights with a softmax, and finally takes the weighted sum of the values. For a sequence of length \(n\) and dimension \(d\), scoring and the weighted sum cost \(O(n^2d)\) compute, and in a standard implementation the score matrix takes \(O(n^2)\) memory; the projections and the FFN cost \(O(nd^2)\), so the longer the sequence, the more the quadratic term becomes the bottleneck.
I will address three aspects: the problem attention solves, the concrete computation steps, and the complexity.
(1) Attention lets each token gather the information it needs from other tokens, based on context.
The meaning of a word often depends on its context; for example, "apple" means something completely different in "I ate an apple" and "Apple released a new phone". Attention computes, for each token, a set of weights indicating how much information it should take from each position, and then aggregates accordingly. Unlike convolutions and RNNs, these weights are not fixed parameters but are computed dynamically from the current input; moreover, any two positions interact directly in a single step, without the step-by-step relay of an RNN, so long-range dependencies are easier to learn and training can be parallelized.
(2) The computation consists of four steps: projection, scoring, normalization and weighted sum.
The input \(X\in\mathbb{R}^{n\times d}\) (\(n\) tokens, each \(d\)-dimensional) first passes through three learned matrices, giving \(Q=XW_Q\), \(K=XW_K\) and \(V=XW_V\). Intuitively, the query says "what information am I looking for", the key says "what information do I have", and the value is "what I will pass to you if you attend to me". We then compute
Here \(QK^\top\) is the \(n\times n\) score matrix, whose entry in row \(i\) and column \(j\) measures how relevant the query of token \(i\) is to the key of token \(j\); dividing by \(\sqrt{d_k}\) (\(d_k\) is the key dimension) controls the scale of the scores (see 1.2 for why); \(M\) is the mask, which is \(-\infty\) at blocked positions (see 1.4); the softmax turns each row of scores into weights that sum to 1; and finally these weights are used to take a weighted sum of the rows of \(V\), giving each token's output.
(3) Complexity: scoring and the weighted sum cost \(O(n^2d)\), while the projections and the FFN cost \(O(nd^2)\).
Every token computes a score with all \(n\) tokens, so the score matrix has \(n^2\) entries, each a \(d\)-dimensional dot product; \(QK^\top\) therefore costs \(O(n^2d)\), and multiplying the weights by \(V\) also costs \(O(n^2d)\); a standard implementation stores the full score matrix, taking \(O(n^2)\) memory per head. In contrast, the Q, K, V, O projections and the FFN act on each token separately, costing \(O(nd^2)\). Hence, for short sequences the projections and the FFN dominate, but once \(n\) is clearly larger than \(d\), the quadratic term becomes the bottleneck, which is the root reason long contexts are expensive. FlashAttention reduces the extra memory to \(O(n)\) by computing in blocks, but the compute remains \(O(n^2d)\) (see 2.3 in Chapter 2).
In summary: self-attention is a weighted average whose weights are determined dynamically by the input, and its price is compute that grows quadratically with sequence length.
Going deeper: the cost of each part, and when the quadratic term becomes the bottleneck
(1) The forward compute of each part of a layer.
Counting one multiply-add as 2 FLOPs, the forward compute of one layer on a sequence of length \(n\) is:
| Part | Compute (FLOPs) | Extra memory |
|---|---|---|
| Q, K, V, O projections | \(8nd^2\) | \(O(nd)\) |
| FFN (4× width) | \(16nd^2\) | \(O(nd)\) |
| \(QK^\top\) | \(2n^2d\) | \(O(n^2)\) per head in a standard implementation |
| Weights times \(V\) | \(2n^2d\) | \(O(nd)\) |
(2) The ratio of the quadratic term to the linear term is about \(n/(6d)\).
The ratio is \(4n^2d / 24nd^2 = n/(6d)\). In a causal model, the upper triangle of the score matrix is masked, and efficient implementations can skip that half of the computation, giving a ratio of about \(n/(12d)\), which matches the estimate in 3.9 of Chapter 3 of the LLM Training Pipeline direction. For example, with \(d=4096\), a 4K context adds only about 8% compute for attention; at a context of about 50K, attention costs as much as everything else.
(3) Lowering the complexity requires changing attention itself.
Sliding-window attention and sparse attention let each token see only some positions; linear attention and state-space models (such as Mamba, Gu & Dao 2023) compress the history into a fixed-size state, bringing the complexity down to \(O(n)\), at the cost of a weaker ability to recall exact details (see Chapter 2, and 0.5 in Chapter 0).
Follow-up questions
Follow-up 1: What are the pros and cons of self-attention compared with an RNN?
The pros are parallelism and easily learned long-range dependencies; the con is quadratic complexity. Any two positions interact in one step, and all positions can be computed in parallel; but compute grows quadratically with length, and the KV cache at inference grows linearly with length, whereas an RNN's state has a fixed size. In addition, attention has no built-in sense of order and needs extra positional encoding.
Follow-up 2: Why does a Transformer need positional encoding?
Because attention without a mask is insensitive to order. Attention scores depend only on the content of the query and key, not on their positions; if the input order is shuffled, each token's output stays the same and simply moves with it, which is called permutation equivariance. Without positional information, "dog bites man" and "man bites dog" therefore look the same to the model, so positional encoding must be added (see Chapter 3).
Follow-up 3: Why use three different projection matrices for Q, K and V?
So that attention can be asymmetric, and so that "what to match on" and "what content to pass" are learned separately. If the query and key shared a matrix \(W\), the score matrix \(XW(XW)^\top\) would be symmetric, so "A attends to B" and "B attends to A" would necessarily be equally strong, and each token's score with itself, \(\|x_iW\|^2\), would tend to be the largest; separate projections allow asymmetric scores. A separate value projection lets "matching" and "the content passed after matching" be learned independently.
Common mistakes
- Do not just say "attention is \(O(n^2)\)": The complete statement is \(O(n^2d)\) compute and \(O(n^2)\) memory for the score matrix, with \(O(nd^2)\) for the projections and the FFN.
- Do not say that FlashAttention lowers the computational complexity: It reduces memory traffic and extra memory; the compute is still \(O(n^2d)\).
- Do not say that the softmax is applied over the whole score matrix: It is applied row by row, so each query's weights over all keys sum to 1.
1.2 Why do we scale attention by √d_k? ★★★¶
One-sentence answer
Because the variance of the query–key dot product grows linearly with the dimension \(d_k\); without scaling, the softmax saturates, gradients vanish, and the model becomes difficult to train. Dividing by \(\sqrt{d_k}\) restores the variance to exactly 1.
I will address this in three parts.
(1) The variance of the dot product grows linearly with the dimension.
Scaled dot-product attention is
where \(d_k\) is the dimension of the query and key. Assume that the components of \(q\) and \(k\) are independent, with mean 0 and variance 1. Then \(q\cdot k\) is a sum of \(d_k\) products \(q_i k_i\), each with variance 1, so the total variance is \(d_k\) and the standard deviation is \(\sqrt{d_k}\). For example, with a head dimension of 128, the scores have a standard deviation of about 11, so the scores for different positions differ substantially.
(2) Excessively spread-out scores saturate the softmax, which in turn causes vanishing gradients.
The softmax exponentiates the scores, which amplifies the differences further, so nearly all of the weight concentrates on the highest-scoring position and the output becomes close to one-hot. The softmax is then in its saturated regime: small changes in the input barely change the output, so its gradient with respect to the input is very small. As a result, the gradient cannot propagate back effectively, \(W_Q\) and \(W_K\) receive almost no updates, and the model has difficulty learning which positions to attend to.
(3) Dividing by \(\sqrt{d_k}\) restores the variance to exactly 1.
Since the standard deviation of the dot product is \(\sqrt{d_k}\), dividing by it makes the variance 1, independent of the dimension. Therefore, whether the head dimension is 64 or 128, the softmax inputs remain in a suitable range: discriminative enough, yet not saturated, so gradients propagate back normally.
In summary: dividing by \(\sqrt{d_k}\) is essentially variance normalization, intended to keep attention trainable from initialization. This is precisely the rationale given in the original Transformer paper (Vaswani et al. 2017).
Going deeper: the variance derivation, and why saturation eliminates the gradient
(1) Variance derivation: each term has variance 1, so summing \(d_k\) terms gives variance \(d_k\).
If \(q_i, k_i\) are independent with mean 0 and variance 1, then
After dividing by \(\sqrt{d_k}\), the variance becomes \(d_k / d_k = 1\).
(2) Saturation causes vanishing gradients: the softmax Jacobian approaches the zero matrix near a one-hot output.
Let \(p=\mathrm{softmax}(z)\). The Jacobian of the softmax with respect to \(z\) is
When \(p\approx(1,0,\dots,0)\), \(\mathrm{diag}(p)\) and \(pp^\top\) are nearly identical, so their difference is close to the zero matrix. Consequently, however large the upstream gradient is, it becomes nearly zero after passing through the softmax.
(3) Comparing three scaling choices: only \(\sqrt{d_k}\) makes the variance exactly 1.
| Scaling | Variance of scores | Softmax output | Result |
|---|---|---|---|
| None | \(d_k\) | Nearly one-hot | Vanishing gradients, hard to train |
| Divide by \(\sqrt{d_k}\) | 1 | Discriminative and not saturated | Trains normally |
| Divide by \(d_k\) | \(1/d_k\) | Nearly uniform | Attention cannot focus |
Follow-up questions
Follow-up 1: Why not divide by \(d_k\) instead?
Because that over-scales the scores, and attention loses its ability to focus. Dividing by \(d_k\) reduces the variance to \(1/d_k\), so the scores become too small overall; the softmax output is then close to uniform, and every position receives nearly the same weight. \(\sqrt{d_k}\) is the scaling that makes the variance exactly 1.
Follow-up 2: Does the "independent, unit-variance" assumption hold in actual training?
It holds only approximately near initialization, so \(\sqrt{d_k}\) mainly ensures that training starts properly. The scale of \(q\) and \(k\) changes during training, so the assumption no longer holds exactly, and in large-scale training the attention logits can still keep growing. For this reason, some models (e.g. Qwen3, Gemma 3) additionally use QK-Norm, which normalizes \(q\) and \(k\) before the dot product to further control the magnitude of the logits.
Follow-up 3: How does this relate to the softmax "temperature"?
Dividing by \(\sqrt{d_k}\) is equivalent to setting a fixed softmax temperature \(T=\sqrt{d_k}\). A higher temperature yields a flatter distribution, and a lower temperature yields a sharper one. \(\sqrt{d_k}\) makes the distribution at initialization neither too flat nor too sharp.
Common mistakes
- Do not say it is "to prevent numerical overflow": Softmax overflow is handled by subtracting the maximum first, which is unrelated to \(\sqrt{d_k}\); \(\sqrt{d_k}\) addresses saturation and vanishing gradients.
- The variance is \(d_k\); the standard deviation is \(\sqrt{d_k}\): The two are easily confused.
- The scaling applies to the scores \(QK^\top\) before the softmax: It applies neither to \(V\) nor to the softmax output.
1.3 Why use multi-head attention? ★★¶
One-sentence answer
Because one softmax produces only one set of weights, a single head finds it hard to attend to several different kinds of information at once. Multi-head attention splits the \(d\) dimensions into \(h\) heads of \(d/h\) dimensions, each with its own projections that decide independently where to look, then concatenates the heads' outputs and mixes them with \(W_O\); the parameter count and compute are essentially the same as one large head, and what increases is the diversity of what can be expressed.
I will address three aspects: the limitation of a single head, how multi-head attention works, and its cost and redundancy.
(1) A single head produces only one set of weights, so different kinds of information get mixed together.
Suppose a token needs two kinds of information at once, say the subject of the sentence and the previous word. A single head can only split its attention between these two positions and average their values by weight, so the two kinds of information are blended into one vector that later layers find hard to separate. Moreover, the softmax tends to concentrate weight on a few positions, so a single head can hardly serve several relations at the same time.
(2) Multi-head attention runs several low-dimensional heads in parallel, each deciding where to look.
Multi-head attention splits the \(d\) dimensions into \(h\) heads, each of dimension \(d_h=d/h\) and with its own \(W_Q^{(i)}, W_K^{(i)}, W_V^{(i)}\), computing attention independently in its own subspace; the outputs of all heads are concatenated and then mixed by \(W_O\) (the formula is in "Going deeper" below). Research has found that different heads do specialize: some track syntactic relations, some attend to the previous word, and some find what a pronoun refers to; there are also induction heads, which find an earlier occurrence of the same pattern and copy what came after it, and are considered one of the important mechanisms behind in-context learning (Olsson et al. 2022).
(3) Multiple heads add almost no cost, but the heads are redundant.
Because each head has dimension \(d/h\), \(W_Q, W_K, W_V, W_O\) still total \(4d^2\) parameters, and the matrix-multiplication compute is the same as a single head of width \(d\); the only change is from "one set of weights" to "\(h\) sets of weights". However, the heads are quite redundant: Michel et al. (2019) found that a substantial fraction of heads can be pruned after training with little loss in quality. Still, this redundancy may help optimization during training, so the number of heads is usually not reduced at training time.
In summary: multi-head attention turns one set of attention weights into several without adding parameters or compute, letting the model attend to different positions and different kinds of information at the same time.
Going deeper: the formula, the choice of head dimension, and the relation to GQA
(1) The formula of multi-head attention.
Here \(W_Q^{(i)}, W_K^{(i)}, W_V^{(i)}\in\mathbb{R}^{d\times d_h}\) are the projection matrices of head \(i\), and \(W_O\in\mathbb{R}^{d\times d}\) mixes the concatenated \(d\)-dimensional vector into the final output. In implementations, the projections of all heads are merged into a single \(d\times d\) matrix computed in one go, and the result is then split into \(h\) parts.
(2) The head dimension is usually 64 or 128 and should not be too small.
Each head's score matrix \(Q_iK_i^\top\) has rank at most \(d_h\). If \(d_h\) is too small, the attention patterns a head can express are limited, which is called the low-rank bottleneck (Bhojanapalli et al. 2020). Therefore, as models get wider, the number of heads is usually increased rather than shrinking each head indefinitely. For example, the original Transformer has \(d=512\), 8 heads and \(d_h=64\); Llama 3 8B has \(d=4096\), 32 heads and \(d_h=128\).
(3) Multi-head attention is the starting point for variants such as MQA, GQA and MLA.
At inference, every head caches its own keys and values, so the KV cache grows with the number of heads. MQA and GQA let several query heads share key/value heads, and MLA compresses the keys and values into low-dimensional vectors; all of them reduce the KV cache on top of multi-head attention (see Chapter 2).
Follow-up questions
Follow-up 1: Are all heads useful?
No, the heads are clearly redundant. Michel et al. (2019) found that many layers can be reduced to a single head at test time with almost no change in quality; Voita et al. (2019) found that a few "specialized" heads do most of the work and the rest can be pruned. This suggests that the value of multiple heads lies more in optimization and diversity during training.
Follow-up 2: Are more heads always better?
No. With \(d\) fixed, more heads mean a smaller dimension per head, which runs into the low-rank bottleneck; too few heads mean insufficient diversity. In practice, \(d_h\) is usually fixed at 64 or 128 first, and the number of heads is then set to \(d/d_h\).
Follow-up 3: Why multiply by \(W_O\) after concatenating the heads' outputs?
Because concatenation merely places the heads' results side by side, and \(W_O\) is what mixes them. Without \(W_O\), each head's output could only be written to a fixed set of \(d_h\) dimensions of the residual stream; with \(W_O\), each head's information can be written in any direction, and the results of different heads can be combined.
Common mistakes
- Do not say that multi-head attention adds parameters or compute: With \(d_h=d/h\), the parameter count is still \(4d^2\) and the compute equals that of a single head.
- Do not say that each head sees only a different segment of the input sequence: Every head sees the whole sequence; the heads differ in the subspaces they project into.
- Do not confuse multi-head attention with GQA: In standard multi-head attention every query head has its own K and V, whereas GQA lets several query heads share K and V.
1.4 What is the causal mask, and why can decoder-only models be trained in parallel? ★★¶
One-sentence answer
The causal mask sets the scores of all "future positions" to \(-\infty\) before the softmax, so each token can see only itself and earlier tokens. During training the full sequence is known, and with the causal mask the output at position \(i\) depends only on the first \(i\) tokens, exactly as at inference, so a single forward pass yields the predictions at all positions and their loss at once, i.e. teacher forcing; during generation, however, each token can be computed only after the previous one has been produced, so generation is sequential.
I will address three aspects: what the causal mask is, why training can be parallel, and why generation must be sequential.
(1) The causal mask lets each position see only itself and earlier positions.
When a language model generates token \(i\), it may rely only on the preceding text and must not see the answers that come later. The causal mask is a matrix \(M\) with \(M_{ij}=0\) when \(j\le i\) and \(M_{ij}=-\infty\) when \(j>i\). It is added to the score matrix before the softmax, so the scores of future positions become \(-\infty\) and their weights become exactly 0 after the softmax; each position's output is therefore determined only by itself and earlier tokens.
(2) During training the full sequence is known, and the causal mask ensures that all positions can be computed in parallel in one forward pass.
During training we feed the whole sequence into the model at once. Because of the causal mask, the output at position \(i\) depends only on the first \(i\) tokens, which is exactly the same computation as predicting token \(i+1\) at inference, so there is no peeking at the answer. A single forward pass therefore yields the predictions at all positions, and each is compared with the true next token to compute the cross-entropy loss; this way of training is called teacher forcing. A sequence of length \(n\) thus provides \(n\) training signals, all computed in parallel as matrix multiplications, which is also why decoder-only models train efficiently (see 0.2 in Chapter 0).
(3) Generation must be sequential, but the same property makes the KV cache possible.
At inference, token \(t+1\) can be computed only after token \(t\) has been sampled and appended to the input, so tokens are generated one at a time. The causal mask, however, also guarantees that past tokens never see later tokens, so their keys and values never change during generation; they can therefore be cached and reused, and each step only computes Q, K and V for the new token. This is the KV cache (details in Chapter 1 of the Inference, Evaluation & Deployment direction).
In summary: the causal mask makes the conditions at every position during training identical to those at inference, so training can be parallel; the same property keeps the K and V of past tokens unchanged, which makes the KV cache possible.
Going deeper: implementing the mask, padding masks and sequence packing, and the computational shape of training and inference
(1) The mask is added before the softmax, rather than zeroing weights after it.
After adding \(M\) to \(QK^\top/\sqrt{d_k}\) and applying the softmax, the masked positions get weight \(e^{-\infty}=0\), and the remaining weights still sum to 1. If the weights were zeroed after the softmax instead, the remaining weights would no longer sum to 1. Implementations usually replace \(-\infty\) with a very large negative number; efficient implementations such as FlashAttention skip fully masked blocks altogether, saving about half of the computation.
(2) The padding mask and the causal mask serve different purposes.
When sequences of different lengths are batched together, padding is added, and the padding mask blocks these meaningless positions so that they are neither attended to nor counted in the loss. A more common practice in pretraining is sequence packing, which concatenates several documents into fixed-length sequences; a document-level mask can then be added so that each token attends only to earlier text within the same document (Llama 3 does this; Dubey et al. 2024).
(3) Training and inference have different computational shapes.
| Training | Prefill stage of inference | Decode stage of inference | |
|---|---|---|---|
| Tokens processed per step | The whole sequence | The whole prompt | 1 new token |
| Parallel or not | All positions in parallel | All positions in parallel | One at a time |
| Main operation | Matrix × matrix | Matrix × matrix | Matrix × vector |
Follow-up questions
Follow-up 1: What is the problem with teacher forcing?
Mainly the mismatch between the input distributions at training and at inference, known as exposure bias. During training, the preceding text at every position is real text; at inference, the preceding text is generated by the model itself, so once an early mistake occurs, the model is in a state it never saw during training, and errors can accumulate. This problem is not prominent in large-scale LLMs; RL and on-policy distillation in post-training train directly on the model's own generated sequences, which also mitigates it to some extent (see Chapter 9 of the LLM Training Pipeline direction).
Follow-up 2: Does the causal mask itself provide positional information?
Partly. Under the causal mask, position \(i\) sees exactly \(i\) tokens, which the model can use to infer where it is; decoder-only models without positional encoding (NoPE) can therefore still learn positional information (Haviv et al. 2022). Mainstream models nevertheless still use RoPE (see Chapter 3).
Follow-up 3: In an encoder-decoder model, which attention in the decoder needs a causal mask?
Only the decoder's self-attention. The decoder's self-attention must not see outputs that have not been generated yet, so it needs a causal mask; cross-attention queries the encoder's representation of the complete input, which is fully given before generation starts, so it needs no causal mask, only padding masking.
Common mistakes
- Do not say that the causal mask zeroes the weights after the softmax: It sets the scores to \(-\infty\) before the softmax, so the remaining weights still sum to 1.
- Do not say that training is sequential just like inference: During training all positions are computed in parallel; only generation is sequential.
- Do not say that a bidirectional encoder can use a KV cache the way a decoder does: Only under causal attention do the K and V of past tokens stay unchanged when new tokens are added.
1.5 What role does the FFN play in a Transformer? ★¶
One-sentence answer
The FFN is a two-layer MLP applied to each token separately: it expands the dimension from \(d\) to \(4d\), applies a nonlinear activation, and projects back to \(d\). Attention moves information between positions, while the FFN processes each position nonlinearly; it holds about two-thirds of each layer's parameters and is believed to store much of the model's knowledge.
I will address three aspects: the structure of the FFN, its division of labor with attention, and its role as knowledge storage.
(1) The FFN is a per-token two-layer MLP whose inner layer is usually \(4d\) wide.
Here \(x\in\mathbb{R}^d\) is the vector of one token, \(W_1\in\mathbb{R}^{4d\times d}\) expands it to \(4d\) dimensions, \(\sigma\) is a nonlinear activation function (ReLU in the original Transformer, GELU in GPT and BERT), and \(W_2\in\mathbb{R}^{d\times4d}\) projects it back to \(d\) dimensions. Every token passes independently through the same FFN, with no interaction between tokens. The two matrices have \(8d^2\) parameters in total, about two-thirds of each layer's \(12d^2\).
(2) Attention handles communication between tokens, and the FFN handles computation within a token.
Attention is essentially a weighted average: given the attention weights, its output is just a linear combination of the values, which cannot transform a single token's information in complex ways. With attention alone, the model would lack the ability to process each position deeply. The FFN fills exactly this gap: after attention brings the relevant information to the current position, the FFN processes it nonlinearly and extracts higher-level features. Only by stacking the two alternately can the model both integrate context and perform complex computation on the integrated information.
(3) The FFN stores a great deal of knowledge and can be viewed as a key–value memory.
Geva et al. (2020) proposed viewing the FFN as a key–value memory: each row of \(W_1\) acts like a key that detects whether a certain pattern appears in the input; when it does, the corresponding activation becomes large, and the matching column of \(W_2\) (the value) is added to the output, often raising the probability of certain words. Later work (such as ROME, Meng et al. 2022) traced the flow of information inside the model and found that factual knowledge (such as "Paris is the capital of France") is stored mainly in mid-layer FFNs, and that editing these weights changes the facts the model remembers. The inner width \(4d\) can be understood as the number of "memory slots": the wider it is, the more patterns can be stored.
In summary: the FFN is a per-token nonlinear transformation and a store of knowledge, complementary to attention, which handles communication between tokens; this is also why MoE sparsifies the FFN to expand capacity.
Going deeper: why 4×, the relation between the FFN and MoE, and knowledge neurons
(1) 4× is an empirical convention, not a theoretical optimum.
In the original Transformer \(d=512\) and the FFN inner dimension is 2048, and GPT-2, GPT-3 and others kept the 4× ratio. Kaplan et al. (2020) found that, for a fixed non-embedding parameter count, the loss is insensitive to shape parameters such as the ratio of FFN width to \(d\), differing by only a few percent over a wide range. The 4× ratio is therefore largely a convention, and individual models adjust around it; a practical benefit is that the resulting large matrix multiplications run very efficiently on GPUs.
(2) The FFN is the most natural place to add capacity, so MoE sparsifies the FFN.
Since knowledge is stored mainly in the FFN, and the FFN is computed independently for each token, one can prepare multiple FFNs (experts) and have a router select only a few of them for each token. The total parameters (capacity) then increase greatly while the compute per token stays roughly the same (see Chapter 5).
(3) Evidence from "knowledge neurons".
Dai et al. (2021) found that certain neurons in the FFN inner layer are strongly associated with specific facts: suppressing them lowers the probability that the model states the fact, and amplifying them raises it. This corroborates the key–value memory interpretation.
Follow-up questions
Follow-up 1: Why do we need an FFN when we already have attention?
Because attention mainly mixes information by weighted averaging and lacks a per-token nonlinear transformation. Given the attention weights, attention's output is just a linear combination of the values; the nonlinear activation in the FFN is what lets the model process each position's information in complex ways. Dong et al. (2021) proved that in a pure attention network without residual connections and FFNs, the output rapidly degenerates with depth into a rank-1 matrix, i.e. all token representations become the same.
Follow-up 2: Where is the model's factual knowledge mainly stored?
Mainly in mid-layer FFNs. Using causal tracing (corrupting the input, then restoring intermediate activations one at a time to see which contributes most to recovering the correct output), ROME found that factual recall relies mainly on the mid-layer FFN computation at the last token of the subject, and that editing these weights can change a specific fact. Knowledge storage is nonetheless distributed, and attention also takes part in extracting and moving information.
Follow-up 3: Why does the FFN first expand the dimension and then project it back?
Expanding lets the nonlinear activation act in a higher-dimensional space, so more patterns can be represented. In the \(4d\)-dimensional inner layer, each dimension can be seen as a pattern detector, and the activation function decides which patterns "light up"; the higher the dimension, the more patterns can be detected. Projecting back to \(d\) keeps the output the same size as the residual stream, so it can be added layer by layer.
Common mistakes
- Do not say that the FFN exchanges information between tokens: The FFN computes each token independently; interaction between tokens happens only in attention.
- Do not say that attention holds most of the parameters: With 4× width, the FFN holds about two-thirds of each layer's parameters.
- Do not say that the 4× width is theoretically derived: It is an empirical choice, and quality differs little over a fairly wide range.
1.6 What do residual connections and normalization do? How do LayerNorm, BatchNorm and RMSNorm differ? ★★¶
One-sentence answer
Residual connections give gradients a path straight back through the network, so even networks with hundreds of layers can be trained; normalization brings each layer's input back into a stable numerical range. BatchNorm computes the mean and variance of each feature over the whole batch, whereas LayerNorm computes them for each token over its own \(d\) features, independent of the batch, which suits variable-length sequences and token-by-token generation; RMSNorm further drops the mean subtraction and only divides by the root mean square, which is cheaper with equal quality, and is the default in modern LLMs.
I will address three aspects: the role of residual connections, the role of normalization and the difference between LayerNorm and BatchNorm, and finally RMSNorm.
(1) Residual connections provide a direct path for gradients, so very deep networks can be trained.
A residual connection adds a sublayer's input directly to its output, i.e. \(x_{l+1}=x_l+F_l(x_l)\), where \(x_l\) is the input to layer \(l\) and \(F_l\) is that layer's sublayer (attention or FFN). Differentiating gives \(\partial x_{l+1}/\partial x_l = I + \partial F_l/\partial x_l\), so every layer's derivative gains an identity matrix \(I\). The main reason deep networks are hard to train is that gradients are multiplied layer by layer during backpropagation and easily become tiny; with this \(I\), whatever \(F_l\) learns, the gradient always has a path back that it can travel unchanged, so even networks with hundreds of layers can be trained (He et al. 2015). In addition, each layer only needs to learn a small change to the existing representation rather than build a new one from scratch, which makes learning easier.
(2) Normalization stabilizes the numerical range; LayerNorm does not depend on the batch, so it suits language models better than BatchNorm.
Normalization brings each layer's input back to around mean 0 and variance 1, making training smoother. The two differ in the dimension over which the statistics are computed: BatchNorm (Ioffe & Szegedy 2015) normalizes each feature using statistics across all samples in the batch, whereas LayerNorm (Ba et al. 2016) normalizes each token using its own \(d\) features. BatchNorm's reliance on batch statistics causes three problems in language models.
- Sequences have different lengths: forming a batch requires padding, and the padding positions distort the statistics.
- Batch statistics are noisy: large models are memory-constrained, so the batch on each GPU is often small, and text features fluctuate greatly across samples, so the estimated mean and variance are very unstable.
- Training and inference are inconsistent: BatchNorm uses the current batch's statistics during training but running averages accumulated during training at inference; and a language model generates one token at a time, so the two situations differ greatly.
LayerNorm looks only at a single token's own features, so it behaves identically at training and inference, and none of these problems arise.
(3) RMSNorm drops the mean subtraction and only rescales, which is cheaper with equal quality.
RMSNorm (Zhang & Sennrich 2019) neither subtracts the mean nor uses the shift \(\beta\); it simply divides the vector by its root mean square and multiplies by a learnable scale \(\gamma\). The authors argue that what really matters in LayerNorm is mainly the rescaling, i.e. bringing the scale of the values back into a stable range, while the mean subtraction contributes little. Dropping that step saves one averaging operation and the associated arithmetic, so it is faster, yet its quality matches LayerNorm. Since each layer normalizes twice, the savings add up, which is why models such as Llama, Qwen and DeepSeek use RMSNorm.
In summary: residual connections keep gradients flowing, and normalization keeps values stable; language models choose LayerNorm over BatchNorm because it does not depend on the batch, and RMSNorm is a cheaper LayerNorm.
Comparing the three normalizations:
| BatchNorm | LayerNorm | RMSNorm | |
|---|---|---|---|
| Statistics computed over | One feature across the whole batch | The \(d\) features of one token | The \(d\) features of one token |
| Subtracts the mean | Yes | Yes | No |
| Learnable parameters | \(\gamma\) and \(\beta\) | \(\gamma\) and \(\beta\) | \(\gamma\) only |
| Same at training and inference | No (running averages at inference) | Yes | Yes |
| Typical use | CNNs (e.g. ResNet) | Original Transformer, BERT, GPT-2/3 | Llama, Qwen, DeepSeek |
Going deeper: the formulas, the direction of BatchNorm's statistics, and the residual-stream view
(1) The formulas of LayerNorm and RMSNorm.
Here \(x\in\mathbb{R}^d\) is one token's vector, \(\mu\) and \(\sigma^2\) are the mean and variance of its \(d\) components, \(\epsilon\) is a small constant that prevents division by zero, \(\gamma\) and \(\beta\) are the learnable per-dimension scale and shift, and \(\odot\) denotes element-wise multiplication. When \(x\) happens to have zero mean, RMSNorm is identical to LayerNorm without \(\beta\).
(2) The direction of BatchNorm's statistics.
For activations of shape \(B\times n\times d\) (\(B\) the batch size, \(n\) the sequence length), BatchNorm computes the mean and variance of each feature dimension over the \(B\times n\) positions, whereas LayerNorm and RMSNorm compute them for each position over the \(d\) features. Shen et al. (2020) found that in NLP tasks the batch statistics fluctuate far more during training than in CV tasks, which is the direct reason BatchNorm performs poorly in Transformers.
(3) Normalization from the residual-stream view.
With residual connections, each token's vector runs from the bottom of the network to the top; each sublayer reads it, computes an update, and adds the update back. In the Pre-LN structure, normalization acts only on the sublayer's input and does not change the residual stream itself, which is what distinguishes Pre-LN from Post-LN (see 1.7).
Follow-up questions
Follow-up 1: Why does BatchNorm work well in CV but not in NLP?
Because batch statistics are stable for images, whereas text does not satisfy this condition. Images have a fixed input size, batches are usually large, and the statistics of a channel are relatively stable across samples; text varies in length, requires padding, and has feature distributions that fluctuate greatly across samples, and inference often proceeds token by token, so none of the premises BatchNorm relies on hold.
Follow-up 2: Why does RMSNorm not perform worse despite dropping the mean subtraction?
Because the key to stabilizing training through normalization is controlling the scale, not moving the mean to 0. Zhang & Sennrich (2019) showed experimentally that RMSNorm, which only rescales, matches LayerNorm while saving compute. Intuitively, the subsequent linear layers can absorb shifts in the mean on their own.
Follow-up 3: Besides mitigating vanishing gradients, what else do residual connections do?
They make the network behave more like an ensemble of many shallow networks, and they turn each layer's learning into an "incremental update". Veit et al. (2016) found that a residual network can be seen as an ensemble of many paths of different depths, and that deleting a single layer has little effect on quality. In a Transformer, the residual stream also lets different layers cooperate by reading from and writing to the same vector.
Common mistakes
- Do not say that LayerNorm normalizes over the batch dimension: It normalizes over each token's own feature dimension.
- Do not say that RMSNorm has no learnable parameters: It keeps the scale \(\gamma\); what it drops is the shift \(\beta\).
- Do not say that residual connections exist only to speed up convergence: Their core role is to provide a direct path for gradients so that deep networks can be trained.
1.7 What is the difference between Pre-LN and Post-LN, and why do modern LLMs use Pre-LN? ★★¶
One-sentence answer
The difference is where the normalization sits: Post-LN normalizes after the residual addition, so the normalization lies on the main residual path; Pre-LN normalizes before each sublayer, so the main path contains only additions. With Post-LN, gradients near the output are very large early in training, so it depends on warmup and becomes less stable as layers are added; with Pre-LN, gradients flow straight back along the residual path, so training is stable and the network can be very deep. Modern LLMs therefore almost all use Pre-LN, at the possible cost of weakening the contribution of deep layers.
I will address three aspects: the structural difference, why Post-LN is unstable, and the advantages and costs of Pre-LN.
(1) The difference is whether the normalization sits on the main residual path or inside the residual branch.
Here \(x_l\) is the input to layer \(l\), \(F\) is the sublayer (attention or FFN), and \(\mathrm{LN}\) is the normalization. The original Transformer and BERT use Post-LN: the sublayer output is first added to the residual and then normalized, so the normalization lies on the main residual path. Models since GPT-2 generally use Pre-LN: the normalization is placed before the sublayer, inside the residual branch, and only plain additions remain on the main path.
(2) In Post-LN, gradients must pass through every layer's normalization, so training is unstable early on and must rely on warmup.
In Post-LN, gradients flowing back from the output to earlier layers must pass through each layer's LayerNorm in turn, which breaks the direct path that the residual connection provides. The analysis of Xiong et al. (2020) shows that with Post-LN, the gradients of parameters near the output layer are large at initialization; if training starts with a normal learning rate, parameter updates are too large and training easily diverges. Post-LN therefore requires a learning-rate warmup, starting with a very small learning rate and raising it gradually, and the more layers there are, the worse the problem becomes.
(3) In Pre-LN, the main path contains only additions, so training is stable, but the contribution of deep layers may be weakened.
In Pre-LN, gradients can travel along the main residual path straight to every layer without interference from normalization, so training is much more stable, less sensitive to warmup, and able to go very deep. Because the main path is never normalized, Pre-LN needs an additional normalization layer after the last block to bring the values back into a normal range before the LM head. Pre-LN has a cost, however: every layer adds content to the residual stream without normalizing it, so the scale of the stream grows with depth; as a result, the updates contributed by later layers are relatively small, the contribution of deep layers is weakened, and the "effective depth" shrinks. Sun et al. (2025) found that the outputs of deep layers in Pre-LN models are highly similar to those of adjacent layers, and that removing these layers causes little loss in quality.
In summary: Pre-LN trades a possible loss of some effective depth for stability in large-scale training; for LLMs with dozens of layers and hundreds of billions of parameters, stability matters more, so Pre-LN (usually with RMSNorm) has become the standard choice.
Comparing the two structures:
| Post-LN | Pre-LN | |
|---|---|---|
| Position of the normalization | After the residual addition, on the main path | Before the sublayer, inside the residual branch |
| Gradient flow | Passes through every layer's normalization; large near the output early in training | Flows straight back along the residual path |
| Dependence on warmup | Required | Weak |
| Deep models | Unstable | Stable |
| Final quality | Often slightly better if training succeeds | Effective depth may shrink |
| Needs an extra final normalization | No | Yes |
| Representative models | Original Transformer, BERT | GPT-2/3, Llama, Qwen, DeepSeek |
Going deeper: the conclusions of the gradient analysis, and ways to mitigate deep-layer degradation in Pre-LN
(1) The conclusion of Xiong et al.: in Post-LN the gradient near the output does not depend on depth, whereas in Pre-LN it shrinks with depth.
Xiong et al. (2020) analyzed the gradients at initialization: in Post-LN, the gradient of the last layer's parameters does not depend on the number of layers \(L\) and is large, so training must start with a very small learning rate; in Pre-LN, this gradient shrinks as \(1/\sqrt{L}\), and the gradients across layers are smoother, so warmup can be removed or shortened.
(2) Another problem of Post-LN: excessive dependence on the residual branch.
Liu et al. (2020) found that in Post-LN each layer's output depends heavily on its own sublayer, so small parameter changes are amplified layer by layer, making training unstable. This explains from another angle why Post-LN is hard to train.
(3) Ways to mitigate deep-layer degradation in Pre-LN.
Sun et al. (2025) proposed LayerNorm Scaling, which multiplies the output of layer \(l\)'s normalization by \(1/\sqrt{l}\) to curb the growth of the residual stream's variance with depth. There are also compromise schemes (such as DeepNorm, Sandwich-LN, or additionally normalizing the sublayer output as in Gemma 2 and OLMo 2) that try to balance stability against the contribution of deep layers.
Follow-up questions
Follow-up 1: Why does Post-LN need warmup?
Because the gradients near the output layer are very large early in training, and a normal learning rate would make updates too large and cause divergence. Warmup starts with a very small learning rate and raises it to the target only after the gradients and Adam's second-moment estimates have stabilized. Pre-LN depends on warmup much less, but in practice LLM training still uses a short warmup to stabilize Adam's early statistics.
Follow-up 2: Why does Pre-LN need a normalization layer at the end?
Because the main residual path in Pre-LN is never normalized. Each layer's updates keep accumulating in the residual stream, so by the last layer the scale of the values may be very large, and feeding them directly to the LM head would make the logits unstable. The final normalization brings them back into a normal range. In Post-LN every layer's output is already normalized, so no extra layer is needed.
Follow-up 3: If Post-LN may give better quality, why not find a way to stabilize it?
People have tried, but in large-scale LLMs the risk of training divergence matters far more than a small difference in quality. Some methods adjust the residual scaling and initialization so that Post-LN can also train very deep networks stably (e.g. DeepNorm); but a single LLM pretraining run is extremely expensive and divergence is very costly, whereas Pre-LN with RMSNorm is simple, robust and repeatedly validated at scale, so it has become the default.
Common mistakes
- Do not say that Pre-LN is better than Post-LN in every respect: If Post-LN trains successfully, its final quality is often slightly better; Pre-LN wins on stability.
- Do not say that Pre-LN needs no warmup at all: It depends on warmup much less, but in practice a short warmup is still common.
- Do not forget Pre-LN's final normalization layer: It is a necessary part of the Pre-LN structure.