Efficient Transformers and LLMs

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.

Fill the memory of a 70B server

16
4,096

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

Why Language Models Need a New Kind of Network

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.

The era before Transformers

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.

DesignLink the first word to the lastTraining on a GPU
RNNO(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.
CNNMany layers. One layer sees only a few neighbours.Fast. Every window runs at once.
AttentionOne layer.Fast, at the price of N times N pairs.

Link the first word to the last

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.

20 words

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.

The road

Eleven chapters follow. Each builds a part of the instrument at the top of the page.

  1. Tokens and embeddings: how text becomes numbers a network can use.
  2. Self-attention: queries, keys, values, heads and the causal mask.
  3. The Transformer block: FFN, LayerNorm, residuals and position codes.
  4. Three families: encoder-decoder, encoder-only and decoder-only.
  5. Relative position: ALiBi, RoPE and a longer context window.
  6. The KV cache: what it costs, and how MQA and GQA shrink it. This is the top of the page.
  7. Gated linear units: a better FFN at the same size.
  8. Large language models: GPT-3, LLaMA, Mistral and the Chinchilla law.
  9. Models that see: Flamingo, PaLM-E and RT-2.
  10. Mixture of experts: a bigger model at the same cost per word.
  11. The field guide: numbers, code and where to go next.
A sentence has 200 words. Why is an RNN slow to train on it, even on a GPU with thousands of workers?

Chapter 1

Words Become Tokens, and Tokens Become Rows of Numbers

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.

Step one: cut the text into tokens

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.

Cut, number, look up

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.

1

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.

Step two: a token becomes a vector

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.

Say it aloud

e equals one-hot of t times E, which equals E row t.

e
e the embedding of the token: a row of d numbers.
onehot(t)
one-hot of t a vector with V slots, all 0 except a 1 in slot t.
·
times a matrix product: the V slots meet the V rows of the table.
E
E the embedding table, V rows by d columns of trained numbers.
E[t]
E row t the one row of the table that belongs to token t.
In plain words

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.

With numbers

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.

The failure: counting words, not tokens

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
A tokenizer turns a 500-word text into 735 tokens. By what factor does the number of attention pairs exceed what 500 words would suggest?

Chapter 2

Self-Attention Lets Every Word Look at Every Other Word

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.

One matrix in, three out

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.

Say it aloud

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.

X
X the token rows: N tokens, d numbers each.
WQ, WK, WV
W-Q, W-K, W-V three learned d by d matrices, one for each role.
Q
Q queries, N by d. Row i is what word i looks for.
K
K keys, N by d. Row j is how word j advertises itself.
V
V values, N by d. Row j is what word j hands over when chosen.
Q KT
Q times K-transpose every query dotted with every key: an N by N grid of scores.
√d
root d the square root of the row width. It keeps the scores near 1 in size.
softmax
softmax turns each row of scores into weights that are positive and add to 1.
Out
Out the result, N by d again: each row a mix of value rows.
In plain words

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.

With numbers

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.

Heads and the mask

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.

Read an attention matrix

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.

it

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)

The failure: training without the mask

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.

A causal attention layer reads 6 tokens. How many of the 36 weights in one head can be non-zero?

Chapter 3

The Transformer Block Adds Thinking, Stability and a Sense of Order

Wrap attention with a feed-forward network, normalization and shortcuts, then teach the model where each word sits

The feed-forward network

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.

Say it aloud

FFN of x equals max of zero and x W-one plus b-one, times W-two, plus b-two.

FFN(x)
FFN of x the output for one token row x: d numbers. Every token uses the same weights.
W1
W-one d by 4d. It widens the row to 4d numbers.
b1
b-one a learned bias, 4d numbers.
max(0, ·)
max of zero and ReLU: keep a positive number, turn a negative one into 0. The lecture also allows GeLU, a smooth version.
W2
W-two 4d by d. It narrows the row back to d.
b2
b-two a learned bias, d numbers.
In plain words

Widen x with W-one and add b-one. Turn every negative number into 0. Narrow back with W-two and add b-two.

With numbers

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.

LayerNorm and the shortcut

Two more parts keep a deep stack trainable:

PartWhat it doesWhy
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 connectionAdds 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-normPost-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.

Words need a place in line

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.

Say it aloud

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.

pt
p-t the position code for position t: d numbers, in sine and cosine pairs.
(2k), (2k+1)
slot 2k, slot 2k plus 1 the two slots of pair k: even slot sine, odd slot cosine.
ωk
omega-k the speed of pair k. Early pairs turn fast, late pairs slowly, like the hands of a clock.
t
t the position in line: 0, 1, 2 and on.
2k/d
2k over d how far along the row pair k sits, from 0 toward 1. Ten thousand to that power sets the slowdown.
In plain words

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 numbers

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).

Compare position codes

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.

10

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.

The recipe, assembled

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)

The failure: no positions

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.

A block has d = 1,024. About how many weights are in its attention layers and its FFN together?

Chapter 4

Three Families Differ Only in Who May Look at Whom

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:

  1. the family: encoder-decoder, encoder-only or decoder-only (this chapter);
  2. absolute to relative position (Chapter 5);
  3. a smaller key-value cache with MQA and GQA (Chapter 6);
  4. the FFN to a gated linear unit (Chapter 7).

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.

FamilyMaskTraining gameUsed for
Encoder-decoder (T5)Encoder global, decoder causal, plus cross-attentionText in, text out: "Translate English to German: That is good." gives "Das ist gut."Translation, summaries, any task cast as text
Encoder-only (BERT)GlobalMasked 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)CausalPredict the next wordWriting. GPT-2 was fine-tuned; larger models run zero-shot or few-shot.

The decoder's training game

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.

Say it aloud

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.

L
L the training loss: how surprised the model is by the real next token, on average. Lower is better.
− (1/N) Σi
minus one over N times the sum over i add one term per position i, divide by the N positions, flip the sign.
log
log the natural log: 0 for a sure hit, far below 0 for a long shot.
P( · | · )
P of, given the probability the model gives the token on the left, after reading what is on the right.
ui
u-i the real token at position i of the training text.
u1 … ui−1
u-one through u-i-minus-one the earlier tokens only: the causal mask at work. The slide uses a window of the k tokens before.
Θ
Theta all the model's weights. Training changes them to lower L.
In plain words

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.

With numbers

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.

See the three masks

Draw who sees whom

A filled cell means the row word may look at the column word. Pick a family and compare the pictures.

6

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

The failure: asking an encoder to write

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.

A text has 1,000 tokens. How many next-word training targets does one GPT pass give, compared with BERT at 15% masking?

Chapter 5

Relative Position Lets a Model Read Longer Texts Than It Trained On

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.

EncodingWhere position entersWhat it reaches
AbsoluteAdded to the input embeddingsQ, K and V, through the whole network
RelativeThe attention scores only: a bias, or a change to Q and KNot V. The hope is "train short, test long", which the slide says does not always hold.

ALiBi: a penalty for distance

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.

RoPE: position as a rotation

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.

Say it aloud

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.

⟨ , ⟩
the dot product of RoPE of q at m and RoPE of k at n the attention score, with the query turned for position m and the key for position n.
qT … k
q-transpose times k a plain dot product of the unturned query and key.
R( · )
R of a 2 by 2 turn by the angle in brackets, applied to each pair.
(n − m) θ
n minus m times theta the gap between the positions times the pair's speed. Only the gap survives.
In plain words

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.

With numbers

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, then stretch

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.

7
3

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

The failure: running off the end

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.

A RoPE pair has θ = 0.5. A query is at m = 20 and a key at n = 17. A second query-key pair sits at m = 120 and n = 117. How do their scores compare?

Chapter 6

The KV Cache Saves Work, Then Eats the Memory

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:

  1. compute q, k and v for the newest token;
  2. append k and v to the cache;
  3. attend q over the whole cache.

Generate with and without a cache

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.

Counting the bytes

Name the parts: batch size B, layers L, key-value heads Hkv, head size dh and tokens so far N.

Say it aloud

Cache equals B times L times H-k-v times d-h times N, times 2, times 2 bytes.

Cache
cache the bytes the server holds for keys and values.
B
B batch size: each text in the batch has its own cache.
L
L layers: each layer keeps its own keys and values.
Hkv
H-k-v key-value heads. In plain multi-head attention it equals the query heads.
dh
d-h numbers per head, 128 in Llama-2.
N
N tokens so far. It grows every step.
2
two one key plus one value.
2 bytes
two bytes per 16-bit number.
In plain words

Multiply B, L, H-k-v, d-h and N. Double for keys and values. Double again for 2 bytes per number.

With numbers

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.

Share the heads

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.

DesignKey-value heads (Llama-2-70B)Cache at 4,096 tokens, batch 1
MHA64, one per query head10 GB
GQA8, so WK and WV shrink from 8,192 by 8,192 to 8,192 by 1,0241.25 GB, 8 times smaller
MQA10.16 GB, 64 times smaller
Mistral-7B (GQA)8 for 32 query heads128 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.

Share key-value heads

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.

8

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)

The failure: out of memory at a bigger batch

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.

Llama-2-13B has 40 layers, 40 heads and head size 128, in 16-bit. What is its KV cache for one sequence of 2,048 tokens?

Chapter 7

A Gate Inside the FFN Gives a Better Model at the Same Size

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.

BendFormulaAt x = −1
ReLUx if x > 0, else 00
GeLUx / (1 + e−1.702x), the slide's form−0.15
Swishx / (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.

Say it aloud

FFN-SwiGLU of x equals Swish of x W, times element by element x V, all times W-two.

FFNSwiGLU(x)
FFN-SwiGLU of x the output for one token row x: d numbers.
Swish(xW)
Swish of x W the gate: h numbers. Near 0, that channel is shut.
⊗
times, element by element channel 1 times channel 1, channel 2 times channel 2, and on.
xV
x V the content: h numbers from the second widening matrix.
W2
W-two h by d. It narrows the gated result back to d.
In plain words

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.

With numbers

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.

Bend it, then gate it

Curves: slide x and read the three bends. Gate: move g from 3 to −3 and watch the same content shrink.

1.0

Exact values from the formulas on this page. In the Gate view, one channel stands for the h channels of a real layer.

Same size, better score

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 stepsFFN with ReLUSwiGLU
65,5361.9971.944
524,2881.6771.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

The failure: an unfair swap

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.

A SwiGLU layer has d = 3,000 and hidden width h = 8d/3 = 8,000. How many weights does the layer have, compared with a vanilla FFN of hidden width 4d?

Chapter 8

Scaling Up Turns the Parts into LLMs, and Compute Has a Best Split

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?

What size unlocks

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.

The open models

ModelFrom the slides
LLaMA7B, 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 2Context 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 3Training 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-7BWidth 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.

The Chinchilla law

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.

Say it aloud

C equals six times N times D.

C
C training compute, in operations.
6
six operations per weight per token: about 2 for the forward pass and 4 for the backward pass.
N
N the number of weights.
D
D the number of training tokens.
In plain words

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.

With numbers

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.

Split a training budget

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.

7B

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

The failure: reading size from the name

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.

A team has a training budget C = 6 × 1022 operations. By the 20-tokens-per-weight rule, about how big should the model be?

Chapter 9

Models That See Turn a Picture into Something Attention Can Read

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:

WayWhere the picture goesExamples
Cross-attentionNew layers inside the LLM read itFlamingo: learns from interleaved pictures and text, and holds a visual dialogue.
Visual tokensIts rows join the text tokens as inputPaLM-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".

Way one: Flamingo

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.

Say it aloud

y equals x plus tanh of alpha times cross-attention of x.

y
y the text row after the layer.
x
x the text row before it; the + is a residual shortcut.
tanh(α)
tanh of alpha the gate, between −1 and 1. Training learns alpha from a start of 0, and tanh of 0 is 0.
CrossAttn(x)
cross-attention of x queries from the text, keys and values from the 5 visual tokens.
In plain words

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.

With numbers

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.

Way two: visual tokens

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.

Squeeze a picture, count the cost

Resampler: learned queries read the visual tokens. Two ways: compare what each way adds for a 100-token text prompt.

27
5

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

The failure: pictures eat the window

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.

A Flamingo-style model starts training with α = 0 in each gated cross-attention layer. What does the model compute at step 0?

Chapter 10

Mixture of Experts Grows the Model Without Growing the Cost per Token

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.

Where the experts live

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.

The router has to share the load

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.

Say it aloud

Capacity equals T over E, times C.

capacity
capacity the most tokens one expert accepts in this batch, rounded down.
T
T tokens in the batch.
E
E experts. T over E is the even share.
C
C the capacity factor: 1 allows the even share, 1.5 allows half as much again.
In plain words

Split the T tokens evenly over the E experts. Multiply by C for slack. Round down to whole tokens.

With numbers

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.

Route the tokens

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.

1.0

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

The failure: dropped tokens

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.

A batch has 12 tokens, 4 experts and C = 1.25. How many tokens may one expert take, and what happens to extra tokens sent to it?

Chapter 11

The Field Guide: Numbers, Checklist and Core Code

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.

The numbers to keep

WhatThe numberWhere from
A tokenizer's ratio110 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 matrixN by N per head, so O(N2)Slide 21
Weights in one block4d2 attention + 8d2 FFN = 12d2Derived from slide 27
KV cache per token512 KB (Llama-2-7B), 800 KB (13B), 2.5 MB (70B with MHA)Slide 52
70B cache at 4,096 tokens10 GB at batch 1, 160 GB at batch 16Slide 53
Shrinking the cacheGQA with 8 key-value heads is 8 times smaller, MQA 64 timesSlides 55 and 56
SwiGLU widthHidden 8d/3 keeps weights equal to a 4d FFNSlide 59
FFN against SwiGLULog-perplexity 1.997 against 1.944 (65,536 steps); 1.677 against 1.636 (524,288 steps)Slide 59, Shazeer 2020
Position interpolationHalve every θ to double the windowSlide 47
Llama 24k context, 2T tokens, 70B with 64 heads and 8 key-value headsSlide 67
Llama 31.8T to 15.6T tokens, 405B flagship, 8K base and 128K tuned contextSlide 68
GQA accuracyClose to MHA on a 30B model trained on 150B tokens; MQA a little lowerSlide 57
ChinchillaAbout 20 tokens per weight; training compute 6 × weights × tokensSlide 70
Perceiver Resampler27 visual tokens + 5 queries = 32 keys, a 5 by 32 map, 5 tokens outSlide 75
Flamingo gatesTwo tanh gates per new layer, both started at 0Slide 76
MoE capacitytokens per batch / experts × C; 6 / 3 × 1 = 2Slide 85

The checklist

Ask these of any new Transformer, in order.

  1. Tokens. How many tokens is my input, counted with the model's tokenizer? (Chapter 1)
  2. Mask. Is it an encoder, a decoder or both, so who may see whom? (Chapter 4)
  3. Position. Does position enter the input, the scores or the queries and keys? Is the context longer than it trained on? (Chapters 3 and 5)
  4. Cache. What is B · L · Hkv · dh · N · 2 · bytes at my batch and context, against the weights? (Chapter 6)
  5. Heads. How many key-value heads does it use: MHA, GQA or MQA? (Chapter 6)
  6. FFN. Is it a plain FFN of width 4d or a gated one of width 8d/3? (Chapter 7)
  7. Recipe. How many tokens per weight did it train on, and what does it cost to serve? (Chapter 8)
  8. Pictures. If it sees, how many visual tokens does a picture cost, and do they join the sequence? (Chapter 9)
  9. Experts. If it is sparse, how many weights sit in memory, and how many run per token? (Chapter 10)

The core in code

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

Where this sits, and where to go

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.

The takeaway. A Transformer is cheap to describe and costly to serve. Attention links any two tokens in one hop, at N times N pairs. Generation turns that into a cache that grows with every token and is read at every step. Count the cache first, then choose the design that shrinks it.

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.

MIT 6.5940 Lecture 12: Efficient Transformers and LLMs
Based on the lecture by Song Han and the MIT HAN Lab, MIT 6.5940: TinyML and Efficient Deep Learning Computing, Fall 2026 · The course site and lecture slides · Back to Lecture 11 · On to Lecture 13 · Back to Gleams