Skip to content

Chapter 1 · Transformer Architecture


1.1 Overall Structure and Architecture Families ★★

Three architecture families

Encoder-only Encoder-Decoder Decoder-only
Attention Bidirectional: every token sees the whole input Encoder is bidirectional; decoder is causal and reads the encoder through cross-attention Causal: each token sees only itself and earlier tokens
Pretraining objective Masked language modeling (predict masked tokens) Seq2seq / span corruption (generate the target from the input) Next-token prediction
Typical models BERT, RoBERTa Original Transformer (2017), T5, BART GPT series, Llama, Qwen, DeepSeek
Good at Understanding: classification, embeddings, retrieval, reranking Tasks with a clear input → output: translation, summarization Open-ended generation, chat, general-purpose LLMs

The Transformer was first designed (2017) for machine translation, using an encoder-decoder structure. It later split into three families. All three use the same attention and FFN modules; the real difference is which tokens each token is allowed to see (that is, the attention mask), and this in turn decides their training objective and what they are good at.

In an encoder-only model (e.g. BERT), every token can see all tokens on both its left and right; this is bidirectional attention. Because it sees the full context, it understands text most thoroughly, which makes it a great fit for "understanding" tasks such as classification, text embeddings, retrieval and reranking. It is trained with masked language modeling (MLM): about 15% of tokens are hidden at random, and the model has to recover them from the context on both sides. But precisely because it always sees "what comes later" during training, it can't naturally generate text one token at a time from left to right.

An encoder-decoder model (e.g. the original Transformer, T5, BART) has two parts. The encoder reads the whole input with bidirectional attention and builds a representation of it; the decoder generates the output token by token with causal attention, and uses cross-attention to look up the encoder's representation whenever it needs to. This "understand first, then generate" split works well when input and output are clearly separate, as in translation (an English sentence in, a Chinese sentence out) and summarization.

A decoder-only model (e.g. GPT, Llama, Qwen, DeepSeek) keeps only the decoder and drops cross-attention. Each token can see only itself and earlier tokens (causal attention), and the training objective is simply to predict the next token. The input (prompt) and the output live in the same sequence: the model reads the prompt and then keeps writing. Almost all general-purpose LLMs today use this structure.

Interview questions

  • ★★ How do encoder-only, encoder-decoder and decoder-only models differ, and what are typical models?
  • ★ Can BERT generate text?

    Not well. During training every position in BERT sees context on both sides, so it learns "fill in the blank from both sides", not "continue from what came before". Forcing it to generate left to right doesn't match its training conditions, so the results are poor.

Inside a decoder-only LLM

tokens → Embedding → [ Decoder Block ] × L → Final Norm → LM Head → softmax → p(next token)

Decoder Block (Pre-LN):
  x → Norm → Causal Self-Attention → (+x) → Norm → FFN → (+) → output
\[h = x + \mathrm{Attn}(\mathrm{Norm}(x)), \qquad y = h + \mathrm{FFN}(\mathrm{Norm}(h))\]

Here is how a decoder-only model computes: the text is split into tokens, and each token looks up a \(d\)-dimensional vector in the embedding table. These vectors pass through \(L\) identical blocks, then a final normalization, and the LM head maps each position's vector to a score (logit) for every word in the vocabulary (small models often share this matrix with the embedding, i.e. weight tying). A softmax over the last position's scores gives the probability distribution of the next token.

Each block has two sublayers with different jobs. Attention moves information between positions: for example, when the model reads the pronoun "it", it has to find the noun it refers to earlier in the text, and only attention can do that. The FFN then processes each position on its own with a nonlinear transformation, working further on the information that was just brought in. Both sublayers have a normalization in front and a residual connection around them, so even very deep networks train stably (see 1.7).

A very useful way to picture this is the residual stream. Imagine each token has a stream of information running from the bottom of the network to the top. Each sublayer reads the current information from the stream, computes an update, and adds that update back. So attention is "communication between tokens", the FFN is "computation within a token", and the whole network accumulates information on this stream layer by layer.

Interview questions

  • ★ Walk through how a decoder-only LLM goes from input to output.

Why decoder-only became mainstream ★★

  1. More efficient training. With next-token prediction, every position in the sequence predicts its next token, so a 1,000-token text gives about 1,000 training signals. BERT's MLM only masks about 15%, so the same text gives only about 150. With the same data and compute, a decoder-only model learns more.
  2. One format covers every task. Since input and output live in the same sequence, any task can be written as "here is a prompt, keep writing". QA, translation and coding all use the same model and the same interface, with no task-specific input/output design. This format is also exactly what lets a model learn a new task from a few examples in the prompt, i.e. in-context learning.
  3. Cheaper inference. With causal attention, newly added tokens never change the computation for earlier tokens, so the KV cache computed so far can be reused, and in a multi-turn chat only the new part needs processing. A bidirectional encoder can't do this: once a new token is added, every position can see it, every representation changes, and everything has to be recomputed.
  4. It scaled best in practice. Wang et al. (2022) found in controlled experiments that with self-supervised pretraining only, decoder-only models have the strongest zero-shot ability. After GPT-3, scaling laws, training frameworks and inference engines were all built around decoder-only models, and the growing investment made them even stronger, a positive feedback loop. (There is also an intuitive argument: a causal attention matrix is lower-triangular with a positive diagonal, so it is always full-rank and its expressiveness isn't limited by low rank. But this is only an intuition, not an established result.)

Encoder-only models have not disappeared, though. For text embeddings and rerankers, we need the model to see the context on both sides of a text and produce a result in one forward pass, which is exactly what a bidirectional encoder is good at. (In between there is also the prefix LM, which uses bidirectional attention over the prompt and causal attention over the generated part.)

Interview questions

  • ★★ Why are almost all LLMs decoder-only?
  • ★ Are encoder-only models still useful?

1.2 Scaled Dot-Product Attention ★★

\[Q = XW_Q,\quad K = XW_K,\quad V = XW_V, \qquad \mathrm{Attention}(Q, K, V) = \mathrm{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}} + M\right)V\]

Core idea

A word's meaning often depends on context. "Apple" means something completely different in "I ate an apple" and "Apple released a new phone". Attention solves exactly this problem: it lets each token gather the information it needs from other tokens, based on context.

Concretely, the input \(X \in \mathbb{R}^{n \times d}\) goes through three learned linear projections, producing three vectors per token. The query says "what information am I looking for", the key says "what information do I have", and the value is "what I'll pass to you if you attend to me". The computation has four steps:

  1. Take the dot product of the query with every key; a larger dot product means the two are more relevant.
  2. Divide by \(\sqrt{d_k}\) to control the size of the scores (the reason is in the next subsection).
  3. Apply softmax to turn the scores into weights that sum to 1.
  4. Use these weights to take a weighted average of all values; that's the token's output.

\(M\) is the mask, which blocks positions the token shouldn't see (see 1.3).

The biggest difference from convolutions and RNNs is that the attention weights aren't fixed parameters: they are computed from the current input, so the same token attends to different positions in different sentences. Also, any two positions interact directly in a single step, whereas in an RNN information has to pass step by step through every position in between. That's why Transformers find long-range dependencies easier to learn and can be trained in parallel.

Interview questions

  • ★★ Explain self-attention. What are Q, K and V?
  • ★ What are the pros and cons of self-attention compared with an RNN?

    The pros: any two positions interact directly in one step, so long-range dependencies are easier to learn, and all positions can be computed in parallel. The cons: compute grows quadratically with length (see "Complexity" below), and attention has no built-in sense of order, so it needs positional encoding.

Why divide by \(\sqrt{d_k}\) ★★

\[q \cdot k = \sum_{i=1}^{d_k} q_i k_i, \qquad \mathrm{Var}(q \cdot k) = d_k \quad (\text{if } q_i, k_i \text{ are i.i.d. with mean 0, variance 1})\]

The problem is that the size of the dot product grows with the dimension. If each dimension of \(q\) and \(k\) is an independent random number with mean 0 and variance 1, the dot product sums \(d_k\) terms, so its variance is \(d_k\). With \(d_k = 128\), for example, the scores have a standard deviation of about 11, so scores for different positions end up far apart.

What happens when the gaps are large? Softmax uses an exponential, which amplifies the gaps even more, so almost all the weight lands on the highest-scoring position and the output is close to one-hot. Softmax is now "saturated": changing the scores a little barely changes the output. Mathematically, the softmax gradient is \(\mathrm{diag}(p) - pp^\top\), which is almost all zeros when \(p\) is nearly one-hot. So gradients can't flow back to \(W_Q\) and \(W_K\), and the model struggles to learn where to attend.

Dividing by \(\sqrt{d_k}\) brings the variance back to 1, whatever the head dimension. Softmax stays in a "soft" regime, and gradients flow normally. (Dividing by \(d_k\) instead would make the variance \(1/d_k\): scores would be too small, softmax would be nearly uniform, and attention couldn't focus.)

Interview questions

  • ★★ Why divide the attention scores by \(\sqrt{d_k}\)?
  • ★ Why not divide by \(d_k\) instead?

Complexity ★★

Part FLOPs Memory
\(QK^\top\) and multiplying by \(V\) \(O(n^2 d)\) \(O(n^2)\) per head (score matrix)
Q/K/V/O projections and FFN \(O(n d^2)\) \(O(nd)\)

Why quadratic? In a sequence of length \(n\), every token computes a score with all \(n\) tokens, so the score matrix is \(n \times n\), and each entry is a \(d\)-dimensional dot product. That gives \(O(n^2 d)\) compute and \(O(n^2)\) memory. In contrast, the projections and the FFN work on each token separately, costing \(O(nd^2)\). So for short sequences the projections and FFN are the main cost; once the sequence is clearly longer than \(d\) (the ratio is about \(n/6d\)), the quadratic attention term becomes the bottleneck. This is the root reason long contexts are expensive.

FlashAttention is a very important optimization, but it doesn't change the complexity. It is fast because the real bottleneck on GPUs is often not compute but memory traffic. A standard implementation writes the \(n \times n\) score matrix to GPU memory (HBM), then reads it back for softmax, which means a huge amount of reading and writing. FlashAttention splits the computation into small blocks and does the scoring, softmax and weighted sum all at once in the GPU's fast on-chip memory (SRAM), never writing the full matrix back. Memory drops to \(O(n)\) and memory traffic drops sharply, so it runs much faster. But the result is exactly the same as standard attention, and the FLOPs are still \(O(n^2 d)\).

To really lower the complexity you have to change attention itself: sliding-window or sparse attention lets each token see only some positions; linear attention and state-space models (such as Mamba) compress the history into a fixed-size state, bringing the cost down to \(O(n)\). The price is losing some ability to recall exact details (see Chapter 6).

Interview questions

  • ★★ What are the time and memory complexity of self-attention, and how can they be reduced?
  • ★ Does FlashAttention change the complexity? Why is it faster?
  • ★ Why hasn't linear attention replaced softmax attention?

Attention has no sense of order ★

Attention scores depend only on the content of \(q\) and \(k\), not on where they sit in the sentence. So if you shuffle the input tokens, each token's output stays the same and simply moves with it; this is called permutation equivariance. In other words, with attention alone, "dog bites man" and "man bites dog" look the same to the model. To let the model know word order, we have to add positional encoding (see Chapter 2). (The causal mask in decoder-only models carries a little position information by itself, since position \(i\) sees exactly \(i\) tokens, so NoPE models without positional encoding can still work, but RoPE remains the standard.)

Interview questions

  • ★ Why does a Transformer need positional encoding?

1.3 Causal Mask and KV Cache ★★

\[M_{ij} = \begin{cases} 0, & j \le i \\ -\infty, & j > i \end{cases}\]

The causal mask makes training parallel

When a language model generates text, token \(i\) may only be predicted from the content before it; it can't peek at later answers. The causal mask sets the scores of all "future positions" to \(-\infty\) before softmax, so their weights become 0 after softmax, and each position sees only itself and earlier tokens.

This design brings a big benefit: training can be parallel. During training the full sentence is known, so we feed the whole sentence in at once. Because of the 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 time, so nothing is cheating. One forward pass therefore gives the predictions for all positions at once, and each is compared with the true next token to compute the loss. This way of training is called teacher forcing.

Generation, however, has to be sequential. At inference time, token \(t+1\) can't be computed until token \(t\) has been sampled and appended to the input, so tokens are produced one at a time.

Interview questions

  • ★ Generation is sequential, so why can training be parallel?

Why the KV cache works

Prefill Decode
Tokens per step The whole prompt at once One token
Main operation Matrix × matrix Matrix × vector
Bottleneck Compute-bound Memory-bandwidth-bound: every step reads all weights and the whole KV cache

During generation, every step makes the new token attend to all previous tokens, so it needs the keys and values of all past tokens. The key point: because of the causal mask, past tokens never see later tokens, so their keys and values never change during generation. Since they don't change, there's no need to recompute them every step; we can store and reuse them. This is the KV cache. With it, each step only computes Q, K and V for the newest token and attends over the cached K and V.

Inference therefore splits into two stages with completely different bottlenecks (see table). Prefill processes the whole prompt at once, with many tokens going through matrix multiplications together, so the GPU's compute units are fully used and the bottleneck is compute. Decode handles only one token per step, so there is very little computation, but every step still has to read all the model weights and the whole KV cache from GPU memory. GPU compute is far faster than memory bandwidth, so most of the time is spent waiting for data to arrive; the bottleneck is memory bandwidth. This is why the size of the KV cache directly affects generation speed, and it is the starting point for the methods in Section 1.5.

Interview questions

  • ★★ What is the KV cache, and why does it work?
  • ★ What are prefill and decode, and why is decode memory-bandwidth-bound?

1.4 Multi-Head Attention ★★

\[\mathrm{head}_i = \mathrm{Attention}\big(XW_Q^{(i)}, XW_K^{(i)}, XW_V^{(i)}\big), \qquad \mathrm{MHA}(X) = \mathrm{Concat}(\mathrm{head}_1, \dots, \mathrm{head}_h)\, W_O\]

Why do we need multiple heads? Because one softmax can give each token only one set of weights. 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 together, so the two kinds of information get blurred. Multi-head attention splits one big attention into \(h\) smaller heads. Each head has its own Q, K and V projections and can decide independently where to look. Finally, the outputs of all heads are concatenated and mixed by \(W_O\).

Research shows that different heads really do specialize: some track grammatical relations, some attend to the previous word, 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; they are considered an important mechanism behind in-context learning.

Multiple heads don't add cost. Each head has dimension \(d_h = d/h\), so \(W_Q, W_K, W_V, W_O\) still total \(4d^2\) parameters, and the compute is the same as one big head of width \(d\). What changes is expressiveness: from "one set of weights" to "\(h\) sets of weights".

In practice heads are quite redundant: many can be pruned after training with little loss (Michel et al. 2019). The redundancy may still help optimization during training, so the number of heads usually isn't reduced at training time. Head dimensions are usually 64 or 128 and shouldn't be too small, because each head's attention score matrix has rank at most \(d_h\); if it's too small, the head can't express complex attention patterns.

Interview questions

  • ★★ Why use multi-head attention? Does it add parameters or compute?
  • ★ Are all heads useful? Why is the head dimension usually 64–128?

1.5 KV-Efficient Attention ★★

\[\text{KV cache per token} = 2 \times L \times n_{kv} \times d_h \times \text{bytes per element}\]

As the previous section explained, the decode stage is limited by memory bandwidth, and every step reads the whole KV cache. So the larger the KV cache, the slower each step; and the more memory it takes, the fewer requests can be served at once (batch size) and the shorter the context that fits. In the formula, the 2 stands for one copy each of K and V, and \(n_{kv}\) is the number of key/value heads. In standard MHA, every query head has its own K/V head, so \(n_{kv} = h\). The common idea behind the three methods below is to cache less K/V.

MQA (Multi-Query Attention, Shazeer 2019) is the most aggressive: all query heads share one K head and one V head, so the KV cache shrinks to \(1/h\). The cost is lower quality. The reason is that all heads are forced to attend over the same keys and values, so they can only differ in how they score, and the diversity of information they extract drops. Training can also be less stable.

GQA (Grouped-Query Attention, Ainslie et al. 2023) is the compromise: the \(h\) query heads are split into \(g\) groups, and each group shares one K/V head. \(g = h\) is MHA and \(g = 1\) is MQA. A typical choice is \(g = 8\): the KV cache is only \(g/h\) of MHA's, yet quality is almost the same, because 8 groups of K/V already keep enough diversity. An already-trained MHA model can also be converted to GQA: initialize each group's K/V head as the average of the heads in that group, then train a bit more with about 5% of the original pretraining compute (called uptraining). GQA is the default in Llama 3, Mistral, Qwen and others.

MLA(Multi-head Latent Attention,DeepSeek-V2)

\[c_t^{KV} = W^{DKV} h_t \in \mathbb{R}^{d_c}, \qquad k_t = W^{UK} c_t^{KV}, \qquad v_t = W^{UV} c_t^{KV}\]

MLA takes a different approach: instead of having heads share K/V, it compresses K and V. Each token's hidden state is first squeezed into a low-dimensional vector \(c_t^{KV}\) (with \(d_c\) much smaller than \(2hd_h\)), and only this vector is cached. When needed, \(W^{UK}\) and \(W^{UV}\) "decompress" it into per-head keys and values.

Even better, the decompression step can be skipped at inference. Since \(q^\top k = q^\top W^{UK} c = (W^{UK\top} q)^\top c\), we can merge \(W^{UK}\) into the query projection ahead of time and let the query take a dot product directly with the compressed vector \(c\); \(W^{UV}\) can likewise be merged into the output matrix \(W_O\) (making this work with RoPE needs an extra trick called decoupled RoPE). So we cache only a small vector and pay no extra decompression cost.

In DeepSeek-V2 (128 heads of 128 dimensions each), each token needs only about 576 cached numbers per layer, versus \(2 \times 128 \times 128 = 32{,}768\) for MHA with the same setup. The paper reports a 93.3% smaller KV cache than DeepSeek 67B, with quality as good as or better than MHA. DeepSeek-V3 and Kimi K2 also use MLA.

Comparison and example

MHA MQA GQA MLA
K/V heads \(h\) 1 \(g\) (\(1 < g < h\)) None; a compressed latent vector
KV cache per token per layer \(2 h d_h\) \(2 d_h\) \(2 g d_h\) \(\approx d_c\) (latent size)
Quality Baseline May drop Close to MHA On par with or better than MHA (reported)
Examples GPT-3, Llama 2 7B PaLM, Falcon-7B Llama 3, Mistral, Qwen DeepSeek-V2/V3, Kimi K2

Example: Llama 3 8B has 32 layers, 8 KV heads of 128 dimensions each, stored in bf16 (2 bytes per number). Plugging into the formula, the KV cache per token is \(2 \times 32 \times 8 \times 128 \times 2 = 128\) KB, so one 8K-token sequence needs 1 GB. If it used MHA (32 KV heads), it would need 4 GB.

Interview questions

  • ★★ Compare MHA, MQA, GQA and MLA.
  • ★★ Estimate the KV cache size of a model (e.g. Llama 3 8B).
  • ★ Can an already-trained MHA model be converted to GQA?
  • ★ Does GQA speed up training?

    Not much. During training many tokens are processed in parallel, so the bottleneck is compute rather than memory reads, and the K/V projections are a small share of total compute. GQA's benefit is mainly at inference.


1.6 Feed-Forward Network ★

\[\mathrm{FFN}(x) = W_2\, \sigma(W_1 x), \qquad W_1 \in \mathbb{R}^{4d \times d},\ W_2 \in \mathbb{R}^{d \times 4d}\]

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\). It has \(8d^2\) parameters, about two-thirds of each block's parameters.

Why do we need an FFN when we already have attention? Because attention is essentially a weighted average: it mixes the values of other positions by their weights, but it doesn't transform the information in complex ways. With attention alone, the model would lack the ability to process each token deeply. The FFN fills this gap: after attention brings in the relevant information, the FFN applies nonlinear processing at each position.

The FFN also stores a lot of knowledge. A common interpretation (Geva et al. 2021) treats 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 matching column of \(W_2\) (the value) is written into the residual stream, often raising the probability of certain output words. Later work (such as ROME) traced information flow inside the model and found that factual knowledge (like "Paris is the capital of France") lives mainly in mid-layer FFNs, and editing those weights changes the facts the model remembers. That's also why MoE (Chapter 4) sparsifies the FFN: it's the most natural place to add model capacity.

Interview questions

  • ★ Why do we need an FFN when we already have attention?
  • ★ Where is the model's factual knowledge mainly stored?

1.7 Residual Connection and Normalization ★★

Residual connection

\[x_{l+1} = x_l + F_l(x_l), \qquad \frac{\partial x_{l+1}}{\partial x_l} = I + \frac{\partial F_l}{\partial x_l}\]

A major reason deep networks are hard to train is vanishing gradients: during backpropagation the gradient is multiplied by each layer's derivative in turn, and after many layers it easily becomes tiny, so early layers barely learn. A residual connection adds the input directly to the output. As the derivative above shows, every layer's derivative gains an identity matrix \(I\). This means that no matter what \(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.

Another benefit is that learning becomes easier. With a residual, a layer doesn't need to build a new representation from scratch; it only needs to learn a small change to the existing one. This is also where the "residual stream" picture comes from.

Interview questions

  • ★ Why are residual connections important?

LayerNorm vs BatchNorm ★★

\[\mathrm{LN}(x) = \gamma \odot \frac{x - \mu}{\sqrt{\sigma^2 + \epsilon}} + \beta \qquad (\mu, \sigma \text{ computed over one token's } d \text{ features})\]

Normalization brings each layer's input back to a stable numeric range so training is smoother. The two kinds differ in which dimension the mean and variance are computed over: BatchNorm normalizes each feature using statistics across all samples in the batch; LayerNorm normalizes each token using its own \(d\) features.

BatchNorm works well for images, but in language models it runs into a series of problems, all rooted in its reliance on batch statistics:

  1. Sentences have different lengths. Padding is added to form a batch, and padding positions distort the statistics.
  2. Batches are small. Large models are memory-hungry, so the batch on each GPU is often small, and the computed mean and variance are noisy.
  3. Training and inference don't match. BatchNorm uses the current batch's statistics in training but switches to running averages at inference, and a language model generates one token at a time, so the two situations differ a lot.

LayerNorm only looks at one token's own features and doesn't depend on other samples in the batch at all, so it behaves exactly the same in training and inference, and none of these problems arise.

Interview questions

  • ★★ Why do Transformers use LayerNorm instead of BatchNorm?

RMSNorm ★

\[\mathrm{RMSNorm}(x) = \gamma \odot \frac{x}{\sqrt{\frac{1}{d}\sum_{i=1}^{d} x_i^2 + \epsilon}}\]

RMSNorm (Zhang & Sennrich 2019) is a simplified LayerNorm: it skips mean subtraction and drops the bias \(\beta\), dividing only by the root mean square. The authors found that what really matters in LayerNorm is mainly re-scaling values into a stable range, while subtracting the mean contributes little. Removing that step saves one averaging operation, so it's faster, yet it works as well as LayerNorm. Normalization runs twice per layer, so the savings add up, which is why Llama, Qwen, Mistral and DeepSeek all switched to RMSNorm.

Interview questions

  • ★ How does RMSNorm differ from LayerNorm?

Pre-LN vs Post-LN ★★

\[\text{Post-LN: } x_{l+1} = \mathrm{LN}\big(x_l + F(x_l)\big) \qquad\qquad \text{Pre-LN: } x_{l+1} = x_l + F\big(\mathrm{LN}(x_l)\big)\]
Post-LN Pre-LN
Where the norm is After the residual add, on the main path Before the sublayer, inside the branch
Gradient flow Passes through every LN; large near the output early in training Clean shortcut along the residual path
Warmup Essential Less critical
Deep models Unstable Stable
Final quality Slightly better when it trains successfully Effective depth shrinks
Used by Transformer (2017), BERT GPT-2/3, Llama, Qwen, DeepSeek

The difference is where the normalization sits. The original Transformer and BERT use Post-LN: add the sublayer output to the residual first, then normalize. As a result, the normalization sits on the main residual path, and gradients flowing back to earlier layers have to pass through the LayerNorm of every layer. Xiong et al. (2020) found that with Post-LN, gradients near the output layer are especially large at the start of training. If you start with a normal learning rate, parameter updates are too big and training easily diverges. So Post-LN needs a learning-rate warmup, starting with a very small learning rate and slowly warming up. And the more layers there are, the worse this gets.

Almost all LLMs now use Pre-LN (since GPT-2): the normalization goes in front of each sublayer, inside the residual branch. The main residual path then contains only plain additions, so gradients can travel along it straight to every layer without being disturbed by layer after layer of LayerNorm. That makes Pre-LN much more stable, less sensitive to warmup, and able to go very deep. Because the main residual path is never normalized, Pre-LN needs one extra normalization layer after the last block to bring the values back to a normal range before the LM head.

Pre-LN has a cost too. Every layer adds something to the residual stream, but nothing normalizes it, so the stream keeps growing as you go deeper. By the last few layers, each layer's update is relatively small compared with the stream, so deep layers have weaker influence and the "effective depth" shrinks. When Post-LN does train successfully, its final quality is often slightly better (hence compromises such as DeepNorm and Sandwich-LN).

Interview questions

  • ★★ What is the difference between Pre-LN and Post-LN, and why do LLMs use Pre-LN?
  • ★ Why does Post-LN need warmup?
  • ★ Why does Pre-LN need a final normalization layer?

1.8 Parameter Count and FLOPs ★★

Component Parameters
Attention: \(W_Q, W_K, W_V, W_O\) \(4d^2\)
FFN: \(2 \times d \times 4d\) \(8d^2\)
Per layer \(\approx 12d^2\)
Whole model \(\approx 12Ld^2 + Vd\) (add another \(Vd\) if the LM head is not shared)
\[\text{Training: } C \approx 6ND, \qquad \text{Inference: } \approx 2N \text{ FLOPs per token}\]

Where the parameter count comes from: attention has four \(d \times d\) matrices (Q, K, V, O), giving \(4d^2\); the FFN expands \(d\) to \(4d\) and back, with two matrices giving \(8d^2\). So each layer has about \(12d^2\), two-thirds in the FFN and one-third in attention. Multiply by the number of layers \(L\) and add the embedding table for a vocabulary of size \(V\), and you have the whole model. A quick check: Llama 2 7B has 32 layers and \(d = 4096\); \(12 \times 32 \times 4096^2 \approx 6.4\)B, plus about 0.26B for the embedding and output layer, which comes to about 6.7B. With GQA only \(W_K\) and \(W_V\) shrink, so attention becomes \(2d^2 + 2d \cdot g d_h\).

How to estimate compute: in the forward pass, every parameter does one multiply and one add for each token, i.e. 2 FLOPs, so the forward pass costs \(2N\) per token. The backward pass computes two kinds of gradients: gradients with respect to activations (to keep propagating backward) and gradients with respect to weights (to update the parameters). Each costs about as much as the forward pass, so the backward pass is about \(4N\). Together, training costs about \(6N\) per token, and training on \(D\) tokens costs \(C \approx 6ND\) in total. For example, Llama 2 7B was trained on 2T tokens, which takes about \(8 \times 10^{22}\) FLOPs. Inference is forward-only, about \(2N\) per generated token.

This estimate counts only the parameter matrix multiplications. Attention scoring and weighted sums add about \(2L \cdot n_{ctx} \cdot d\) forward FLOPs per token (Kaplan et al. 2020), a ratio of about \(n_{ctx}/12d\) to the parameter part. With context and \(d\) both 4096 that's only about 8% extra and can be ignored, but at contexts of hundreds of thousands of tokens it becomes the dominant cost.

Training memory: with mixed precision and Adam, each parameter needs about 16 bytes: 2 bytes each for bf16 weights and gradients, 4 bytes for fp32 master weights (to keep parameter updates precise), and 8 bytes for Adam's first and second moments. A 7B model needs about 112 GB for these alone, before activations, which doesn't fit on one GPU, so ZeRO/FSDP shard these states across GPUs (Chapter 5).

Interview questions

  • ★★ How do you estimate a Transformer's parameter count?
  • ★ How does GQA change the parameter count?
  • ★ How do you estimate training and inference compute?
  • ★ Roughly how much memory does training a 7B model need?

1.9 Other Design Choices in Modern LLMs ★

  • No bias terms. PaLM and Llama remove the biases from linear layers and norms. In a \(d \times d\) linear layer the bias adds only \(d\) parameters, which barely helps capacity, and normalization already handles overall shifts in the values. PaLM also reported more stable training for large models without biases, so most later models followed. (Qwen2 kept a QKV bias; Qwen3 removed it and added QK-Norm.)
  • No dropout in pretraining. Dropout exists to prevent overfitting. But LLM pretraining uses so much data that each token is seen roughly once; the model's problem is "not finishing learning" rather than "memorizing too much", i.e. under-fitting rather than over-fitting. Dropout would only add noise and slow convergence. When finetuning on a small dataset, overfitting becomes a concern again and dropout can help.
  • Parallel blocks (GPT-J, PaLM): \(y = x + \mathrm{Attn}(\mathrm{LN}(x)) + \mathrm{FFN}(\mathrm{LN}(x))\). In a standard block the FFN has to wait for attention to finish; a parallel block lets both read the same input and compute at the same time, so their matrix multiplications can be fused for better hardware utilization. PaLM reported about 15% faster training at large scale, with a slight quality loss for small models.

Interview questions

  • ★ Why do modern LLMs drop bias terms and dropout?

1.10 Original Transformer vs Modern LLM ★★

Component Transformer (2017) Modern LLM (Llama-style) Why it changed
Architecture Encoder-decoder Decoder-only Simpler, one format for all tasks, reusable KV cache
Position encoding Sinusoidal absolute RoPE Encodes relative position, handles long context better (Ch. 2)
Normalization Post-LN, LayerNorm Pre-LN, RMSNorm (+ QK-Norm) Stable training at depth, faster
Attention MHA GQA or MLA Smaller KV cache, faster inference
Bias Yes None Little benefit, more stable at scale
Dropout 0.1 None in pretraining Data seen about once, no overfitting
Sparsity Dense Often MoE (Ch. 4) More capacity without more compute per token

Interview questions

  • ★★ What are the main changes from the original Transformer to modern LLMs, and why?