Contents
Key concepts
Tokenisation and embeddings
Byte-level BPE starts from 256 byte symbols, repeatedly merges the most frequent adjacent pair in a training corpus, and stops at a target vocabulary (Llama 3 uses about 128k tokens); encoding applies the learnt merges in order. Larger vocabularies shorten sequences but enlarge the embedding and output matrices. Tokenisers trained mostly on English can need noticeably more tokens for the same content in other languages or in code, which raises cost and latency and shrinks the effective context window. Token IDs map to learnt embedding vectors that feed the residual stream.
Scaled dot-product attention and its cost
For each head, Q = XW_Q, K = XW_K, V = XW_V, and output = softmax(QKᵀ/√d_k + mask) V, where the causal mask sets future positions to −∞. If query and key components have unit variance, q·k has variance d_k (standard deviation about 11 for d_k = 128), which saturates the softmax and kills gradients; dividing by √d_k restores unit variance. Compute is O(n²d) and a naive implementation stores an n × n score matrix per head; FlashAttention tiles the computation with an online softmax so memory is O(n) and HBM traffic falls, without changing the result.
Multi-head, grouped-query, latent and hybrid attention
Multiple heads let the model attend to different relations in parallel subspaces. Multi-query attention shares a single K and V head across all query heads; grouped-query attention shares each K/V head among a group (for example, 32 query heads and 8 KV heads), cutting KV-cache memory and decode bandwidth 4× with little quality loss, and can be uptrained from a multi-head checkpoint. Multi-head latent attention (DeepSeek-V3, Kimi K2) caches a compressed latent instead. GQA is still the commonest choice in open-weight models (gpt-oss shares each KV head across 8 query heads), but many 2025–26 flagships mix layer types: gpt-oss alternates full attention with 128-token banded windows, Qwen3-Next and Qwen3.5 follow every three Gated DeltaNet linear-attention layers with one gated full-attention layer, Nemotron-H replaces most attention layers with Mamba layers, and DeepSeek uses learned sparse or compressed attention. Linear and windowed layers keep a bounded state, so their memory and per-token cost stop growing with context; the remaining full-attention layers preserve exact long-range recall.
Positional information and long context
Self-attention is permutation-equivariant, so order must be injected. Sinusoidal and learnt absolute embeddings add position vectors; RoPE rotates pairs of query and key dimensions by position-dependent angles so their dot product depends on relative offset; ALiBi adds a distance-proportional penalty to the attention logits. Extending a model trained at 8k to 128k usually combines rescaled RoPE (position interpolation, NTK-aware scaling or YaRN, or a larger RoPE base) with continued training on long documents, then evaluation beyond needle-in-a-haystack.
Block anatomy and normalisation
A modern block is x + Attn(Norm(x)) followed by x + MLP(Norm(x)) (pre-norm), usually with RMSNorm and a gated SwiGLU MLP roughly 2.7–3.5× wider than the model (3.5× in Llama 3 8B). Layer norm and RMSNorm normalise each token over features, so they behave the same in training and inference and do not depend on batch composition or padding; batch norm normalises over the batch, needs running statistics at inference and is ill suited to variable-length autoregressive generation. The residual stream is the shared channel that layers read from and write to. Recent stability tweaks sit inside the block: QK-norm on queries and keys; a per-head sigmoid gate on the attention output (a NeurIPS 2025 best paper, used in Qwen3-Next and Qwen3.5) or an explicit learned sink in the softmax (gpt-oss), both of which stop heads parking attention on the first token; and DeepSeek-V4’s manifold-constrained hyper-connections, which widen the residual stream while keeping its identity-mapping property.
Flow · 4 stepsBlock anatomy: pre-norm attention and MLP
- Pre-norm attention The residual stream enters the block and is normalised before attention.
- Add attention output The attention output is added back to x.
- Pre-norm MLP The residual stream is normalised before the gated SwiGLU MLP.
- Add MLP output The MLP output is added back to x and leaves the block.
Data
| Step | Title | What happens |
|---|---|---|
| 1 | Pre-norm attention | The residual stream enters the block and is normalised before attention. |
| 2 | Add attention output | The attention output is added back to x. |
| 3 | Pre-norm MLP | The residual stream is normalised before the gated SwiGLU MLP. |
| 4 | Add MLP output | The MLP output is added back to x and leaves the block. |
Source: This page's text
| Box | Group | Detail |
|---|---|---|
| Residual stream in | Residual stream | |
| Norm | Attention | RMSNorm |
| Attention | Attention | recent: QK-norm, gate or sink |
| Add residual | Residual stream | |
| Norm | MLP | RMSNorm |
| SwiGLU MLP | MLP | gated, ~2.7–3.5× wider |
| Add residual | Residual stream | |
| Residual stream out | Residual stream |
Source: This page's text
Mixture of experts
An MoE layer replaces the dense MLP with E expert MLPs and a router that sends each token to the top k. Designs have moved from a few large experts (Mixtral: 2 of 8) to many small ones: gpt-oss-120b picks 4 of 128, DeepSeek-V3 picks 8 of 256 routed experts plus one always-on shared expert, and Qwen3.5 picks 10 of 512 plus a shared expert, so 397B total parameters cost about 17B per token. Compute per token scales with active parameters, but memory holds all of them. Routing needs load balancing (an auxiliary loss, or DeepSeek-V3’s auxiliary-loss-free scheme, which nudges a per-expert bias that affects only expert selection, not the output weights), capacity limits that can drop tokens, and expert parallelism with all-to-all communication. Training can be unstable, and serving needs enough batch to keep every expert busy.
Scaling laws and compute-optimal training
Training compute is about C ≈ 6ND FLOPs for N parameters and D tokens. Chinchilla found that for a fixed compute budget N and D should grow roughly equally, about 20 tokens per parameter, so a 70B model on 1.4T tokens beat much larger under-trained models. Production models are often trained far beyond that ratio (Llama 3 8B saw over 15T tokens; Llama 4 and DeepSeek-V4 report over 30T) because a smaller model is cheaper to serve for its whole life. When fresh high-quality data runs short, options include a few epochs of repetition, synthetic rephrasing (as in Kimi K2), better filtering and more inference-time compute, spent either on longer chains of thought or, in looped and recurrent-depth models, on re-applying the same layers several times.
Other generative model families
VAEs maximise the ELBO, E_q[log p(x|z)] − KL(q(z|x) ‖ p(z)), whose gap to log p(x) is the KL from q to the true posterior; they give likelihood bounds and fast sampling but blurrier samples. GANs train a generator against a discriminator, giving sharp samples and fast sampling but mode collapse and no likelihood. Diffusion models learn to reverse a noising process with a simple denoising loss (a reweighted ELBO); they give excellent quality and coverage but need many sampling steps, reduced by distillation, consistency models and flow-matching formulations.
Worked examples
Attention FLOPs and memory for one layer at 8k and 32k context
One multi-head attention layer has d_model = 4,096 and 32 heads of 128, followed by a SwiGLU MLP with hidden size 14,336. For one sequence of n = 8,192 tokens in bf16, compute the FLOPs of the projections, the attention core and the MLP, and the memory of a naively materialised score matrix. Repeat for n = 32,768.
Use 2 FLOPs per multiply-add.
1. Q, K, V and output projections. Four d × d matmuls over n tokens: 4 × 2 × n × d² = 8 × 8,192 × 4,096² = 1.10e12 FLOPs.
2. Attention core. QKᵀ summed over heads is 2 × n² × d = 2 × 8,192² × 4,096 = 5.5e11; the weighted sum with V is the same, so 4n²d = 1.10e12 FLOPs. It equals the projection cost exactly when 4n²d = 8nd², that is n = 2d = 8,192.
3. MLP. Three d × 14,336 matrices: 3 × 2 × n × d × 14,336 = 6 × 8,192 × 4,096 × 14,336 = 2.89e12 FLOPs.
4. Share at 8k. Core 1.10 / (1.10 + 1.10 + 2.89) ≈ 22% of the layer.
5. At 32k (4× longer). Projections and MLP scale with n: 4.4e12 and 1.15e13. The core scales with n²: 1.10e12 × 16 = 1.76e13, now about 53% of the layer. Long context makes attention dominant.
6. Naive score memory. heads × n² × 2 bytes = 32 × 8,192² × 2 = 4.3 GB per layer per sequence at 8k, and 69 GB at 32k, most of an 80 GB GPU. FlashAttention never materialises it: it streams tiles of K and V through on-chip memory with a running softmax, so memory is O(n).
7. Causal masking means half the scores are discarded; kernels that skip fully masked tiles do about half the core FLOPs.
Compute-optimal model size for a 1e23 FLOP budget
You have 1e23 training FLOPs. Using C ≈ 6ND and the Chinchilla rule of about 20 tokens per parameter, choose N and D. How long would it take on 1,000 H100s at 40% utilisation? Why might you choose a smaller model anyway?
1. Substitute D = 20N. C = 6 × N × 20N = 120N², so N = √(C/120) = √(1e23 / 120) = √(8.33e20) ≈ 2.9e10, about 29B parameters.
2. Tokens. D = 20 × 2.9e10 ≈ 5.8e11, about 580B tokens. Check: 6 × 2.9e10 × 5.8e11 ≈ 1.0e23. ✓
3. Wall-clock. 1,000 × 989e12 FLOP/s × 0.4 = 3.96e17 FLOP/s. Time = 1e23 / 3.96e17 ≈ 2.5e5 s, about 70 hours, or roughly 3 days.
4. Why go smaller. Compute-optimal minimises training loss per training FLOP, not total cost. If the model will serve trillions of tokens, inference cost (about 2N FLOPs per token) dominates. An 8B model trained on 15T tokens costs 6 × 8e9 × 1.5e13 = 7.2e23 FLOPs, 7× this budget, but is about 3.6× cheaper per token to serve than the 29B model. Over-training small models is the norm for deployed LLMs.
5. Caveats. The 20:1 ratio depends on data quality, architecture and tokeniser; when high-quality data is limited, repeated epochs give diminishing returns.
Memory versus compute for a mixture-of-experts model
Mixtral 8x7B routes each token to 2 of 8 experts per layer and has about 47B total and 13B active parameters. In bf16 on H100s (3.35 TB/s), compare memory, per-token compute and decode bandwidth with a dense 47B model, at batch 1 and at batch 32.
1. Memory. All experts must be resident: 47e9 × 2 B ≈ 94 GB, the same as a dense 47B model and more than one 80 GB GPU, so it needs two GPUs or quantisation.
2. Compute per token. About 2 × active parameters: 2 × 13e9 = 26 GFLOPs, against 94 GFLOPs for dense 47B, about 3.6× less. Prefill and other compute-bound work get correspondingly cheaper.
3. Decode at batch 1. Only the active weights are read: about 13e9 × 2 B = 26 GB per token, giving 26 GB / 3.35 TB/s ≈ 7.8 ms, so at most about 130 tokens/s. Dense 47B reads 94 GB (28 ms, about 36 tokens/s).
4. Decode at batch 32. With roughly uniform top-2-of-8 routing, the chance that a given expert in a layer is chosen by none of 32 tokens is (6/8)^32 = 0.75^32 ≈ 1e-4. So almost every expert is read each step: about 94 GB per step, about 28 ms, the same bandwidth cost as the dense model. The MoE still uses 3.6× fewer FLOPs, but decode is memory-bound, so its speed advantage largely disappears at moderate batch.
5. Takeaway. MoE buys training and prefill efficiency and quality per FLOP; it does not reduce memory, and its decode advantage is largest at small batch. Serving at scale adds expert parallelism and all-to-all communication, and skewed routing creates hot experts.
Flow · 4 stepsHow a mixture-of-experts layer routes a token
- Route A token enters the router.
- Select experts The router sends the token to the top k experts; all experts are resident.
- Balance and limit Load balancing nudges selection, and capacity limits can drop tokens.
- Emit Active experts produce the layer output; compute scales with active parameters.
Data
| Step | Title | What happens |
|---|---|---|
| 1 | Route | A token enters the router. |
| 2 | Select experts | The router sends the token to the top k experts; all experts are resident. |
| 3 | Balance and limit | Load balancing nudges selection, and capacity limits can drop tokens. |
| 4 | Emit | Active experts produce the layer output; compute scales with active parameters. |
Source: This page's text
| Box | Group | Detail |
|---|---|---|
| Token | Input | |
| Router | Compute | top k |
| Load balancing | Compute | aux loss or bias |
| Capacity limits | Compute | may drop tokens |
| E expert MLPs | Memory | all resident |
| Layer output | Output |
Source: This page's text
What changed recently
DeepSeek-V4: compressed sparse attention and hyper-connections at 1.6T parameters
DeepSeek-V4-Pro (1.6T total, 49B active) and V4-Flash (284B, 13B active) use a hybrid of Compressed Sparse Attention and Heavily Compressed Attention, so at a 1M-token context V4-Pro needs about 27% of DeepSeek-V3.2’s per-token FLOPs and 10% of its KV cache. They also replace the plain residual connection with manifold-constrained hyper-connections and train with the Muon optimiser. Interviewers use it to check that you see attention and the residual path, not the MLP, as where architecture design is now moving.
Qwen3.5 makes a linear-attention hybrid the open-weight flagship
Qwen3.5-397B-A17B stacks 15 repeats of three Gated DeltaNet (linear-attention) layers followed by one gated full-attention layer, each with an MoE of 512 experts where 10 routed plus 1 shared are active, giving about 17B active parameters and a 262k native window. It extends the Qwen3-Next design to a frontier-scale, natively multimodal release. Expect questions on what a linear-attention state can and cannot remember and why a few full-attention layers are kept.
Gated attention wins a NeurIPS 2025 best paper award
The Qwen team compared more than 30 gating variants on 15B MoE and 1.7B dense models and found that a head-specific sigmoid gate after scaled dot-product attention consistently helps: training is more stable, attention sinks shrink and context-length extension improves. The change is a few lines of code and already ships in Qwen3-Next, so interviewers ask why adding non-linearity and query-dependent sparsity at that point works.
Looped language models make depth a test-time knob
Ouro pretrains looped language models that re-apply a shared stack of layers in latent space, with an entropy-regularised objective that learns how much depth to use; its 1.4B and 2.6B models, trained on 7.7T tokens, match standard models of up to 12B on a range of benchmarks. With earlier recurrent-depth work, it gives research interviews a third way to spend compute besides parameters and chain-of-thought tokens.
gpt-oss: learned attention sinks, banded windows and MXFP4 experts
OpenAI’s open-weight gpt-oss models alternate fully dense attention with 128-token banded windows and give every head a learned bias in the softmax denominator, so a head can attend to nothing at all. The MoE weights, over 90% of the parameters, are stored in MXFP4 at about 4.25 bits, which lets the 120B model fit on a single 80 GB GPU. It is now the standard reference for questions on sinks, sliding windows and low-bit MoE weights.
Pitfalls
- Saying √d_k scaling is about numerical overflow; it keeps logit variance near 1 so the softmax does not saturate and gradients survive.
- Claiming attention is always the dominant cost; at short contexts the projections and MLP dominate, and attention dominates only beyond about n = 2d.
- Saying MoE reduces memory because only a few experts are active per token.
- Thinking RoPE alone lets a model generalise far beyond its training length without rescaling and long-context training.
- Quoting Chinchilla as ‘the’ optimal recipe for deployed models, ignoring inference cost over the model’s lifetime.
- Confusing GQA with multi-head attention using fewer heads; GQA keeps all query heads and shares only K and V.
How interviewers probe it
- Walk through one decoder layer’s attention with tensor shapes; why divide by √d_k, and what happens if you drop it? Where would an output gate go, and what does it do to attention sinks?
- Write attention and give its time and memory complexity; how does the KV cache change decoding, and what does FlashAttention change?
- Compare MHA, MQA, GQA and latent attention; why did most open-weight models adopt GQA, and why do flagships such as Qwen3.5 and DeepSeek-V4 now mix in linear, sparse or compressed attention layers?
- How does a transformer know token order? Compare sinusoidal, learnt, RoPE and ALiBi, and explain how an 8k model is stretched to 128k.
- What changes for training and serving with MoE compared with a dense model of similar quality, and why have recent models moved to hundreds of small experts plus a shared expert?
- Summarise Chinchilla and decide, for a fixed budget, between a bigger model on fewer tokens or a smaller one on more.
Quiz
Three questions from this guide. Answer each in your head or out loud, show the model answer, then rate yourself. The cards join your practice deck and come back when they are due.
Walk me through scaled dot-product self-attention in one decoder layer: tensor shapes, why the scores are divided by the square root of the key dimension, what the causal mask does, and how compute and memory grow with sequence length.
Model answer, written in a candidate's voice
- Input X [n,d_model] projected to Q,K,V; split into h heads; per head scores = Q_h K_hᵀ/√d_k, softmax, weighted sum of V_h; concat heads and apply output projection
- Divide by √d_k so dot-product logits have roughly constant variance as d_k grows, avoiding saturated softmax and tiny gradients
- Causal mask sets future key positions to −∞ before softmax so position i attends only to j≤i, enabling parallel teacher-forced training of an autoregressive decoder
- Per head compute is O(n²·d_k) and score memory is O(n²); across heads this is O(n²·d_model) compute and O(h·n²) scores; FlashAttention tiles/online-softmaxes to avoid materialising the n×n matrix with the same maths
- Attention sits inside the decoder block with residual connections and (pre-)normalisation, followed by a per-position MLP with its own residual
Why are attention logits divided by the square root of the key dimension, and what happens to training if you drop it?
Model answer, written in a candidate's voice
- Dot product variance grows with key dimension under i.i.d. zero-mean unit-variance components.
- Dividing by sqrt(d_k) normalises logit variance to about 1.
- Without it, logits get large, softmax saturates towards one-hot, and gradients shrink.
- Training becomes slower/less stable and can lock into near-argmax attention.
- Alternatives include QK-normalisation or a learned temperature.
Write the attention formula. Explain the time and memory complexity in sequence length, why scaling by √d matters, and how a KV cache changes decoding cost.
Model answer, written in a candidate's voice
- Attention: softmax(QKᵀ/√d)V; naive compute O(T²·d), attention-score memory O(T²).
- √d scaling: dot-product logits have std ~√d, so dividing by √d keeps variance near 1 and avoids softmax saturation.
- Multi-head: h parallel subspaces of width d/h; same total order, concatenated and projected.
- KV cache: store past K and V; each new token costs O(T·d) attention instead of recomputing the prefix; cache grows with layers × heads × head_dim × T (×2 for K and V).
- Variants: FlashAttention tiles with online softmax to avoid materialising the T×T matrix; GQA/MQA share K/V across heads to cut cache size.
You have finished this topic.
Reading
- The Illustrated TransformerA visual walkthrough of attention, heads and the encoder-decoder architecture.
- Attention Is All You NeedThe original transformer, including scaled dot-product attention and sinusoidal positions.
- Let's build GPT: from scratch, in code, spelled out (Andrej Karpathy)Builds a decoder-only transformer step by step; ideal preparation for implement-attention rounds.
- Neural Machine Translation of Rare Words with Subword UnitsThe paper that brought BPE to neural language models.
- GQA: Training Generalized Multi-Query Transformer Models from Multi-Head CheckpointsDefines grouped-query attention and shows how to uptrain it from a multi-head model.
- Training Compute-Optimal Large Language Models (Chinchilla)The compute-optimal scaling result behind the 20-tokens-per-parameter rule of thumb.
- The Big LLM Architecture Comparison (Sebastian Raschka)A regularly updated side-by-side of 2025–26 open models: MLA versus GQA, fine-grained MoE, sliding windows, QK-norm, sinks and linear-attention hybrids.
- Gated Attention for Large Language Models: Non-linearity, Sparsity, and Attention-Sink-FreeNeurIPS 2025 best paper: a systematic study of where to gate attention and why an output gate removes attention sinks and stabilises training.
Practise this topic
- Walk me through scaled dot-product self-attention in one decoder layer: tensor shapes, why the scores are divided by the square root of the key dimension, what the causal mask does, and how compute and memory grow with sequence length.
- Why are attention logits divided by the square root of the key dimension, and what happens to training if you drop it?
- Write the attention formula. Explain the time and memory complexity in sequence length, why scaling by √d matters, and how a KV cache changes decoding cost.
- Compare multi-head, multi-query and grouped-query attention, and latent attention if you know it. Why did most recent open-weight models adopt GQA, and what does it change when you serve the model?
- How does a transformer know token order? Compare learned/sinusoidal embeddings, RoPE and ALiBi, and explain how a model trained at 8k context can be stretched to 128k.
- Explain how a subword tokeniser such as byte-level BPE is trained and applied, then tell me how the choice of tokeniser shows up in cost, latency and quality for a product that serves Welsh, Turkish and English users, source code and numbers.
- What is a mixture-of-experts transformer, and what changes for training and serving compared with a dense model of similar quality?
- How does a mixture-of-experts layer work, what problems does routing introduce, and how does MoE change the memory, compute and communication profile compared with a dense model of similar quality?
- Summarise the compute-optimal scaling result from the Chinchilla work. With a fixed training budget, would you train a larger model on fewer tokens or a smaller model on more tokens, and how does expected inference demand change your answer?
- Compare VAEs, GANs and diffusion models on training objective, sample quality, mode coverage, likelihood evaluation and sampling speed.
- Qwen3.5-397B-A17B activates 10 of 512 routed experts plus one shared expert per token. Compared with Mixtral-style 2-of-8 routing, what do fine-grained and shared experts buy you, what do they cost in training and serving, and how does DeepSeek-V3’s auxiliary-loss-free load balancing work?
- Compare Native Sparse Attention, DeepSeek Sparse Attention and DeepSeek-V4’s compressed attention. What does each select or compress, what does it cost, how is it trained, and why do these methods train sparsity in rather than applying it to a finished dense model?
- Qwen3-Next and Qwen3.5 follow every three Gated DeltaNet (linear-attention) layers with one gated full-attention layer. What does a linear-attention layer keep instead of a KV cache, what is it bad at, and why ship a 3:1 hybrid rather than a fully linear model?
- The NeurIPS 2025 best paper on gated attention adds a head-specific sigmoid gate after scaled dot-product attention. Where exactly does the gate sit, why could such a small change stabilise training and remove attention sinks, and how would you test it on your own model?
- Explain batch normalisation: what it computes at training versus inference time, and why it helps. Why do transformers use layer norm or RMSNorm instead, and does pre-norm vs post-norm placement matter?
- Walk through how a modern chat model is produced, from raw text to deployed assistant: pretraining, supervised fine-tuning and preference/RL training. What can go wrong at each stage?
- Implement multi-head causal self-attention from scratch in PyTorch or JAX, without built-in attention functions. Be explicit about tensor shapes, the mask and the output projection.
- What does a key–value cache store during autoregressive generation? Give the formula for its memory footprint, explain why decoding is usually memory-bandwidth-bound, and describe how grouped-query or multi-query attention changes this.
- Self-attention is permutation-equivariant, so how does a transformer know token order? Compare sinusoidal, learned absolute and rotary embeddings, and discuss extending context beyond the training length.
- What are the main weaknesses of the standard transformer, and which modifications or alternatives address each (compute, memory, context length, reasoning)?
- A hand-written transformer language model trains, but its validation loss is suspiciously low and its generations are poor. Which bugs do you look for first?