AI and ML FoundationsVol. 14A · Part XIV
0 / 0

Shelves / AI and ML Foundations

AI·154

Transformers

The architecture behind modern AI, derived piece by piece: token embeddings, attention as a differentiable soft dictionary lookup, scaled dot-product attention and why the √d scaling, a full numeric worked example, self-attention vs cross-attention, causal masking, multi-head attention with shape walkthroughs, multi-query and grouped-query attention, the Transformer block with residual streams, pre-norm and RMSNorm, the position-wise MLP and SwiGLU, positional information from sinusoidal encodings to learned positions, ALiBi and rotary embeddings (RoPE) with the rotation derivation, encoder-only, decoder-only and encoder-decoder families, the quadratic cost of attention, FlashAttention, KV caching, sliding windows, sparse and linear attention, context extension, and a complete GPT-style model in PyTorch checked against the fused attention kernel.

27 topics · ~24 min read · 32-question quiz
Updated Suggest a correction

Start here: attention as a soft lookup

A Transformer processes a sequence of tokens (word pieces) by letting every position gather information from other positions, in a step called attention. Think of it as a soft dictionary lookup: each position asks a question (a query vector), every position offers a label (a key vector) and some content (a value vector). The query is compared with every key by a dot product; a softmax turns the scores into weights that sum to 1; the result is the weighted average of the values:

Python
def attention(q, k, v, mask=None):
    s = q @ k.transpose(-2, -1) / math.sqrt(q.shape[-1])     # compare each query with every key
    if mask is not None: s = s.masked_fill(mask, float("-inf"))
    return s.softmax(-1) @ v                                 # weighted average of values

A Transformer block is attention followed by a small MLP, each wrapped with a residual connection and layer normalisation; a model stacks dozens of blocks.

Why divide by √d

Random queries and keys with unit-variance entries, 16 keys each:

Text
d =   16  unscaled: largest weight 0.675, entropy 0.93 nats   scaled: 0.239, 2.37
d =  256  unscaled: largest weight 0.920, entropy 0.20 nats   scaled: 0.244, 2.36
d = 1024  unscaled: largest weight 0.966, entropy 0.08 nats   scaled: 0.248, 2.36   (uniform = 2.77)

A dot product of d random terms has spread √d, so without scaling, wider vectors give huge scores, softmax puts nearly all weight on one key (0.966), and its gradient vanishes. Dividing by √d keeps scores at unit spread whatever the width: the attention stays soft and trainable.

The causal mask: no peeking at the future

A language model predicts each token from the ones before it, so position i may only attend to positions ≤ i. A mask sets future scores to −∞ before the softmax:

Text
change token 5 → largest change in outputs at positions 0–4: 0.0    at positions 5–7: 33.02
attention weights of position 2: [0.139, 0.629, 0.232, 0, 0, 0, 0, 0]

Earlier positions were completely unaffected by a change at position 5, and position 2's weights over positions 3–7 were exactly zero. This is what lets one forward pass train on every position of a sequence at once.

The price: attention is quadratic

Text
sequence length   256: 0.3 ms    1,024: 11.4 ms    2,048: 163.8 ms    4,096: 466.5 ms
score matrix size 0.3 MB          4.2 MB             16.8 MB             67.1 MB   (one head)

Every position compares with every other, so doubling the sequence quadruples the score matrix. That's why long contexts are expensive and why tricks like FlashAttention (which never stores the full matrix), sliding windows and KV caching (chapter 156) matter.

Where the parameters live

Text
d_model = 128:   attention 0.07 M + MLP 0.13 M  ≈ 0.20 M per block
d_model = 768:   attention 2.36 M + MLP 4.72 M  ≈ 7.08 M per block   (GPT-2 small: 12 blocks)
d_model = 4096:  attention 67 M   + MLP 134 M   ≈ 201 M per block

About 12·d² per block: four d×d attention matrices (query, key, value, output) and an MLP that widens to 4d and back. Two thirds of a Transformer's weights sit in its MLPs.

How deep to go in Transformers

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Explain attention, queries/keys/values and what a Transformer block contains
L2 Implement scaled dot-product and multi-head attention with masks in PyTorch
L3 Explain the √d scaling, positional encodings (sinusoidal, RoPE), residual streams and parameter counts
L4 Debug attention implementations (masking, shapes, numerical stability) and profile their cost
L5 Choose architecture variants (GQA, MoE, long-context methods) for a model's constraints
L6 Design and scale Transformer architectures for frontier models

The big picture

The Transformer ("Attention Is All You Need", Vaswani et al., 2017) processes a sequence of vectors by repeatedly applying two operations:

  1. Attention: each position gathers information from other positions, weighted by relevance. Mixing across positions.
  2. MLP (feed-forward network): each position transforms its own vector independently. Computation within a position.

Both are wrapped with residual connections and normalisation, stacked N times. Because attention compares all positions at once (no recurrence), training parallelises across the whole sequence, which is what made scaling to trillions of tokens practical.

token ids [B, T] embedding → x [B, T, d] × N blocks RMSNorm causal MH attention + RMSNorm MLP (SwiGLU) + residualstream norm → unembed → logits [B,T,V]
A decoder-only Transformer, the architecture of GPT-style language models. Token ids are embedded into vectors; a stack of identical blocks each applies normalisation, causal multi-head self-attention and an MLP, each added back into the residual stream; a final normalisation and an output projection produce logits over the vocabulary for the next token at every position.

Embeddings

Text is first split into tokens (chapter 155) mapped to integer ids in a vocabulary of size V (32k–260k for current LLMs). An embedding matrix E ∈ ℝ^{V×d} turns each id into a learned vector of dimension d (the model width, e.g. 768, 4096, 8192): a lookup, equivalent to multiplying a one-hot vector by E.

  • Embeddings are learned end-to-end; tokens used in similar contexts end up with similar vectors.
  • The output layer (unembedding) maps final vectors back to V logits; many models tie it to Eᵀ to save parameters.
  • From here on, the model works in the residual stream: a [batch, tokens, d] tensor that every block reads from and adds to.

Attention from first principles

A soft dictionary lookup

A Python dict returns the value whose key exactly matches a query. Attention is a differentiable version: compare the query with every key, turn similarities into weights that sum to 1, and return the weighted average of the values.

Attention(q, K, V) = Σᵢ softmax(q · kᵢ / √d_k) vᵢ

In matrix form for all positions at once (the roadmap's formula):

Q = XW_Q, K = XW_K, V = XW_V Attention(Q, K, V) = softmax(QKᵀ / √d_k) V

  • Query (what this position is looking for), key (what each position offers to be matched on), value (what each position contributes if attended to): three different learned projections of the same input X.
  • QKᵀ is a [T × T] matrix of scores: row i says how much position i wants to look at each position j.
  • Softmax over each row gives the attention weights (each row sums to 1).
  • Multiplying by V mixes value vectors accordingly: the output at position i is a context-dependent blend of information from the sequence.
X Q = XW_Q K = XW_K V = XW_V QKᵀ[T × T] ÷ √d_k mask softmax weights × V→ out [T × d_k]
Scaled dot-product attention. Inputs are projected to queries, keys and values. Each query is compared with every key by dot product, the scores are scaled by one over the square root of the key dimension, optionally masked, and normalised with softmax into weights; the output for each position is the weighted sum of value vectors.

Why divide by √d_k

If the components of q and k are independent with mean 0 and variance 1, their dot product has variance d_k. With d_k = 128, scores have standard deviation ≈ 11: softmax of such large numbers is nearly one-hot, its gradients nearly zero, and training stalls. Dividing by √d_k restores unit variance.

Python
import numpy as np
rng = np.random.default_rng(0)
for d in (16, 128, 1024):
    q, k = rng.normal(size=(10000, d)), rng.normal(size=(10000, d))
    print(d, round((q * k).sum(1).std(), 1), round(((q * k).sum(1) / np.sqrt(d)).std(), 2))
# 16 → 4.0 vs 1.0 · 128 → 11.3 vs 1.0 · 1024 → 32.0 vs 1.0

Worked example

Three tokens with d_k = 2 (tiny, for hand calculation):

Python
def softmax(z, axis=-1):
    z = z - z.max(axis=axis, keepdims=True); e = np.exp(z); return e / e.sum(axis=axis, keepdims=True)

Q = np.array([[1.0, 0.0], [0.0, 1.0], [1.0, 1.0]])
K = np.array([[1.0, 0.0], [0.0, 1.0], [1.0, 1.0]])
V = np.array([[10.0, 0.0], [0.0, 10.0], [5.0, 5.0]])

scores = Q @ K.T / np.sqrt(2)          # [[0.71, 0, 0.71], [0, 0.71, 0.71], [0.71, 0.71, 1.41]]
W = softmax(scores)                    # row 0 ≈ [0.40, 0.20, 0.40]: token 0 attends to 0 and 2
out = W @ V                            # row 0 ≈ [6.0, 4.0]: a blend of values 0 and 2

Token 0's query [1, 0] matches keys 0 and 2 equally (both have first component 1), so its output mixes their values; key 1 (orthogonal) gets less weight.

Self-attention vs cross-attention

  • Self-attention: Q, K and V all come from the same sequence: each token looks at other tokens of the same text.
  • Cross-attention: Q comes from one sequence, K and V from another: a decoder generating a translation attends to the encoded source; an image generator attends to the text prompt's embeddings; a multimodal model's text tokens attend to image features.

Causal masking

A language model predicting token t+1 must not see tokens after t. A causal mask sets scores for j > i to −∞ before softmax, so those weights become 0. One forward pass over a sequence of T tokens thus trains T next-token predictions in parallel (teacher forcing).

keys (j) → Thecatsatonmat Thecatsatonmat green: allowed (j ≤ i)orange: score = −∞→ weight 0 after softmax T predictions per pass(teacher forcing)
A causal attention mask for five tokens. Row i is the query position and column j the key position. Cells on or below the diagonal are allowed; cells above it are set to minus infinity before softmax, so each token can only use itself and earlier tokens. Encoder models such as BERT use no mask and see the whole sequence.

Multi-head attention

One attention operation computes one kind of weighting. Multi-head attention runs h attention operations in parallel ("heads"), each with its own projections into a smaller dimension d_head = d/h, then concatenates the results and mixes them with an output projection W_O. Different heads learn different relations: previous-token, syntactic dependencies, coreference, copying ("induction heads"), positional patterns.

Shapes for batch B, length T, width d, heads h:

Step Shape
Input x [B, T, d]
Q, K, V = x W_Q, x W_K, x W_V [B, T, d] each
Split heads [B, h, T, d_head]
Scores Q Kᵀ / √d_head [B, h, T, T]
Weights · V [B, h, T, d_head]
Merge heads [B, T, d]
Output projection W_O [B, T, d]

Parameters per attention layer: 4d² (+ biases if used). The [T, T] score matrix per head is the source of attention's quadratic cost in sequence length.

Multi-query and grouped-query attention

At inference, keys and values of past tokens are cached (the KV cache, chapter 157/166). Its size per token is 2 × layers × kv_heads × d_head × bytes. To shrink it:

  • Multi-query attention (MQA): all query heads share one K/V head.
  • Grouped-query attention (GQA): query heads are divided into groups that share K/V heads (e.g. 32 query heads, 8 KV heads): the standard in most current open models.
  • Multi-head latent attention (MLA) (DeepSeek): compresses K/V into a low-rank latent that is cached instead.

Worked number: a model with 80 layers, 8 KV heads, d_head 128, bf16 (2 bytes): 2 × 80 × 8 × 128 × 2 = 327,680 bytes ≈ 320 KB per token: a 128k-token context needs about 40 GB of KV cache per sequence. With 64 full KV heads it would be 8× larger.

The Transformer block

Text
x = x + Attention(Norm(x))     # mix information across positions
x = x + MLP(Norm(x))           # transform each position
  • Residual stream: blocks add their outputs to x rather than replacing it, so information and gradients flow freely (chapter 151). A useful mental model: the stream is a shared communication channel; attention heads move information between positions; MLPs read and write features (often acting like key-value memories of facts).
  • Pre-norm (normalise the input of each sub-layer) trains far more stably at depth than the original post-norm; a final norm precedes the output projection.
  • RMSNorm: x / √(mean(x²) + ε) · γ, cheaper than LayerNorm and standard in LLMs.
  • MLP: expands to a hidden size of ~4d (or ~8/3·d for gated variants), applies a nonlinearity, projects back. SwiGLU: MLP(x) = W_down(SiLU(x W_gate) ⊙ (x W_up)). The MLPs hold about two-thirds of a dense model's parameters.
  • Parameters per block ≈ 12d² (4d² attention + 8d² MLP with 4× expansion), so a model with L layers has ≈ 12·L·d² parameters plus embeddings. GPT-3 (L = 96, d = 12288): 12 × 96 × 12288² ≈ 174B, matching its 175B.

Positional information

Attention is permutation-invariant: shuffling the tokens shuffles the outputs identically; without extra information "dog bites man" = "man bites dog". Positional schemes:

Scheme How Notes
Sinusoidal (original) Add fixed sin/cos vectors of different frequencies to embeddings No parameters; extrapolates poorly in practice
Learned absolute Add a learned vector per position (GPT-2, BERT) Can't go beyond trained length
Relative biases (T5) Add a learned bias to scores based on distance j − i Generalises better
ALiBi Add a fixed penalty −m·(i − j) to scores, slope m per head Extrapolates to longer inputs
RoPE (rotary) Rotate query and key vectors by position-dependent angles Standard in most current LLMs (Llama, Qwen, Mistral, Gemma, DeepSeek)

Rotary position embeddings (RoPE)

Split q and k into 2-D pairs; rotate pair i at position m by angle m·θᵢ, with θᵢ = base^(−2i/d) (base 10,000 originally, often 500,000+ for long-context models). Because rotating both vectors and taking a dot product depends only on the difference of angles:

⟨R(mθ)q, R(nθ)k⟩ = ⟨q, R((n − m)θ)k⟩

the attention score depends on the relative offset n − m, while positions are applied as cheap elementwise operations. Low-frequency pairs encode long-range position, high-frequency pairs short-range.

Python
def rope(x, base=10000.0):
    """x: [..., T, d] with d even. Rotate consecutive pairs by position-dependent angles."""
    T, d = x.shape[-2], x.shape[-1]
    inv_freq = base ** (-np.arange(0, d, 2) / d)                   # θ_i
    angles = np.arange(T)[:, None] * inv_freq[None, :]            # [T, d/2]
    cos, sin = np.cos(angles), np.sin(angles)
    x1, x2 = x[..., 0::2], x[..., 1::2]
    out = np.empty_like(x)
    out[..., 0::2] = x1 * cos - x2 * sin
    out[..., 1::2] = x1 * sin + x2 * cos
    return out

# The score between rotated q (at m) and k (at n) depends only on n − m
q, k = rng.normal(size=8), rng.normal(size=8)
def score(m, n, T=64):
    Qs = rope(np.tile(q, (T, 1))); Ks = rope(np.tile(k, (T, 1)))
    return Qs[m] @ Ks[n]
round(score(3, 7), 6) == round(score(20, 24), 6)                  # True: same offset 4

Context extension (training at 8k, using at 128k+) rescales RoPE frequencies: position interpolation, NTK-aware scaling, YaRN, followed by a short fine-tune on long sequences.

Architecture families

Family Attention Training objective Examples Use
Encoder-only Bidirectional self-attention (no mask) Masked language modelling BERT, RoBERTa, DeBERTa, ModernBERT Classification, NER, embeddings, rerankers
Decoder-only Causal self-attention Next-token prediction GPT series, Llama, Claude, Gemini, Qwen, Mistral, DeepSeek Generation, chat, code, reasoning, agents
Encoder-decoder Encoder bidirectional; decoder causal + cross-attention Span corruption / seq2seq Original Transformer, T5, BART, Whisper Translation, summarisation, speech recognition

Decoder-only models dominate because one simple objective scales, and generation subsumes most tasks.

A complete GPT-style model

Python
import torch, torch.nn as nn, torch.nn.functional as F

class RMSNorm(nn.Module):
    def __init__(self, d, eps=1e-6):
        super().__init__(); self.eps = eps; self.weight = nn.Parameter(torch.ones(d))
    def forward(self, x):
        return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) * self.weight

def rope_cache(T, d_head, base=10000.0, device=None):
    inv = base ** (-torch.arange(0, d_head, 2, device=device).float() / d_head)
    ang = torch.arange(T, device=device).float()[:, None] * inv[None, :]
    return ang.cos(), ang.sin()                                   # [T, d_head/2]

def apply_rope(x, cos, sin):                                      # x: [B, h, T, d_head]
    x1, x2 = x[..., 0::2], x[..., 1::2]
    return torch.stack([x1 * cos - x2 * sin, x1 * sin + x2 * cos], dim=-1).flatten(-2)

class CausalSelfAttention(nn.Module):
    def __init__(self, d, n_heads, n_kv_heads):
        super().__init__()
        self.h, self.kv, self.dh = n_heads, n_kv_heads, d // n_heads
        self.q = nn.Linear(d, n_heads * self.dh, bias=False)
        self.kv_proj = nn.Linear(d, 2 * n_kv_heads * self.dh, bias=False)
        self.o = nn.Linear(n_heads * self.dh, d, bias=False)

    def forward(self, x, cos, sin):
        B, T, _ = x.shape
        q = self.q(x).view(B, T, self.h, self.dh).transpose(1, 2)            # [B, h, T, dh]
        k, v = self.kv_proj(x).view(B, T, 2, self.kv, self.dh).unbind(2)
        k, v = k.transpose(1, 2), v.transpose(1, 2)                          # [B, kv, T, dh]
        q, k = apply_rope(q, cos, sin), apply_rope(k, cos, sin)
        rep = self.h // self.kv                                               # grouped-query attention
        k, v = k.repeat_interleave(rep, dim=1), v.repeat_interleave(rep, dim=1)
        y = F.scaled_dot_product_attention(q, k, v, is_causal=True)           # fused (Flash) kernel when available
        return self.o(y.transpose(1, 2).reshape(B, T, -1))

class SwiGLU(nn.Module):
    def __init__(self, d, hidden):
        super().__init__()
        self.gate, self.up = nn.Linear(d, hidden, bias=False), nn.Linear(d, hidden, bias=False)
        self.down = nn.Linear(hidden, d, bias=False)
    def forward(self, x): return self.down(F.silu(self.gate(x)) * self.up(x))

class Block(nn.Module):
    def __init__(self, d, n_heads, n_kv_heads, hidden):
        super().__init__()
        self.n1, self.attn = RMSNorm(d), CausalSelfAttention(d, n_heads, n_kv_heads)
        self.n2, self.mlp = RMSNorm(d), SwiGLU(d, hidden)
    def forward(self, x, cos, sin):
        x = x + self.attn(self.n1(x), cos, sin)
        return x + self.mlp(self.n2(x))

class GPT(nn.Module):
    def __init__(self, vocab=32000, d=512, layers=8, n_heads=8, n_kv_heads=2, max_len=1024):
        super().__init__()
        self.embed = nn.Embedding(vocab, d)
        self.blocks = nn.ModuleList(Block(d, n_heads, n_kv_heads, int(8 * d / 3)) for _ in range(layers))
        self.norm = RMSNorm(d)
        self.lm_head = nn.Linear(d, vocab, bias=False)
        self.lm_head.weight = self.embed.weight                                # weight tying
        cos, sin = rope_cache(max_len, d // n_heads)
        self.register_buffer("cos", cos, persistent=False); self.register_buffer("sin", sin, persistent=False)
        self.apply(self._init)

    @staticmethod
    def _init(m):                                                              # small init (GPT-2 style)
        if isinstance(m, (nn.Linear, nn.Embedding)):
            nn.init.normal_(m.weight, mean=0.0, std=0.02)

    def forward(self, ids, targets=None):
        B, T = ids.shape
        x = self.embed(ids)
        for blk in self.blocks:
            x = blk(x, self.cos[:T], self.sin[:T])
        logits = self.lm_head(self.norm(x))                                    # [B, T, vocab]
        loss = None
        if targets is not None:
            loss = F.cross_entropy(logits.reshape(-1, logits.size(-1)), targets.reshape(-1))
        return logits, loss

model = GPT(vocab=1000, d=128, layers=4, n_heads=8, n_kv_heads=2, max_len=256)
ids = torch.randint(0, 1000, (2, 64))
logits, loss = model(ids[:, :-1], ids[:, 1:])                # shift by one: predict the next token
logits.shape, round(loss.item(), 2)                          # [2, 63, 1000], ≈ 6.9 = ln(1000): uniform guessing at init
sum(p.numel() for p in model.parameters())                   # 816,768 parameters (tied embeddings counted once)

Verifying that the fused kernel matches the textbook formula:

Python
B, h, T, dh = 2, 4, 16, 32
q, k, v = (torch.randn(B, h, T, dh) for _ in range(3))
scores = q @ k.transpose(-2, -1) / dh ** 0.5
mask = torch.triu(torch.ones(T, T, dtype=torch.bool), diagonal=1)
manual = scores.masked_fill(mask, float("-inf")).softmax(-1) @ v
fused = F.scaled_dot_product_attention(q, k, v, is_causal=True)
torch.allclose(manual, fused, atol=1e-5)                     # True

Cost and long context

  • Compute: attention is O(T²·d) per layer; MLPs are O(T·d²). For short contexts MLPs dominate; beyond T ≈ d attention dominates.
  • Memory: naive attention materialises [h, T, T] scores: 32 heads × 32k × 32k × 2 bytes ≈ 64 GB for one layer: impossible.
  • FlashAttention (Tri Dao, 2022; v2, v3 for Hopper, later versions for Blackwell) computes exact attention in tiles held in fast on-chip SRAM with an online softmax, never materialising the T × T matrix: memory O(T), and much faster because it's bound by memory traffic. F.scaled_dot_product_attention dispatches to such kernels.
  • Training compute rule of thumb: about 6 × parameters × tokens FLOPs (2 forward, 4 backward). A 7B model on 2T tokens: 6 × 7e9 × 2e12 ≈ 8.4e22 FLOPs.

Approaches to long context:

Approach Idea
Sliding-window attention Each token attends to the last w tokens; information propagates further through layers (Mistral, Gemma interleave local and global layers)
Sparse attention Fixed patterns (local + strided + global tokens) or learned selection of relevant blocks (DeepSeek sparse attention)
Linear attention / SSM hybrids Replace softmax attention in some layers with recurrent, constant-state alternatives (chapter 153)
KV-cache compression GQA/MLA, quantised KV, evicting unimportant tokens, attention sinks
Context/ring parallelism Split long sequences across GPUs during training
RoPE scaling + long-context fine-tuning Extend trained length (YaRN etc.)

Lab: attention, from scratch

PyTorch 2.14.1 on the lab machine's CPU, float32. All four experiments use the 6-line attention() function from the Start here section.

Experiment 1: the scaling factor

1,000 random queries, 16 keys each, entries ~ N(0, 1):

d Unscaled max weight / entropy Scaled max weight / entropy
16 0.675 / 0.93 0.239 / 2.37
64 0.844 / 0.41 0.250 / 2.35
256 0.920 / 0.20 0.244 / 2.36
1024 0.966 / 0.08 0.248 / 2.36

Uniform attention over 16 keys has entropy ln 16 = 2.77 nats; scaled scores with unit variance give about 2.36 at every width. In trained models, learned query and key norms can still grow large and cause attention "entropy collapse"; QK-normalisation (layer-norming queries and keys) is one modern fix.

Experiment 2: causality

Text
T = 8 tokens, d = 32; perturb token 5 by +10 in every dimension
max |Δoutput| at positions 0–4: 0.0e+00      at positions 5–7: 33.02
weights of position 2: [0.139, 0.629, 0.232, 0.0, 0.0, 0.0, 0.0, 0.0]

Exactly zero, not merely small, because exp(−∞) = 0. A mask bug (off by one in triu(..., 1)) would let each position see itself or its successor, and the model would learn to copy the answer: training loss collapses towards zero while generation is garbage. Testing causality this way is a cheap unit test for any attention implementation.

Experiment 3: quadratic cost

n Time (one head, d = 64) Score matrix (float32)
256 0.3 ms 0.3 MB
512 1.1 ms 1.0 MB
1,024 11.4 ms 4.2 MB
2,048 163.8 ms 16.8 MB
4,096 466.5 ms 67.1 MB

Time grew faster than 4× per doubling between 1,024 and 2,048, when the score matrix stopped fitting in the CPU's caches; memory movement, not arithmetic, dominated. That observation is the motivation for FlashAttention (tiling the computation so blocks stay in fast memory) and for torch.nn.functional.scaled_dot_product_attention, which picks fused implementations automatically. Multiply by heads, layers and batch size for a real model: 32 heads × 32 layers at n = 4,096 would need 69 GB just for score matrices if they were all stored.

Experiment 4: parameter counts

d_model Attention (4d²) MLP (8d²) Per block
128 0.07 M 0.13 M 0.20 M
768 2.36 M 4.72 M 7.08 M
4,096 67.11 M 134.22 M 201.33 M

GPT-2 small (d = 768, 12 blocks) therefore has about 85 M parameters in its blocks, plus 38.6 M in its 50,257 × 768 token embedding (shared with the output layer), close to its published 124 M. Modern variants change the constants: grouped-query attention shrinks the key/value projections; SwiGLU MLPs use three matrices of about 8d/3 width; mixture-of-experts layers multiply MLP parameters while activating only a few experts per token.

Try it yourself

  1. Implement multi-head attention (8 heads of d/8) and check it gives the same output as nn.MultiheadAttention with the same weights.
  2. Replace your function with F.scaled_dot_product_attention(..., is_causal=True) and time n = 4,096.
  3. Introduce the off-by-one mask bug and train a tiny model on chapter 156's corpus for 200 steps. What happens to the training loss and to generated text?
  4. Count the parameters of a 6-layer, d = 256 model with a 4,096-token vocabulary, then verify with sum(p.numel() for p in model.parameters()) in chapter 156's lab.

Revision sheet: Transformers

Key ideas

  • Embeddings turn tokens into vectors; positional information via learned/sinusoidal embeddings or rotary embeddings (RoPE) applied to queries and keys.
  • Scaled dot-product attention: softmax(QKᵀ/√d)V; masks for causality and padding.
  • Multi-head attention: several heads on lower-dimensional projections, concatenated and projected.
  • Block: (pre-)layer norm → attention → residual add → layer norm → MLP (GELU/SwiGLU) → residual add.
  • Decoder-only (GPT-style, causal) vs encoder-only (BERT, bidirectional) vs encoder–decoder (T5, translation).
  • Cost: O(n²·d) attention, O(n·d²) MLP; parameters ≈ 12·d² per block plus embeddings.
  • Efficiency variants: FlashAttention, KV cache, grouped-query / multi-query attention, sliding-window and sparse attention, mixture of experts.

Numbers to remember

  • Lab: unscaled attention at d = 1024 put 0.966 weight on one key; scaled stayed ≈ 0.25.
  • Lab: a causal mask gave exactly 0.0 change in earlier outputs.
  • Lab: n = 4,096 score matrix = 67 MB per head (float32).
  • GPT-2 small ≈ 124 M parameters (12 blocks × 7.1 M + 38.6 M embeddings).

Pitfalls

  • Missing or off-by-one causal masks (training looks great, generation fails).
  • Forgetting the √d scale; softmax in low precision without max-subtraction.
  • Padding tokens attended to (missing padding mask).
  • Underestimating attention memory at long context.
  • Confusing encoder (bidirectional) and decoder (causal) use cases.

Glossary

  • Query / key / value: what a position asks for / offers as a label / offers as content.
  • Residual stream: the running sum of block outputs passed through the network.
  • RoPE: rotary position embedding, encoding relative position by rotating Q and K.
  • GQA: grouped-query attention; several query heads share one key/value head.
  • Context length: maximum tokens the model attends over.