Repository navigation
Module 14
⬅️ Module 13 · 🗺️ Curriculum · 🏠 Home · Module 15 ➡️
Level: Advanced · Prerequisites: Modules 01, 09, 13 · Time: about 10–12 hours
On this page: Overview and learning goals · Beginner: the big picture · Core concepts and derivations · Worked example · Implementation · Advanced topics · Pitfalls and best practices · Conceptual questions and answers · Sources and further reading
The Transformer (Vaswani et al. 2017) replaced recurrence with self-attention: every token directly attends to every other token in one parallel operation. It underlies modern language, vision, speech and multimodal models. This module derives scaled dot-product attention, multi-head attention and the full encoder/decoder block, and shows how to count parameters and cost.
After this module you should be able to:
- derive queries, keys, values and scaled dot-product attention, including why we divide by
$\sqrt{d_k}$ ; - explain permutation equivariance, and causal and padding masks;
- track tensor shapes through multi-head attention, the feed-forward network, residuals and norms;
- distinguish encoder-only, decoder-only and encoder–decoder designs and compute parameters/FLOPs.
Read the sentence "The animal didn't cross the street because it was tired." To interpret "it", you look at other words. Self-attention formalises this: each token asks a query ("what am I looking for?"), every token offers a key ("what do I contain?") and a value ("what do I pass on?"). Tokens whose keys match the query contribute more of their values. Because all tokens do this simultaneously, training is parallel across the sequence.
flowchart TD
X["Token embeddings + positions"] --> LN1["LayerNorm"]
LN1 --> MHA["Multi-head self-attention"]
X --> R1(("+"))
MHA --> R1
R1 --> LN2["LayerNorm"]
LN2 --> FFN["Feed-forward network (MLP)"]
R1 --> R2(("+"))
FFN --> R2
R2 --> OUT["Block output (repeat N times)"]
Figure 14.1 — A pre-LN Transformer block. Original diagram; the architecture follows Vaswani et al. (2017) with the pre-LN arrangement analysed by Xiong et al. (2020).
Text → tokens (sub-words, Module 23) → integer IDs → rows of an embedding matrix
Three learned linear projections of the inputs:
Why
Row
For a permutation matrix
(softmax is row-wise, so it commutes with row/column permutation). Self-attention is therefore permutation-equivariant: it sees a set of tokens, which is why positional information must be injected (Module 15).
Add

Figure 14.2 — Random figures/make_figs_2.py).
Run
Heads can specialise (syntax, coreference, positional patterns). Shapes:
Applied independently to each token:
Each sub-layer is wrapped as
The encoder stacks bidirectional self-attention + FFN. The decoder has (i) causal self-attention, (ii) cross-attention with queries from the decoder and keys/values from the encoder output, (iii) FFN. Cross-attention is the Module 13 mechanism in
| Family | Attention | Objective | Examples |
|---|---|---|---|
| Encoder-only | bidirectional | masked-token prediction | BERT |
| Decoder-only | causal | next-token prediction | GPT, LLaMA |
| Encoder–decoder | both + cross | span/seq2seq | T5, original Transformer |
Parameter count per layer (
import numpy as np
def softmax(s):
s = s - s.max(-1, keepdims=True); e = np.exp(s); return e / e.sum(-1, keepdims=True)
def mha(X, Wq, Wk, Wv, Wo, h, causal=False):
T, d = X.shape; dk = d // h
split = lambda M: (X @ M).reshape(T, h, dk).transpose(1, 0, 2) # (h, T, dk)
Q, K, V = split(Wq), split(Wk), split(Wv)
S = Q @ K.transpose(0, 2, 1) / np.sqrt(dk) # (h, T, T)
if causal: S = np.where(np.tril(np.ones((T, T))) == 1, S, -np.inf)
A = softmax(S); O = (A @ V).transpose(1, 0, 2).reshape(T, d) # concat heads
return O @ Wo, A
# check the worked example
Q = np.eye(2); K = np.array([[1., 0.], [1., 1.]]); print(softmax(Q @ K.T / np.sqrt(2)).round(3))import torch, torch.nn as nn
layer = nn.TransformerEncoderLayer(d_model=512, nhead=8, dim_feedforward=2048, norm_first=True, batch_first=True)
mask = nn.Transformer.generate_square_subsequent_mask(T) # causal mask- Efficient attention: FlashAttention (IO-aware exact attention), sparse/local/sliding-window attention, linear attention, multi-query and grouped-query attention to shrink the KV cache (Module 23).
- Architecture variants: RMSNorm, SwiGLU, parallel attention+FFN blocks, mixture-of-experts FFNs, QK-norm.
- Vision Transformers treat image patches as tokens (Dosovitskiy et al. 2021).
- Mechanistic interpretability: induction heads, residual-stream analysis, superposition.
-
Scaling and stability: learning-rate warm-up,
$\mu$ P, attention-logit growth and z-loss, precision issues in softmax. - Expressivity and limits: fixed-depth attention has theoretical limitations on some sequential/algorithmic tasks; chain-of-thought extends effective computation.
- Forgetting the causal mask during training of decoder models (information leak → train loss collapses to ~0, generation fails).
- Wrong mask polarity/dtype; adding
$-10^9$ in half precision overflow issues (use-infor dtype-min). - Mixing
$(B,T,d)$ and$(T,B,d)$ conventions. - Not scaling logits by
$1/\sqrt{d_k}$ . - Ignoring that
$T^2$ memory limits context length.
Q1. Why divide by
Show answer
Dot products of unit-variance vectors have variance
Q2. Why is self-attention permutation-equivariant and what is the consequence?
Show answer
Permuting the inputs permutes the outputs identically because the operations are symmetric across positions; word order is invisible unless positional information is added.
Q3. What does multi-head attention buy over single-head attention of the same width?
Show answer
Multiple independent softmaxes let the layer attend to different positions/relations simultaneously; a single softmax averages everything into one distribution.
Q4. How are causal masks implemented and why before the softmax?
Show answer
Set forbidden logits to
Q5. Where are most of a Transformer's parameters?
Show answer
FFN layers (
Q6. Encoder-only vs decoder-only models?
Show answer
Encoder-only (bidirectional) models give contextual representations for understanding tasks; decoder-only (causal) models generate text autoregressively and, at scale, also solve understanding tasks via prompting.
Q7. What is cross-attention?
Show answer
Attention whose queries come from one sequence (decoder) and keys/values from another (encoder output), letting the decoder read the source.
Q8. What is the time/memory complexity of self-attention and why does it matter?
Show answer
Q9. Why are residual connections essential in Transformers?
Show answer
They keep an identity gradient path through dozens of layers and let each sublayer add a refinement to the residual stream.
- Vaswani, A., et al. (2017). Attention is all you need. NeurIPS. arXiv:1706.03762.
- Devlin, J., et al. (2019). BERT. NAACL. arXiv:1810.04805.
- Radford, A., et al. (2018, 2019). Improving language understanding by generative pre-training; Language models are unsupervised multitask learners (GPT, GPT-2). OpenAI technical reports.
- Raffel, C., et al. (2020). Exploring the limits of transfer learning with a unified text-to-text Transformer (T5). JMLR, 21.
- Xiong, R., et al. (2020). On layer normalization in the Transformer architecture. ICML.
- Shazeer, N. (2020). GLU variants improve Transformer. arXiv:2002.05202.
- Dosovitskiy, A., et al. (2021). An image is worth 16×16 words: Transformers for image recognition at scale. ICLR. arXiv:2010.11929.
- Elhage, N., et al. (2021). A mathematical framework for Transformer circuits. Anthropic (Transformer Circuits Thread).
- Phuong, M., & Hutter, M. (2022). Formal algorithms for Transformers. arXiv:2207.09238.
⬅️ Module 13 · 🗺️ Curriculum · 🏠 Home · Module 15 ➡️
🏠 Home · 🗺️ Curriculum · 🧭 Learning paths · ❓ Question bank · 📖 Glossary · 📚 References · ✏️ Contributing
🏠 Home · 🗺️ Curriculum · 🧭 Learning paths
❓ Question bank · 📖 Glossary · 📚 References
Jump to module:
01 02 03 04 05 06 07 08 09 10 11 12
13 14 15 16 17 18 19 20 21 22 23 24