Published research guide
Transformers: a research guide
The architecture that ate machine learning.
Published by ArcXiv on · Updated
Overview
Transformers are sequence models built almost entirely from one operation: scaled dot-product attention. Each token decides, in parallel, how much to look at every other token. Layers of attention plus position-wise MLPs stack into a deep model that scales gracefully on modern accelerators because there is no inherent sequential dependency inside a block.
The architecture won because three things compose: the inductive bias is weak enough to learn almost anything from data, the operations are matrix-friendly, and the model can be trained at scale without exploding gradients thanks to residual connections, LayerNorm, and careful initialization. Every modern LLM, most vision backbones, and a growing share of audio/video models are transformers in some dress.
To learn transformers well you need three lenses at the same time: the math of attention, the engineering of a real implementation, and the historical context for why specific choices (LayerNorm placement, residual streams, RoPE) won.
Chapter 1 of 3 · beginner
Foundations
The math and mental model behind attention.
Before you write a single line of transformer code, you need three things in your head: why attention exists, what the residual stream really is, and what positional encoding actually encodes. This chapter walks you through those, anchored to the original 2017 paper.
Explain attention without waving your hands.
1.1 · 6 min read
What attention buys you
RNNs sequential, convolutions local — attention is both global and parallel.
Before transformers, sequence models were either recurrent (LSTM, GRU) or convolutional. RNNs handled long-range dependencies in principle but, because each step depended on the last, they couldn't be parallelised across time. Convolutions parallelised but only saw a fixed local window. Both bled accuracy at long sequence lengths because gradients had to propagate through many steps.
Attention is the answer: every token in the sequence directly looks at every other token, in one matrix multiplication. The result is a model that is global in receptive field and parallel in compute, so it scales gracefully on modern accelerators. The cost is quadratic memory — but that's a tractable engineering problem, not a learning problem.
What you need before transformers
1.2 · 8 min read
Scaled dot-product attention
Three projections, one softmax, one matmul. That's it.
Each token starts as a vector in the residual stream. Attention turns each token into three projections: a query asking 'what am I looking for?', a key answering 'this is what I am', and a value carrying the information to mix back in. Queries dot with keys to score relevance, the scores are normalised by a softmax, and the values are mixed in proportion to those scores.
Attention is softmax-normalised dot products of queries with keys, used to weight values.
The divisor is not cosmetic. Without it, as the head dimension grows, the dot products scale with in standard deviation. That pushes the softmax inputs into a regime where one entry dominates, the distribution collapses to almost one-hot, and gradients through the softmax vanish. The scale factor keeps softmax temperature roughly invariant to .
Why softmax, specifically?
Any monotone normaliser would give you a distribution. Softmax wins because (a) it's differentiable everywhere, (b) the gradient has a clean form , and (c) the exponential makes the model commit — a small score advantage compounds into a clear winner. Linear attention drops the softmax and pays for it with much worse pattern selectivity.
Check your understanding
Why divide attention scores by √d_k?
1.3 · 5 min read
Positional encoding
Attention is order-blind. Position has to be encoded by hand.
Self-attention is permutation-equivariant: shuffle the input tokens and the output shuffles the same way. Language is not permutation-equivariant — 'dog bites man' and 'man bites dog' mean different things. Something has to carry order, and that something is the positional encoding.
The original paper added a fixed sinusoidal vector to the token embedding before the first attention layer. Modern systems prefer rotary positional embeddings (RoPE), which rotate Q and K in 2-D subspaces by an angle proportional to position. RoPE encodes *relative* position naturally and extrapolates better to longer contexts.
Chapter 2 of 3 · intermediate
Inside one block
How a transformer turns vectors into vectors.
A transformer is the same block stacked dozens of times. Once you can trace one forward pass — embeddings, attention, MLP, residuals, LayerNorm — you can read any model architecture in the wild. We'll trace a decoder block because that's what every modern LLM uses.
Trace a forward pass end to end without looking at a reference.
2.1 · 8 min read
Forward pass through a decoder block
Embed → LayerNorm → attention → MLP → next-token logits.
Forward pass through one decoder block
- Tokens
- Embed + PERoPE or sinusoidal
- LayerNorm
- Q, K, Vlinear projections
- Attentionsoftmax(QKᵀ/√d) V
- + residual
- LayerNorm
- MLPGeLU / SwiGLU
- + residual
- Next-token logits
Tokens are first embedded into the residual stream and combined with a positional signal. From there, every block reads from the residual stream, computes something, and writes the result *back* to the same stream via a residual addition. That's the central engineering trick: the residual stream is a shared bus, and each block is a side-channel that adds its contribution without erasing the rest.
Inside one block, the two side-channels are attention (mixes information across positions) and the MLP (mixes information within a position). LayerNorm sits before each, in the now-dominant pre-norm configuration, to keep activations well-scaled at every depth. Without it, deep stacks become unstable around block 30.
Pre-norm vs post-norm
The 2017 paper used post-norm (LayerNorm AFTER the residual add). Every modern model uses pre-norm because training is dramatically more stable at depth. The cost is a small accuracy hit at very small scales — irrelevant for anything you'd actually train.
2.2 · 5 min read
Multi-head attention
One attention is brittle. Many attentions in parallel are not.
A single attention head learns one similarity metric. That's fragile: a head can be the right tool for 'match the subject to its verb' but the wrong tool for 'attend to the previous punctuation'. Multi-head attention runs independent attentions in parallel, each with its own learned projections, then concatenates the outputs and projects back to model dimension.
In practice each head specialises. Mechanistic-interpretability work has named specific head types: induction heads, name-mover heads, copy-suppression heads. The model doesn't 'know' it's doing this — it falls out of training.
2.3 · 5 min read
The KV cache
What makes generation linear instead of quadratic.
At training time, the model sees the whole sequence at once. At inference time it generates one token at a time, and every step would otherwise recompute attention over the entire past. The trick is that for past tokens the and projections never change — only the current token's matters. Cache the past s and s, and per-step inference drops from to .
# Sketch — not production code.
for step in range(max_new_tokens):
q = project_q(current_token)
k_new = project_k(current_token)
v_new = project_v(current_token)
k_cache.append(k_new)
v_cache.append(v_new)
# Attend over the WHOLE cache, not just one step.
scores = q @ stack(k_cache).T / sqrt(d_k)
attn = softmax(scores)
out = attn @ stack(v_cache)
current_token = sample(project_out(out))Per-step inference with a KV cache.
Chapter 3 of 3 · advanced
What's still open
Where the transformer is starting to bend.
The architecture is settled, but the field is not. Long context, KV memory, low-precision training, and post-transformer ideas like SSMs are all live. Pick the threads you care about; this chapter is a map, not the territory.
Know which research directions matter and which are noise.
3.1 · 6 min read
Long-context attention
Quadratic compute hits a wall around 100k tokens.
Vanilla attention is in both compute and memory. Past ~32k tokens that's a serious wall, especially during training where you don't have a KV cache to amortise. The frontier here is a spectrum: sparse attention (only attend to a learned subset), linear attention (drop the softmax for an associative kernel), flash attention (re-tile the computation so the matrix never materialises), and state-space models (Mamba and friends, which replace attention with a learned linear recurrence).
Flash attention is the boring-but-essential one: it doesn't change the math, just the I/O pattern. Everyone uses it. The exotic ones — Mamba, RWKV, RetNet — keep appearing but haven't dethroned the transformer for general language modelling yet.
Attention is all you need.
3.2 · 5 min read
Scaling laws and the data wall
Compute-optimal training meets the limits of the web.
Kaplan et al. (2020) and then Hoffmann et al. (2022) showed that, for a fixed compute budget, there is a specific ratio of parameters to training tokens that minimises loss. Earlier work had over-parameterised and under-trained; Chinchilla's rule of thumb of roughly 20 tokens per parameter shifted the field.
The practical consequence in 2024-2026 is the data wall: the web's high-quality text supply is finite. Modern training pipelines spend serious effort on filtering, deduplication, and synthetic data because more parameters can no longer compensate for thin data.
Why this matters for you
If you're training a small model from scratch, the Chinchilla recipe still applies — train for tokens, not for parameters. If you're fine-tuning a frontier model, the data quality of your fine-tune set matters far more than its size.
Study resources
Diagrams, source papers, vocabulary, exercises, knowledge checks, and review cards for this guide.
Concepts and prerequisites
Diagrams
What you need before transformers
Forward pass through one decoder block
- Tokens
- Embed + PERoPE or sinusoidal
- LayerNorm
- Q, K, Vlinear projections
- Attentionsoftmax(QKᵀ/√d) V
- + residual
- LayerNorm
- MLPGeLU / SwiGLU
- + residual
- Next-token logits
Scaled dot-product attention
For each query, score it against every key, normalize the scores into a probability distribution, then take a weighted average of the values.
- queries — what the current token is looking for
- keys — what each token offers to be matched against
- values — the information actually mixed back in
- key dimension; the √d_k scales scores so softmax doesn't saturate
How we got here
- 2014
Seq2Seq
methodEncoder/decoder RNNs prove sequence-to-sequence is learnable end-to-end.
- 2014
Bahdanau Attention
methodAttention added on top of RNN decoders solves long alignments.
- 2017
Attention Is All You Need
architectureDrop recurrence entirely. Stack attention + MLPs. Train faster, scale further.
- 2019
GPT-2
scalingA decoder-only transformer scaled to 1.5B parameters generates coherent text.
- 2020
Scaling Laws for LMs
scalingLoss falls predictably with compute, data, and parameters.
- 2021
RoPE
methodRotary positional embeddings: relative positions baked into Q/K rotations.
- 2022
Chinchilla
scalingCompute-optimal models are smaller and trained on more tokens than GPT-3 was.
Attention is not memory by default
Why people get this wrong: The image of 'looking at every other token' makes it sound like memory, but the cost is O(n²) precisely because there is no compressed state — every comparison is recomputed.
Paper roadmap
Read the source papers in the order that best supports the guide.
- CanonicalarXiv:1706.03762· 2017
Attention Is All You Need
Vaswani et al.
The original transformer paper. Read sections 3 and 5 carefully; the rest is translation-task plumbing.
read §3 Model Architecture, §3.2 Attention, §5 Training · skip §6 Results (translation-specific)
- BackgroundarXiv:1409.0473· 2014
Neural Machine Translation by Jointly Learning to Align and Translate
Bahdanau et al.
The first time attention appears in deep learning. Reading this before the 2017 paper turns 'why softmax over keys' into an obvious answer.
read §3 Learning to Align and Translate
- BackgroundarXiv:1607.06450· 2016
Layer Normalization
Ba, Kiros, Hinton
LayerNorm is the unsung hero of stable transformer training. Short paper, big payoff.
read §3
- FrontierarXiv:2104.09864· 2021
RoFormer: Enhanced Transformer with Rotary Position Embedding
Su et al.
RoPE is now the default positional encoding in serious LLMs. The derivation is cleaner than its reputation suggests.
read §3.2 Rotary Position Embedding
- BeginnerarXiv:1810.04805· 2018
BERT: Pre-training of Deep Bidirectional Transformers
Devlin et al.
Encoder-only transformers in one accessible paper. The masked-LM objective set the template for all modern pretraining.
read §3 BERT · skip §5 Ablation
- FrontierarXiv:2203.15556· 2022
Training Compute-Optimal Large Language Models (Chinchilla)
Hoffmann et al.
The paper that retired 'bigger = better' and replaced it with a token-per-parameter recipe.
read §3 Estimating the optimal parameter/training tokens allocation
Vocabulary
- Query / Key / Value
- Three linear projections of the input. Queries ask, keys answer, values get mixed back in proportional to the query–key match.
- Causal mask
- An upper-triangular -∞ mask that prevents a token at position t from attending to positions > t. Required for autoregressive generation.
- RoPE
- Rotary positional embedding. Encodes relative position by rotating Q and K vectors in 2-D subspaces by an angle proportional to position.
- Residual stream
- The running-sum vector at each token position that every block reads from and writes to. The mental model behind mech interp.
Exercises
Implement scaled dot-product attention in 20 lines of PyTorch
Write a function that takes Q, K, V (B, T, d) and an optional causal mask. Return the attention output and the attention weights. Verify it matches `torch.nn.functional.scaled_dot_product_attention` to 1e-6.
Difficulty 2/5
Train a tiny GPT on TinyStories
Stack 4 decoder blocks with d_model=128, 4 heads, train for 5k steps on a TinyStories subset. Plot the loss curve. Generate a 200-token sample with temperature 0.8 and report what makes sense and what doesn't.
Difficulty 3/5
Knowledge checks
Which component is responsible for telling tokens apart by position?
- The MLP
- The residual stream
- Positional encodings
- Dropout
Answer: Positional encodings
Self-attention is permutation-equivariant. Without a positional signal added or rotated into Q/K, tokens are interchangeable bags of vectors.
Why is the KV cache primarily an inference-time optimization, not training-time?
- Training uses bigger batches
- Training does a single parallel forward pass per sequence so there is nothing to cache between calls
- Caches are too memory-hungry to train with
- Modern optimizers fuse Q,K,V differently
Answer: Training does a single parallel forward pass per sequence so there is nothing to cache between calls
During training, the whole sequence is processed at once. The cache speeds up step-by-step autoregressive decoding, where the same past gets reused every step.
What is the asymptotic cost of standard self-attention in sequence length n?
- O(n)
- O(n log n)
- O(n²)
- O(n²) memory but O(n) compute
Answer: O(n²)
Forming the full attention matrix QKᵀ is O(n²) in both compute and memory. Linear attention and SSMs exist to break this.
Flashcards
- Why divide attention scores by √d_k?
- To keep the softmax inputs at unit variance. Without the scale, large d_k makes the dot products huge and softmax saturates, killing gradients.
- Encoder, decoder, encoder-decoder — which one is GPT?
- Decoder-only with a causal mask. BERT is encoder-only. The original 2017 paper is encoder–decoder.
- What does a KV cache cache, and why?
- The K and V projections of every previous token. During autoregressive decoding the past doesn't change, so caching turns per-step cost from O(n²) into O(n).
- What is the Chinchilla scaling rule of thumb?
- Compute-optimal training uses roughly 20 tokens per parameter. Earlier scaling laws underweighted data.
What to study next
Cited papers
Every structured arXiv source cited by the guide and its diagrams.
- Attention Is All You Need (arXiv:1706.03762)
- Neural Machine Translation by Jointly Learning to Align and Translate (arXiv:1409.0473)
- Layer Normalization (arXiv:1607.06450)
- RoFormer: Enhanced Transformer with Rotary Position Embedding (arXiv:2104.09864)
- BERT: Pre-training of Deep Bidirectional Transformers (arXiv:1810.04805)
- Training Compute-Optimal Large Language Models (Chinchilla) (arXiv:2203.15556)
- Seq2Seq (arXiv:1409.3215)
- Scaling Laws for LMs (arXiv:2001.08361)