Every new word an LLM writes re-reads a cache of all earlier words. For Llama-2-70B that cache is 10 GB at 4,096 tokens, and grouped-query attention cuts it to 1.25 GB.
Learn how a Transformer works, which design choices made LLMs practical, and why memory, not arithmetic, is the cost that decides what you can serve.
Pick an attention design, then drag the batch size and the context length. Watch the cache grow past the model itself, then shrink. Then we build, piece by piece, the tokens, attention, position, the cache, and the choices that shrink it.
You need a little matrix multiplication (rows times columns) and a little Python for the code. We build the rest from zero.
Based on Lecture 12 of MIT 6.5940: TinyML and Efficient Deep Learning Computing (Fall 2026), taught by Song Han and the MIT HAN Lab. Lecture slides. Every idea is re-taught here in our own words and devices. It follows Lecture 11, TinyEngine and leads to Lecture 13, LLM Deployment.
Shapes are Llama-2-70B as on the lecture's slides 52 to 56: 80 layers, 64 query heads, head size 128, 16-bit numbers. Grouped-query shares 8 key-value heads, multi-query shares 1. Weights are 70 billion numbers at 2 bytes, 130 GB, where 1 GB is 230 bytes as on the slides. The cache formula is exact. A real server adds some overhead.
Chapter 0
See what LLMs do all day, then see the two flaws that made older networks too slow and too forgetful for language
A chatbot, a translator, a coding assistant and an assistant that reads a photo: the lecture opens with these four. Under all four sits one object, the large language model (LLM). It is a big neural network that reads text and predicts what comes next. Inside every LLM is a Transformer. At each step we ask the course's question: what does it cost, in memory and in time?
Language jobs come in two kinds. A discriminative task reads a whole text and gives one label, such as positive or negative. A generative task writes new text: it reads "As a visual treat, the film is almost" and writes "perfect". A generator writes one word at a time, and each new word joins the input before the model runs again. Chapter 6 shows what that loop does to memory.
A recurrent neural network (RNN) reads words in order. It keeps a small summary, the hidden state, and rewrites it at every word. In "The chef who ... was", the word "chef" must survive every rewrite to reach "was". A convolutional neural network (CNN) slides a small window over the words instead.
| Design | Link the first word to the last | Training on a GPU |
|---|---|---|
| RNN | O(seq_len) steps. LSTM cells help, but the path stays long. | Slow. State n needs state n minus 1, so it takes n steps to reach state n. |
| CNN | Many layers. One layer sees only a few neighbours. | Fast. Every window runs at once. |
| Attention | One layer. | Fast, at the price of N times N pairs. |
Each dot is a word. Blue marks what the last word has seen so far. The first word turns warm when the link is made.
Illustrative: the CNN uses a window of 5 words, so each layer reaches 2 words further on each side. The RNN steps and the CNN layers are counted exactly. The attention cost counts every pair of words, N times N. The lecture's slides 12 and 13 state the RNN facts.
Set the length to 32. The RNN needs 32 steps in a row and the CNN needs 16 layers. Attention links the two words in one layer, at the price of 1,024 pairs. That trade, one hop for N times N pairs, runs through the rest of this lesson.
Eleven chapters follow. Each builds a part of the instrument at the top of the page.
Chapter 1
Follow one sentence through the tokenizer and the embedding table until a network can use it
A network multiplies numbers, not words. So text becomes numbers in two steps: cut it into tokens, then look up a row of numbers for each token.
A token is a piece of text the model treats as one unit. A tokenizer cuts text into tokens and gives each an integer ID; the list of all tokens is the vocabulary. Think of Lego bricks: a common word is one big brick, a rare word several small ones. Whole words would miss new names, and letters would make texts long.
On the lecture's slide, 110 words become 162 tokens, 1.47 per word. Attention compares every pair, so 162 tokens make 26,244 pairs where 110 words suggest 12,100: a factor of 2.2.
Each box is a token with its ID. The outlined token is the one being looked up. Switch the view between the one-hot vector and the embedding row.
Illustrative: 25 made-up bricks, and 4 numbers per row from a fixed formula, not training. The read-out sizes use the 7B shapes on slide 66 (vocabulary 32,000, width 4,096).
Try "Rare words": "unbelievable" breaks into "un", "believ" and "able". An unseen word still gets a code.
A one-hot vector has one slot per vocabulary entry, all 0 but one. It is huge and says nothing about meaning: "good" is as far from "great" as from "cabbage". A word embedding is a short trained row of numbers per token, so tokens that behave alike get similar rows. Word2Vec and GloVe are pre-trained ones.
Name the parts: token ID t, vocabulary size V, row width d, the table E and the token's row e.
e equals one-hot of t times E, which equals E row t.
Multiply the one-hot of t by E. Every row meets a 0 except row t, so e is row t. Code skips the multiply and reads the row.
Slide 66's 7B model has V = 32,000 and d = 4,096. Token t = 2,317 gives e = row 2,317: 4,096 numbers. E holds 131 million numbers, 262 MB at 2 bytes.
N token IDs go in; an N × d matrix comes out.
Symptom: a 3,000-word document fails with "context length exceeded" on a 4,096-token model. Measure: at 1.47 tokens per word it is about 4,400 tokens. Fix: count with the model's own tokenizer.
pythonimport torch, torch.nn as nn V, d = 32000, 4096 E = nn.Embedding(V, d) # the table, shape (V, d), trained with the model ids = torch.tensor([[1, 2317, 88, 9]]) # (batch=1, N=4) integers from the tokenizer x = E(ids) # (1, 4, 4096): one row of d numbers per token # same result, slower: one_hot(ids, V).float() @ E.weight
Chapter 2
Build queries, keys and values from one matrix, then add heads and a mask that hides the future
"The robot must obey the orders given to it." To read "it", you look back and find "robot". The lecture frames this as a video search. The engine compares a query (the search text) with keys (the titles) and returns the best values (the videos). Self-attention runs this search with every word as both searcher and video.
Start from Chapter 1's token rows, X, shape N × d. Three learned matrices, WQ, WK and WV, turn X into queries Q, keys K and values V.
Q equals X times W-Q, K equals X times W-K, V equals X times W-V. Out equals softmax of Q times K-transpose over root d, all times V.
Score every query against every key. Divide by root d. Softmax each row into weights. Each output row is that weighted mix of value rows.
Made-up: d = 4, query (1, 1, 1, 1), keys (1, 1, 1, 1), zeros, zeros. Dot products 4, 0, 0 over root d = 2 give 2, 0, 0; softmax gives 0.787, 0.107, 0.107. Values (1, 0), (0, 1), (1, 1) give Out = (0.893, 0.213): a soft lookup.
The N by N grid makes attention O(N2): double the text, four times the numbers. Why root d? A dot product of d numbers of spread 1 has spread about root d, 11 for d = 128. Scores that large push softmax to one weight near 1, where slopes are flat and training stalls.
Multi-head attention (MHA) runs H heads side by side. Each has its own three matrices on d/H numbers: 128 for d = 4,096 and H = 32. A matrix WO blends the joined outputs. One head can link "it" to "robot" while another links each word to its left neighbour.
A causal mask hides the future from a generator: before softmax, add minus infinity wherever the key comes after the query. The lecture contrasts this causal attention with global attention, which has no mask.
Row i is the query word, column j the key word; darker means more weight. Pick "it" with Head A: most weight lands on "robot". Then switch the mask.
Toy: we chose the 2-number vectors by hand. Scores, mask and softmax are exact. Without the mask, Head B lets the first word see the last.
pythonimport torch, torch.nn.functional as F def attention(Q, K, V, causal=True): # Q,K,V: (B, H, N, d_h) d_h = Q.shape[-1] scores = Q @ K.transpose(-2, -1) / d_h**0.5 # (B, H, N, N): the quadratic part if causal: N = scores.shape[-1] keep = torch.tril(torch.ones(N, N, dtype=torch.bool)) scores = scores.masked_fill(~keep, float('-inf')) # hide the future return F.softmax(scores, dim=-1) @ V # (B, H, N, d_h)
Symptom: training loss falls near zero, then the model writes nonsense. Cause: with no mask, word t reads word t+1, the answer itself. Measure: change a future token; earlier outputs must not move. Fix: mask every decoder layer.
Chapter 3
Wrap attention with a feed-forward network, normalization and shortcuts, then teach the model where each word sits
Attention only mixes rows. The feed-forward network (FFN) works on each token alone: if attention is a meeting, the FFN is each word thinking at its desk. Name the parts: a token's row x, matrices W1 and W2, biases b1 and b2.
FFN of x equals max of zero and x W-one plus b-one, times W-two, plus b-two.
Widen x with W-one and add b-one. Turn every negative number into 0. Narrow back with W-two and add b-two.
Made-up hidden values 1.3 and −0.7 leave ReLU as 1.3 and 0. With d = 4,096, W-one and W-two hold 4,096 × 16,384 = 67 million weights each: 134 million in all.
Attention adds four d by d matrices, so a block holds about 12d2, two thirds in the FFN. GPT-3 (d = 12,288, 96 layers): 12 × 12,2882 × 96 ≈ 174 billion, near its 175 billion.
Two more parts keep a deep stack trainable:
| Part | What it does | Why |
|---|---|---|
| Layer normalization (LN) | For each token, subtracts the mean of its d numbers, divides by their spread, then applies a learned scale and shift. | Stops the numbers drifting through many layers. |
| Residual connection | Adds a layer's input to its output: x + f(x). | A layer with nothing to add passes the signal on, and gradients flow back the same way. |
| Post-norm against pre-norm | Post-norm, the original, puts LN after the add. Pre-norm puts LN first inside the branch. | The slide: pre-norm is more popular now because it trains more stably. |
Attention and the FFN see a bag: "dog bites man" and "man bites dog" look alike. The lecture calls this set encoding (bad), not sequence encoding (good). A positional encoding adds an absolute code to each row. Name the parts: position t, code pt, pair k with speed ωk.
p-t at slot 2k equals sine of omega-k times t; p-t at slot 2k plus 1 equals cosine of omega-k times t; omega-k equals one over ten thousand to the power 2k over d.
Multiply pair k's speed omega-k by the position t. Put the sine in the even slot, the cosine in the odd slot.
With d = 4: omega-0 = 1 and omega-1 = 1 / 100002/4 = 0.01. Position t = 1 gives (0.841, 0.540, 0.010, 1.000). Position 0 gives (0, 1, 0, 1).
Top: each position's code (rows), blue for plus, yellow for minus. Bottom: how much the chosen code resembles every other. Near positions look alike.
The lecture's formula, exact, with d = 32 for display. Similarity is the dot product of two codes over 16, its largest value, so a position scores 1.00 against itself.
A full model: embeddings plus positions, N identical blocks, and a linear layer that scores each vocabulary token.
pythonimport numpy as np def sinusoid(N, d): # position codes, shape (N, d) t = np.arange(N)[:, None]; k = np.arange(d // 2)[None, :] w = 1.0 / 10000 ** (2 * k / d) P = np.zeros((N, d)); P[:, 0::2] = np.sin(w * t); P[:, 1::2] = np.cos(w * t) return P def block(x, attn, ffn, ln1, ln2): # pre-norm block, x: (N, d) x = x + attn(ln1(x)) # tokens trade notes return x + ffn(ln2(x)) # each token thinks alone; still (N, d)
Symptom: "who bit whom?" gets one answer for both word orders. Measure: shuffle the input rows, run the stack, unshuffle and compare; a difference of 0 means no order. Fix: add pt to each row before block 1.
Chapter 4
Compare the encoder-decoder, the encoder-only and the decoder-only Transformer through one picture: the attention mask
Part II of the lecture opens with a fact: most of the original design survived. The community changed four things, and they set the next chapters:
The encoder reads the whole prompt with global attention. The decoder writes one token at a time with causal attention. In cross-attention, decoder queries read encoder keys and values, like a translator glancing back at the French while writing English.
| Family | Mask | Training game | Used for |
|---|---|---|---|
| Encoder-decoder (T5) | Encoder global, decoder causal, plus cross-attention | Text in, text out: "Translate English to German: That is good." gives "Das ist gut." | Translation, summaries, any task cast as text |
| Encoder-only (BERT) | Global | Masked language modeling (MLM): hide 15% of tokens and guess them. Next sentence prediction (less used). | Fine-tuned for labels and search. It never learned to continue a text. |
| Decoder-only (GPT) | Causal | Predict the next word | Writing. GPT-2 was fine-tuned; larger models run zero-shot or few-shot. |
Every large model in this lesson is decoder-only. Name the parts. The real token at position i is ui, and the model's weights are Θ. P is the probability the model gives that token after reading only the earlier ones. L is the loss over N positions.
L equals minus one over N times the sum over i of log P of u-i, given u-one through u-i-minus-one, with weights Theta.
At each position i, take the log of P, the probability the model gave the real token u-i. Average over the N positions and flip the sign. That is L.
Made-up: the model gives three real tokens P = 0.5, 0.25 and 0.1. Minus log gives 0.69, 1.39 and 2.30, so L = 1.46. Sure and right every time would give 0.
A filled cell means the row word may look at the column word. Pick a family and compare the pictures.
Exact counts for the length you pick. For T5 the decoder writes a reply of half that length, rounded down. The examples are from slides 38 to 41.
Pick GPT at 8 words: 36 of 64 cells fill. BERT fills all 64. So one GPT pass over 1,000 tokens gives about 1,000 targets; BERT's hidden 15% give about 150.
pythonimport torch N = 6 global_mask = torch.ones(N, N, dtype=torch.bool) # BERT, T5 encoder: everyone sees everyone causal_mask = torch.tril(global_mask) # GPT, T5 decoder: only the past and self print(global_mask.sum().item(), causal_mask.sum().item()) # 36 and 21 # T5 cross-attention: queries (decoder, Nd rows) x keys (encoder, Ne rows) -> (Nd, Ne), no mask
Symptom: an encoder-only model asked to continue a story returns one fill-in word, or nonsense. Cause: BERT guesses hidden words from both sides, and the end of a text has no right side. Fix: write with a decoder; keep encoders for labels and search.
Chapter 5
Encode the distance between words, not their address, then stretch the window with a half-speed rotation
A model trained on texts of up to 2,048 tokens gets a 4,000-token document. It never saw position 3,000, and the answer degrades. The slide's limits: 2k for LLaMA, 4k for Llama-2, 8k for GPT-4.
Chapter 3's sine codes name an absolute position, like a house number. A relative code names the distance, like "three doors down". A rule such as "attend to the word before me" then works at any position.
| Encoding | Where position enters | What it reaches |
|---|---|---|
| Absolute | Added to the input embeddings | Q, K and V, through the whole network |
| Relative | The attention scores only: a bias, or a change to Q and K | Not V. The hope is "train short, test long", which the slide says does not always hold. |
ALiBi (attention with linear biases) subtracts a hand-set slope m times the distance from each score. Four equal scores at distances 0 to 3 with m = 0.5 get biases 0, −0.5, −1, −1.5, and weights 0.455, 0.276, 0.167, 0.102.
LLaMA uses rotary position embedding (RoPE). Cut each query and key into d/2 pairs, points on a plane. Turn pair i by the position times θi = 10000−2(i−1)/d: early pairs fast, late pairs slowly. Name the parts: query q at position m, key k at position n, and R, a turn by an angle.
The dot product of RoPE of q at m and RoPE of k at n equals q-transpose times R of n minus m times theta, times k.
Turn the query by m times theta and the key by n times theta. The angle between them is n minus m times theta, and the score depends only on that angle.
Made-up: one pair, theta = 0.5, q = k = (1, 0). At m = 3 and n = 1 the turns are 1.5 and 0.5 rad, 1.0 rad apart: score cos 1.0 = 0.540. At m = 10 and n = 8 the gap is still 2, and the score is still 0.540.
RoPE leaves V alone. It also stretches the window. Position interpolation halves every θi to double the window, so position 4,000 gets the angle position 2,000 had. The slide extends LLaMA from 2k to 32k this way.
Rotate: try m = 7, n = 3, then m = 12, n = 8; the angle stays. Stretch: drag past 2,048; the plain arrow turns red, the interpolated one stays inside.
One pair, q and k of length 1. Rotate uses θ = 0.5 rad per position. Stretch uses a slow pair, θ = 0.0015, and 2,048 trained positions (slide 47). Angles are exact.
pythonimport numpy as np def rope(x, m, scale=1.0): # x: (d,) one query or key at position m d = x.shape[0]; th = 10000.0 ** (-2 * np.arange(d // 2) / d) a = m * scale * th # scale=0.5 doubles the window (interpolation) x1, x2 = x[0::2], x[1::2] # d/2 pairs, each a 2D point out = np.empty_like(x) out[0::2] = x1 * np.cos(a) - x2 * np.sin(a) out[1::2] = x1 * np.sin(a) + x2 * np.cos(a) return out # rope(q,m) @ rope(k,n) depends on m - n only
Symptom: a model trained to 2,048 tokens reads the first pages of a long prompt well, then degrades. Measure: at position 3,000 and θ = 0.0015, the slow pair sits at 4.50 rad, past the 3.07 rad it saw. Fix: interpolate to 2.25 rad, at the price of packing neighbours closer.
Chapter 6
Store every earlier key and value so generation stays fast, count the bytes, then share heads to shrink them
To write token 501, attention needs the keys and values of all 500 earlier tokens. Rebuilding them every step is like re-reading a book before each new sentence.
Under the causal mask, old keys and values never change. The KV cache stores them for all earlier tokens, in every layer; each step needs only the current query. Each step:
Each square is a token. Warm squares have their key and value computed in this step. Yellow squares are read from the cache. Press the button to write a token.
Illustrative: an 8-token prompt, then one token per press, up to 40. Counts are exact, for one layer. Write 20 tokens with the cache off (378 projections), then on (28).
After T tokens, recomputing projects 1 + 2 + … + T tokens: 500,500 for T = 1,000, against 1,000 with the cache. But every step still reads every cached row.
Name the parts: batch size B, layers L, key-value heads Hkv, head size dh and tokens so far N.
Cache equals B times L times H-k-v times d-h times N, times 2, times 2 bytes.
Multiply B, L, H-k-v, d-h and N. Double for keys and values. Double again for 2 bytes per number.
Llama-2-70B with multi-head attention (slide 53): B = 1, L = 80, H-kv = 64, d-h = 128, N = 4,096 gives 10.7 billion bytes, 10 GB. At B = 16 it is 160 GB, more than the 130 GB of weights.
Each step reads the whole cache once. At about 2 TB/s (an A100 80 GB), 10 GB takes 5.4 ms: memory, not arithmetic, sets the speed.
The fix is to shrink Hkv. In multi-query attention (MQA, Shazeer 2019) all query heads share one key-value head. In grouped-query attention (GQA, Ainslie 2023) each group of query heads shares one, typically query heads / 8.
| Design | Key-value heads (Llama-2-70B) | Cache at 4,096 tokens, batch 1 |
|---|---|---|
| MHA | 64, one per query head | 10 GB |
| GQA | 8, so WK and WV shrink from 8,192 by 8,192 to 8,192 by 1,024 | 1.25 GB, 8 times smaller |
| MQA | 1 | 0.16 GB, 64 times smaller |
| Mistral-7B (GQA) | 8 for 32 query heads | 128 KB per token, a quarter of Llama-2-7B's 512 KB |
Queries keep their shape. On the slide's table (30B model, 150B tokens), GQA stays close to MHA; MQA is a little lower on most tasks.
The 64 squares are query heads. Same colour means they share one key-value head. The bar below is the cache, against multi-head at full length.
Llama-2-70B at 2,048 tokens and batch 64, as on slide 56. Exact sizes, 1 GB = 230 bytes. Weights: 130 GB.
pythondef kv_bytes(B, L, Hkv, dh, N, nbytes=2): return B * L * Hkv * dh * N * 2 * nbytes # the 2 is K and V GB = 2 ** 30 print(kv_bytes(1, 80, 64, 128, 4096) / GB) # 10.0 (MHA) print(kv_bytes(1, 80, 8, 128, 4096) / GB) # 1.25 (GQA, 8x smaller) # GQA: expand each of the Hkv key heads to serve its group of query heads # K: (B, Hkv, N, dh) -> K.repeat_interleave(Hq // Hkv, dim=1) -> (B, Hq, N, dh)
Symptom: a 70B server runs at batch 8 and runs out of memory at batch 32. Measure: with MHA at 2,048 tokens, 32 texts add 160 GB. Fix: GQA cuts it to 20 GB.
Chapter 7
Replace one wide layer with two parallel ones, where one decides how much of the other passes
A plain FFN plays every channel at a fixed volume. A gated linear unit (GLU) adds a second signal that works the faders, channel by channel and token by token. The slide's headline: replacing the vanilla FFN with a GLU improves Transformers. LLaMA uses the SwiGLU version.
| Bend | Formula | At x = −1 |
|---|---|---|
| ReLU | x if x > 0, else 0 | 0 |
| GeLU | x / (1 + e−1.702x), the slide's form | −0.15 |
| Swish | x / (1 + e−x), x times the sigmoid of x | −0.27 |
GeLU and Swish are smooth and let small negative values through. Name the parts of the gate: the token row x, two widening matrices W and V, and a narrowing matrix W2. The hidden width is h.
FFN-SwiGLU of x equals Swish of x W, times element by element x V, all times W-two.
Widen x twice, with W and with V. Pass the first through Swish to make the gate. Multiply gate and content channel by channel, then narrow with W-two.
Made-up, one channel: xW = 2 and xV = 1.5. Swish(2) = 2 / 1.135 = 1.762, so the channel gives 2.64: open. With xW = −2, Swish gives −0.238 and the channel gives −0.36: nearly shut.
Curves: slide x and read the three bends. Gate: move g from 3 to −3 and watch the same content shrink.
Exact values from the formulas on this page. In the Gate view, one channel stands for the h channels of a real layer.
A gate needs three matrices, so match sizes. Vanilla: two d by 4d matrices, 8d2. SwiGLU with h = 8d/3: three d by 8d/3 matrices, also 8d2. That is the 8/3 d on the slide. At equal size, Shazeer's 2020 table (slide 59) gives log-perplexity, lower is better:
| Training steps | FFN with ReLU | SwiGLU |
|---|---|---|
| 65,536 | 1.997 | 1.944 |
| 524,288 | 1.677 | 1.636 |
pythonimport torch, torch.nn.functional as F class SwiGLU(torch.nn.Module): def __init__(self, d, h=None): super().__init__(); h = h or int(8 * d / 3) # 8d/3 keeps the weights equal to a 4d FFN self.W = torch.nn.Linear(d, h, bias=False) # gate path, (d, h) self.V = torch.nn.Linear(d, h, bias=False) # content path, (d, h) self.W2 = torch.nn.Linear(h, d, bias=False) # narrow back, (h, d) def forward(self, x): # x: (N, d) return self.W2(F.silu(self.W(x)) * self.V(x)) # silu is Swish with slope 1
Symptom: you swap in SwiGLU at hidden width 4d, and it wins but is bigger. Measure: three d by 4d matrices make 12d2, 1.5 times the FFN. Fix: set the hidden width to 8d/3.
Chapter 8
See what size unlocked, read the recipe of the open models, and learn how to spend a training budget between model and data
Part III of the lecture is a tour: every earlier choice appears in a real model. Then the course's question: with fixed compute, how big should the model be?
On made-up arithmetic ("1 + 1 -> 3") or unscrambling "sohpto", small models score at chance, then scores climb fast past a size. The lecture calls these emergent abilities. GPT-3, at 175 billion weights, does new tasks with no fine-tuning. In zero-shot use the prompt describes the task: "Translate English to French: cheese =>". In few-shot use it also shows solved examples. This is in-context learning: no weight changes, only text.
Larger models use examples better, and with enough examples a prompt with no task description catches up. Every example is cache: ten examples of 50 tokens add 500 tokens to every request.
| Model | From the slides |
|---|---|
| LLaMA | 7B, 13B, 33B, 65B. Decoder-only, pre-norm, SwiGLU, RoPE. 7B: width 4,096, 32 heads, 32 layers, vocabulary 32k, context 2,048. 65B: width 8,192, 64 heads, 80 layers. |
| Llama 2 | Context 2k to 4k. Training text 1T or 1.4T to 2T tokens, no sign of saturation. 70B uses GQA: 64 heads, 8 key-value heads. Llama-2-chat, instruction-tuned. |
| Llama 3 | Training text 1.8T to 15.6T multilingual tokens; 50 times the compute of Llama 2; 405B flagship. Context 8K base, 128K instruction-tuned. Post-training: supervised fine-tuning, rejection sampling, DPO. |
| Mistral-7B | Width 4,096, 32 heads, 8 key-value heads, 32 layers, context 8k. Beats Llama-2-13B and Llama-34B. Sliding window attention, dropped from v2 on. |
Check "7B" with Chapter 3's count: 12 × 4,0962 × 32 = 6.44 billion. Two 32,000 by 4,096 embedding tables add 0.26 billion, for 6.70 billion.
Training costs about 6 operations per weight per token. Name the parts: the training compute C, the number of weights N (here N counts weights, not tokens) and the training tokens D.
C equals six times N times D.
Multiply the weights N by the tokens D and by 6 to get the bill C. For a fixed C, more weights means fewer tokens.
Chinchilla's 10B row: 6 × 1010 × 2.05 × 1011 = 1.23 × 1022, as on slide 70. Llama-2-7B: 6 × 7 × 109 × 2 × 1012 = 8.4 × 1022.
The Chinchilla law: for a fixed C, scale model and data together, about 20 tokens per weight. Llama-2-7B's budget with D = 20N gives 120N2 = 8.4 × 1022: N = 26.5 billion, D = 530 billion. The slide's twist: that counts only training, and serving cost grows with N. So Llama-2-7B trains smaller and longer, 286 tokens per weight, and is 3.8 times cheaper to serve.
Pick a budget and slide the model size; tokens follow. The dashed line is 20 tokens per weight. For Llama-2-7B's budget, 26B meets it; Llama-2-70B sits near it, at 29.
Budget C = 6 × weights × tokens (7B and 70B at 2T tokens, 1B at 20.2B). White dots are rows of the table on slide 70. It shows the trade, not accuracy.
pythondef tokens_for(C, N): return C / (6 * N) # fixed budget: more weights, fewer tokens def chinchilla_N(C, k=20): return (C / (6 * k)) ** 0.5 # D = k N => 6 k N^2 = C C = 6 * 7e9 * 2e12 # Llama-2-7B: 8.4e22 print(chinchilla_N(C) / 1e9, tokens_for(C, chinchilla_N(C)) / 1e9) # 26.5 B weights, 530 B tokens
Symptom: you pick a model by its parameter count, and a smaller one beats it. Measure: Mistral-7B beats Llama-2-13B; Llama-2-7B read 286 tokens per weight, not 20. Fix: compare data, recipe and serving cost too.
Chapter 9
Compare two ways to feed a picture to an LLM, and count what each way costs in sequence length and cache
You photograph a receipt and ask how much tax you paid. Part IV starts here, with GPT-4V reading pictures. The picture must become rows of d numbers, in one of two ways:
| Way | Where the picture goes | Examples |
|---|---|---|
| Cross-attention | New layers inside the LLM read it | Flamingo: learns from interleaved pictures and text, and holds a visual dialogue. |
| Visual tokens | Its rows join the text tokens as input | PaLM-E: images in an <img> slot, robot states or 3D scenes in an <emb> slot. RT-2: also writes robot control signals as tokens. VILA: explains a chair flying off a truck on a highway and says to stop, a driving "corner case". |
Flamingo's LLM and vision encoder are frozen: their weights never change. Only new layers between the LLM layers learn. First a Perceiver Resampler squeezes the picture: a few learned queries attend over the visual tokens joined with themselves. Slide 75: 27 visual tokens and 5 queries make 32 keys, a 5 by 32 map, and 5 tokens out.
Then gated cross-attention lets the text read those 5 tokens. Name the parts: the text row x, what it reads from the picture, CrossAttn(x), and the result y. A learned number α starts at 0.
y equals x plus tanh of alpha times cross-attention of x.
Read from the picture. Scale what you read by tanh of alpha. Add it to x. While alpha is 0, nothing from the picture gets through.
Made-up: x = 1.0 and CrossAttn(x) = 2.0. At alpha = 0, y = 1.0, the plain LLM. At alpha = 0.5, tanh gives 0.462 and y = 1 + 0.462 × 2 = 1.92.
Each new layer has two such gates, after cross-attention and after a new FFN, both started at 0 (slide 76). So training starts from the original LLM, and random visual signal cannot wreck its language.
A vision encoder, often a ViT, gives one vector per image patch, and a projector maps each to width d. The LLM reads these rows with ordinary self-attention, beside the text. A 224 by 224 picture in 16 by 16 patches gives 196 tokens.
The cost: each visual token is one more cache entry. At 512 KB per token (Llama-2-7B), 196 tokens add 98 MB per request. Flamingo's text sequence keeps its length.
Resampler: learned queries read the visual tokens. Two ways: compare what each way adds for a 100-token text prompt.
Shapes from slide 75; the weights come from made-up random vectors, so the pattern means nothing. Two ways uses 512 KB per token (slide 52) and an illustrative 100-token prompt.
Drag the visual tokens to 64: the output stays at 5. In "Two ways", the visual-token sequence grows token for token; the cross-attention one does not.
pythonimport torch, torch.nn.functional as F def resample(vis, queries): # vis (27, dim), queries (5, dim) learned kv = torch.cat([vis, queries], dim=0) # (32, dim): keys and values att = F.softmax(queries @ kv.T / kv.shape[-1] ** 0.5, dim=-1) # (5, 32) return att @ kv # (5, dim): always 5 tokens out def gated_cross(x, vis5, attn, alpha): # x: text states (N, dim); alpha starts at 0 return x + torch.tanh(alpha) * attn(q=x, kv=vis5) # tanh(0)=0: starts as the plain LLM
Symptom: a prompt with eight images leaves little room for the question. Measure: 8 × 196 = 1,568 visual tokens, leaving 480 of a 2,048-token window, and 784 MB of cache. Fix: resample each image to a few tokens, or lower the resolution.
Chapter 10
Add many FFNs, let a router send each token to a few of them, and watch what happens when an expert gets too busy
A hospital does not send every patient to every doctor. A front desk sends each one to a specialist, so the hospital can hire hundreds of doctors while each visit stays cheap. The slide's promise: use only part of the weights for each token, and grow the total without raising the cost per token.
Mixture of experts (MoE) replaces the FFN of a block with E copies, the experts, each with its own weights. A router, a linear layer with softmax, scores the experts for each token. In the Switch Transformer the token goes to the top expert. Its output is multiplied by its probability, so the router learns too.
With E = 8 experts of 8d2 weights each, the layer holds 64d2, yet each token runs one expert. The slide's plot: more experts, lower loss. But all E experts must sit in memory, because the next token may need any of them.
If the router favours one expert, it gets most tokens while the others idle, and hardware wants fixed-size batches. So each expert gets a capacity, the most tokens it takes per batch. Name the parts: the tokens per batch T, the number of experts E and the capacity factor C, a slack multiplier.
Capacity equals T over E, times C.
Split the T tokens evenly over the E experts. Multiply by C for slack. Round down to whole tokens.
Slide 85: T = 6 and E = 3. With C = 1, capacity = 6 / 3 × 1 = 2. With C = 1.5, it is 3.
On the slide the router wants 3 tokens for expert 1, 2 for expert 2 and 1 for expert 3. At C = 1, expert 1 takes 2 and skips one token, which passes on through the residual shortcut, untouched. At C = 1.5 no expert skips a token, but experts 2 and 3 have 1 and 2 empty slots, which still cost compute.
Each row is a token, each column an expert. Lines show where the router sends each token. Slots are the capacity. A red outline marks a skipped token.
Toy: made-up router scores send 3, 2 and 1 tokens to experts 1, 2 and 3, as on slide 85. Capacity rounds down to a whole token.
pythonimport torch, torch.nn.functional as F def switch_ffn(x, Wr, experts, C=1.0): # x: (T, d), Wr: (d, E) T, E = x.shape[0], len(experts) p = F.softmax(x @ Wr, dim=-1) # router probabilities (T, E) pick = p.argmax(-1); cap = int(T / E * C) # top-1 expert per token, and the capacity out = x.clone() # skipped tokens keep x: the residual path for e, ffn in enumerate(experts): idx = (pick == e).nonzero().flatten()[:cap] # the first `cap` tokens that chose expert e out[idx] = x[idx] + p[idx, e:e+1] * ffn(x[idx]) # gate by the router probability return out
Symptom: answers get worse on batches where many tokens share a topic, such as a page of code. Measure: 3 of 6 tokens wanting one expert at C = 1 means 1 in 6, 17%, skips the layer. Fix: raise C to 1.5, or route by expert choice.
Chapter 11
Keep the numbers, the questions to ask of any Transformer, and one block of code that holds the whole lecture
The lecture's last slide lists four parts: Transformer basics, design variants, LLMs and multi-modal models. One story joins them. Generation caches keys and values, and the cache, not the arithmetic, sets the bill. Grouped heads, rotary position, gated FFNs, small models trained long and sparse experts each shrink that bill or buy more for it.
| What | The number | Where from |
|---|---|---|
| A tokenizer's ratio | 110 words became 162 tokens (1.47 per word) | Slide 16 |
| Original Transformer (big) | 28.4 BLEU English to German, 41.8 English to French; best earlier ensembles 26.36 and 41.29. Training: 2.3 × 1019 operations against 7.7 × 1019 (English to German). BLEU scores closeness to human translations. | Slide 34 |
| Attention matrix | N by N per head, so O(N2) | Slide 21 |
| Weights in one block | 4d2 attention + 8d2 FFN = 12d2 | Derived from slide 27 |
| KV cache per token | 512 KB (Llama-2-7B), 800 KB (13B), 2.5 MB (70B with MHA) | Slide 52 |
| 70B cache at 4,096 tokens | 10 GB at batch 1, 160 GB at batch 16 | Slide 53 |
| Shrinking the cache | GQA with 8 key-value heads is 8 times smaller, MQA 64 times | Slides 55 and 56 |
| SwiGLU width | Hidden 8d/3 keeps weights equal to a 4d FFN | Slide 59 |
| FFN against SwiGLU | Log-perplexity 1.997 against 1.944 (65,536 steps); 1.677 against 1.636 (524,288 steps) | Slide 59, Shazeer 2020 |
| Position interpolation | Halve every θ to double the window | Slide 47 |
| Llama 2 | 4k context, 2T tokens, 70B with 64 heads and 8 key-value heads | Slide 67 |
| Llama 3 | 1.8T to 15.6T tokens, 405B flagship, 8K base and 128K tuned context | Slide 68 |
| GQA accuracy | Close to MHA on a 30B model trained on 150B tokens; MQA a little lower | Slide 57 |
| Chinchilla | About 20 tokens per weight; training compute 6 × weights × tokens | Slide 70 |
| Perceiver Resampler | 27 visual tokens + 5 queries = 32 keys, a 5 by 32 map, 5 tokens out | Slide 75 |
| Flamingo gates | Two tanh gates per new layer, both started at 0 | Slide 76 |
| MoE capacity | tokens per batch / experts × C; 6 / 3 × 1 = 2 | Slide 85 |
Ask these of any new Transformer, in order.
One decode step of one decoder layer: grouped-query attention, rotary position, a KV cache and a gated FFN. Shapes are in the comments.
pythonimport torch, torch.nn.functional as F def rope(x, pos, base=10000.0): # x: (heads, dh); rotate each pair by pos * theta_i dh = x.shape[-1]; th = base ** (-2 * torch.arange(dh // 2) / dh) c, s = torch.cos(pos * th), torch.sin(pos * th) x1, x2 = x[..., 0::2], x[..., 1::2] return torch.stack([x1 * c - x2 * s, x1 * s + x2 * c], -1).flatten(-2) def decode_step(x, L, cache, pos, Hq, Hkv, dh): # x: (d,) the newest token's row h = L.ln1(x) q = (h @ L.Wq).view(Hq, dh); k = (h @ L.Wk).view(Hkv, dh); v = (h @ L.Wv).view(Hkv, dh) q, k = rope(q, pos), rope(k, pos) # position acts on q and k only cache.k.append(k); cache.v.append(v) # the KV cache grows by Hkv * dh numbers each K = torch.stack(cache.k).repeat_interleave(Hq // Hkv, dim=1) # (N, Hq, dh): share each kv head V = torch.stack(cache.v).repeat_interleave(Hq // Hkv, dim=1) att = F.softmax(torch.einsum('hd,nhd->hn', q, K) / dh ** 0.5, dim=-1) # (Hq, N), no mask needed x = x + torch.einsum('hn,nhd->hd', att, V).reshape(-1) @ L.Wo # back to (d,) h = L.ln2(x) return x + (F.silu(h @ L.W) * (h @ L.V)) @ L.W2 # SwiGLU, width 8d/3
This lecture sets the vocabulary that the rest of the course leans on. The cache and the bandwidth story continue in Lecture 13, LLM Deployment and in Lecture 15, Long-Context LLMs. The vision Transformers behind visual tokens are in Lecture 18. Behind us, Lecture 11, TinyEngine showed how small models run on tiny chips.
For more depth on single topics, see the Transformer from zero, attention variants, FlashAttention, tokenization, mixture of experts and the Chinchilla paper.
Now press Teach and explain, from memory, why the KV cache exists, how big it is for a model you pick, and what grouped-query attention changes. Then go back to the memory bars at the top and drag the batch size once more.