Attention

Every word, patch and sound sample can ask the rest of the signal a question, and attention answers with a blend whose weights depend on content: here, 72% of “it” goes to “animal”.

Learn how a position asks, how the others answer, why that is a matched filter in disguise, and how the same trick runs transformers, image and audio diffusion, and model compression.

Pick a word below, then switch between Fixed window and Attention. Watch which words “it” can reach. Then we build, piece by piece, the queries, keys and values underneath, the signal processing hiding in the softmax, and what happens when you shrink the numbers.

You need a dot product (multiply two lists of numbers pairwise, then add) and a rough idea of what a matrix is. We build the rest from zero.

Based on Lecture 25 of Stanford EE269: Signal Processing and Quantization for Machine Learning, taught by Mert Pilanci (lecture of March 2, 2026). Course slides. Every idea is re-taught here in our own words and devices; the course’s slide images are not reproduced.

Ask the sentence

The sentence is the lecture’s (slide 4). The five word features, keys and queries are our own illustrative toy, hand-set so the softmax can be checked by hand; a trained model learns its own. The fixed window gives equal weight to every word within 2 positions.

Chapter 0

Why a Signal Needs to Look Around

See why a fixed filter fails on a sentence, a photo and a sound, and why we let each position choose what to read

Read this sentence slowly: “The animal didn’t cross the street because it was too tired.” What does “it” mean? You said “the animal” in a blink. Change the last word to “wide” and “it” now means the street. Your answer moved to a different word, and you did not scan from left to right to find it.

Now think about how you filtered signals so far in this course. A filter is a rule that makes each output sample from a few input samples near it, with fixed weights. A moving average is one. A convolutional network layer is a bank of them.

A filter looks only at a window: a few neighbours on each side. The weights stay the same wherever the window sits, and they never depend on what the samples say. That is a strong and useful habit. It also fails here. In our sentence, “it” sits 6 words from “animal”. A window of 2 words on each side cannot reach.

The hero at the top of this page shows this. Choose “it”, then flip between the two modes. The fixed window gives the five nearest words equal weight, and the nearest noun inside it is “street”. Attention hands most of the weight to “animal” instead. The rest of this lesson explains how it chooses.

The same problem in three media

The lecture opens with three pictures of one need. In each, the part of the signal that matters is not next door.

First, visual attention. To tell a dog from a cat, the answer lives in the animal patches, not in the grass around it. The lecture shows heat maps from a survey of transformers in visual media (Xu et al., 2022). For a dog image, a cat image, an elephant and a zebra, the bright cells sit on the animal.

Second, textual attention: our sentence about the tired animal. The picture on slide 4 draws lines from “it” to the words it leans on. The thickest line goes to “animal”, and a thinner one goes to “street”. A model that used a window could not draw that line at all.

Third, audio-visual attention. A video has frames, and a sound track has audio features, and they come in pairs. In the lecture’s example (Mercea et al., 2022) a model must name the action: a parrot talking, someone playing a harmonica, scuba diving, skateboarding. The sound can say which video frames to trust. A frame with a harmonica in view matters more when the audio shows a harmonica’s tone. One medium asks the other a question.

The idea in one sentence

Let each position ask a question and let every position offer an answer. Then score how well each answer fits the question. Finally take a blend of the answers, with more weight on the good fits.

The lecture outlines five stops: the attention mechanism, transformer networks, applications in signal processing, text-conditioned diffusion, and model compression. We walk them in that order. Notice that the last stop sounds off topic. It is not. The same course asked, from Lecture 1, how few bits a signal needs. Big attention models are the places where that question costs real money.

Feel it before the formulas

The device below is the image case in miniature. Sixty patches make a picture. Some patches hold an animal, the rest hold grass and sky. Each patch has a small feature vector, and the model carries a query that says “I am looking for fur”. A sharpness knob says how strongly the model prefers good matches.

Turn up the sharpness

Each cell is a patch. Yellow shows how much weight the query gives it. At 0 every patch counts the same, like a plain average. Drag up and watch the weight move onto the animal.

0.0

Illustrative toy: patch features (fur, grass, sky) with seeded noise, and one hand-set query. The lecture’s slide 3 shows real heat maps from a trained model. The scores are sharpness times the dot product of query and patch, then a softmax.

At sharpness 0 the weights are all 1/60. The animal gets only the share its patches take up, about one sixth. At sharpness 3 most of the weight has moved. At 8 the grass and sky are nearly ignored. Nobody told the model where the animal sits. Content decided it.

That is the first big contrast with a filter. A filter’s weights depend on position only. Attention weights depend on content. Move the dog to another corner and the weights follow it. The layer is the same one, with the same learned numbers.

The road

  1. Queries, keys and values: the database lookup that attention softens.
  2. The matrix form: one formula for every position at once, and why we divide by a square root.
  3. What attention can compute: a matched filter that adapts, and a copy machine.
  4. A toy you can run: a convolutional network that cannot see a partner, and an attention layer that can.
  5. Many heads and the transformer: heads, blocks, positions.
  6. Size and cost: vision transformers, model sizes, and the n² bill.
  7. Text steers diffusion: cross-attention in image, video and audio generators.
  8. Fewer bits for the same signal: energy, uniform quantization, random embeddings.
  9. Lattices: better codebooks, from the hexagon to E8.
  10. Low rank and low precision: squeezing a language model’s weight matrices.
  11. Field guide: numbers, checklist, code, where to go next.
Why can a window of 2 words on each side not find that “it” means “animal” in our sentence?

Chapter 1

Queries, Keys and Values

Turn a database lookup into a smooth one, so a network can learn what to ask and what to answer

Picture a small database with five rows. Each row has a key (its label) and a value (its content). You send a query. The database compares your query with each key, finds the row that matches, and returns that row’s value. On slide 6 the query matches Key 5, so Value 5 comes out.

This is the whole picture of attention. Keep it in mind: the key decides whether a row matches, and the value is what the row hands over. They are two different things. A library card says “gardening, 1962”. The book holds the soil advice you came for.

The lecture states the terms like this. Given a set of value vectors and a query vector, attention is a way to compute a weighted sum of the values that depends on the query. The query decides which values to focus on, and we say the query attends to them. The keys are used to compute the scores. The values are used to build the output.

Why the lookup must be soft

A real database lookup is a hard choice. One row wins and the others vanish. That is a problem for a neural network, because a network learns by backpropagation: it nudges every number a little in the direction that lowers the error. A hard choice has no “a little”. Either row 5 wins or it does not. The error does not change smoothly, so there is no direction to follow.

A soft lookup fixes this. Instead of one winner, give every row a score for how well its key fits the query. Turn the scores into weights that are positive and add up to 1. The output is the weighted sum of all the values. Now a small change to a key changes the weights a little, and the output a little. Gradients can flow.

The device below uses a dial. Each key is an arrow pointing at some angle, and so is your query. Two arrows of length 1 have a dot product equal to the cosine of the angle between them, so the arrow that points nearest your query scores highest. Drag the query round the dial, then raise the sharpness and watch the soft answer turn into the hard one.

Query a five-row database

Top: five blue key arrows and your warm query arrow. Bottom: each row’s purple value, with its yellow weight. The teal line is the soft answer. The green ring marks what a hard lookup would return.

95°
4.0

Illustrative: keys at 20, 55, 90, 125 and 160 degrees with values 0.3, 0.8, 0.45, 0.9 and 0.2. Score = sharpness times the dot product of two unit arrows. The lecture’s slide 6 shows only the database picture; the dial is ours.

At sharpness 0 every row gets 20%, and the answer is the plain average of the values, 0.53. Raise it to about 20 and the weights turn almost one-hot. The soft answer sits on the ring. Between those two ends is the useful middle, where the network can both choose and learn.

The same thing as matrices

A network does not get keys and values handed to it. It makes them. Suppose we have two lists of vectors: X, the things that ask, and Y, the things that answer. Each has n vectors of dimension d. Three learned weight matrices turn them into the three roles.

  1. Query. q = WQ x. A matrix of size dk × d turns a d-vector into a dk-vector: what am I looking for?
  2. Keys. ki = WK yi, also dk numbers: what do I offer? Keys must match the query’s size, so their dot product exists.
  3. Values. vi = WV yi, with dv numbers: what do I hand over? Values may have any size.
  4. Scores and mix. Score each key against the query, run softmax over the scores, and sum the values with those weights.
ai
The score of key i: how well it fits the query. A raw number, any size, positive or negative.
1/√dk
A shrink factor. It keeps the scores from growing as the key size dk grows. Chapter 2 measures why.
kiT q
The dot product of key i and the query: multiply the two lists pairwise and add. Big when they point the same way.
output
One vector of size dv for this query. It is a blend of values, never a value the database never held.
∑ softmaxi(a) vi
Softmax turns the scores into weights: eai divided by the sum of all eaj. Each weight is above 0 and they total 1.

The lecture also notes two facts. First, the three matrices WQ, WK and WV are learned by backpropagation, like any other weights. Second, the shrink factor makes the variance of the score equal 1. We check that claim by experiment in the next chapter.

A worked example with every step

Let dk = 2, so 1/√dk = 0.707. The query is (1, 0). Three keys: (1, 0), (0, 1) and (−1, 0). Three values: (10, 0), (0, 10) and (5, 5).

dot products: 1, 0, −1  →  scores a = 0.707, 0, −0.707

ea = 2.028, 1.000, 0.493  →  sum 3.521  →  weights 0.576, 0.284, 0.140

output = 0.576 (10, 0) + 0.284 (0, 10) + 0.140 (5, 5) = (6.46, 3.54)

Read the answer. The first key matches the query best, so the first value dominates: 6.46 of the first coordinate. The second value pulls the second coordinate up to 3.54. The third key points opposite to the query and still gets 14%. Softmax never gives exactly 0.

Why does attention use a soft weighted sum instead of returning the single best-matching value like a database?

Chapter 2

One Formula for Every Position at Once

Stack all the queries, keys and values into matrices, and see the layer as one row-wise blend you can compute in a single product

Chapter 1 handled one query. A real layer has n of them, one per token, and they all ask at the same time. A GPU loves this: instead of n small loops, do three matrix products. So we stack the vectors as rows and write the whole layer as one formula.

Take the two input matrices X and Y, each n rows of d numbers (n tokens, d numbers per token). Multiply by the three learned matrices.

  1. Q = X WQ, of shape n × dk. Row i is the query of token i.
  2. K = Y WK, of shape n × dk. Row j is the key of token j.
  3. V = Y WV, of shape n × dv. Row j is the value of token j.
  4. A = softmax(QKT / √dk), of shape n × n. Row i holds the weights of query i over all keys.
  5. Z = A V, of shape n × dv. Row i is the output for token i.

Two things to notice. The matrix QKT holds every query-key dot product at once: entry (i, j) is qi dotted with kj. And softmax is applied row-wise: each row is normalised on its own, so each query gets its own set of weights summing to 1.

Z
The layer’s output: n rows of dv numbers, one row for each token that asked.
softmax
Applied to each row separately. It makes the row positive and gives it a total of 1, with the largest score getting the most weight.
QKT
An n × n table of scores. Row i, column j says how well token j’s key answers token i’s query.
√dk
The square root of the key size. Dividing by it keeps the scores near the same size whatever dk is.
V
The values, one row per token. Multiplying by the weight matrix mixes them row by row.

When Y is a different signal from X, the layer is cross-attention: one signal asks and another answers. The lecture credits the idea to the translation work of Bahdanau and colleagues. Hold on to it, because Chapter 7 uses exactly this form to let a text prompt steer an image.

Four steps, with real numbers

Step through the layer on four tokens. The numbers are small on purpose, so you can check one row by hand. Choose a stage, then choose a row to follow.

Step the layer

Each grid is a stage. Pick a stage with the buttons, then pick a row to see its arithmetic in the read-out.

Illustrative numbers: Q, K and V are each 4 × 2 and hand-picked. Every grid is computed live from them with the lecture’s formula.

The mixture view

Row i of Z is the sum over j of pij times the value vector Vj. The weights pij are all at least 0 and add up to 1 along each row. A sum like that is a convex combination: a blend that stays inside the cloud of the values. It can never leave it.

This explains something people find odd. Attention cannot invent a value larger than every value it has. It can only choose a mix. The mixture weights depend on the input, and that is where all of its power sits.

Now set Y = X. This is self-attention, where a signal queries itself. The layer becomes Z = softmax(X WQ WKT XT / √dk) X WV. Look at the middle: WQ WKT is a single d × d matrix of rank at most dk. So the score between two inputs is a bilinear form xiT M xj. In plain words, the network learns one similarity measure, and that measure can be asymmetric.

Why divide by a square root

The lecture says the shrink factor makes Var of the score equal 1. Here is the derivation, then an experiment. Suppose each entry of q and k is an independent random number with mean 0 and variance 1. Then one product qmkm has mean 0 and variance 1. The dot product adds dk such products. Variances of independent terms add, so Var(qTk) = dk, and the standard deviation is √dk. Dividing by √dk divides the variance by dk, which leaves exactly 1.

Why does it matter? Look at the symptom first. With dk = 64 the raw scores spread over about ±8. A softmax over scores that far apart puts almost all the weight on one key. The measurement follows in the device. The fix is the division. The reason it matters is the gradient: when one weight is near 1, the softmax passes almost no learning signal back.

Grow the key size

Grey: dot products of random queries and keys with no shrink. Teal: the same products divided by the square root of dk. Drag dk from 1 to 512.

64

Measured live: 2,000 random pairs per setting (entries from a standard normal, seeded). The saturation figure is the average largest weight when a softmax is taken over groups of 8 such scores.

At dk = 1 the two histograms are the same. As dk grows the grey one fans out like √dk, while the teal one stays put at spread 1. The read-out also shows the cost of the fan: the softmax of grey scores is nearly one-hot, so it is nearly deaf to everything but one key.

Queries and keys have independent entries with mean 0 and variance 1, and dk = 64. What is the standard deviation of qTk before and after dividing by √dk?

Chapter 3

What Attention Can Compute

Recognise the softmax as an adaptive matched filter, then build a layer that copies the previous token with a shift matrix

You know this problem from radar. A pulse of known shape, call it s, is sent out. A receiver hears y = s + n, where n is random noise. Is the pulse there? And if the transmitter might send one of several pulses, which one?

The classic answer is the matched filter: take the dot product of what you heard with the shape you expect. Large means present. Here is why it is the best linear detector. A filter h gives output hTy = hTs + hTn. The signal part is hTs. The noise part has power σ2‖h‖2, if the noise is white with variance σ2. By the Cauchy-Schwarz inequality, (hTs)2 is at most ‖h‖2‖s‖2, so the ratio of signal power to noise power is at most ‖s‖2/σ2. Equality holds only when h is a multiple of s. The best filter is the pulse, flipped in time and used as a correlator.

Now look at the attention score again: ai = kiTq / √dk. The query q is what you heard. Each key ki is a pulse shape you expect. The score is a matched filter output. The lecture states it this way: this is a correlation detector, optimal for detecting a fixed waveform in Gaussian noise.

The softmax makes the filter bank adapt

A plain bank of matched filters gives n scores. Attention then runs softmax over them: ωi = eai divided by the sum of all eaj. This turns the scores into weights that add up to 1, and the output is z = ∑ ωi vi. The lecture gives the reading in three lines.

  1. The keys are a learned dictionary. Each key is an atom, a waveform the layer has learned to look for.
  2. Attention selects the most correlated atoms. The best match gets the most weight.
  3. The output is a data-dependent convex combination. The blend changes with every input.

One honest caution. Matched-filter optimality needs a known waveform and white Gaussian noise. Softmax adds a winner-take-most step on top, which is not part of the classical proof. And correlation favours atoms with more energy, so the comparison is fair only when the atoms have equal energy. The lecture’s point is the analogy, and it is a good one.

Try it. The device has four atoms: a slow tone, a fast tone, a chirp (a tone that sweeps up in pitch) and a short pulse. Pick which one the transmitter sent. Noise buries it. Raise the noise and watch the correct atom lose its lead.

Detect the hidden waveform

Top: what the receiver hears (the query). Middle: four blue atoms with their score and yellow weight. Bottom: the purple blend, against the true waveform in dashes.

4.0

Illustrative: 64 samples, each atom scaled to have the same energy, white Gaussian noise of the standard deviation shown, scores divided by the square root of 64. The values are the atoms themselves. Seeded; press New noise for another draw.

With a small noise the right atom takes nearly all the weight and the blend is almost exactly the clean waveform. That is denoising by selection, not by smoothing. Notice a difference from a low-pass filter: the filter blurs everything, while attention keeps the chosen shape sharp. As the noise grows, other atoms collect weight and the blend becomes a mix of shapes. That is the correct, honest answer to “I am not sure”.

A layer that copies the previous token

Now a different question. Can one attention layer do something exact and simple? The lecture picks the copy-previous-token task. The input is four tokens x1, x2, x3, x4. The target is yt = xt−1. So the output is (0, x1, x2, x3): the input, pushed back by one step. In filter language, it is a delay of one sample, z−1.

To keep the arithmetic clean, write each token in the delta basis: token t is the vector et, with a 1 in place t and 0 elsewhere. Stacking them gives X = I4, the identity matrix. (The token’s name and its position are the same thing here. That is a shortcut of the lecture’s example.)

Choose WQ = I, WV = I and WK = S, the shift matrix: ones just above the diagonal, zeros everywhere else. Then Q = X WQ = I, K = X WK = S, and the score table is QKT = I ST = ST.

ST rows: (0 0 0 0), (1 0 0 0), (0 1 0 0), (0 0 1 0)

Read it row by row. Row 2 puts its 1 in column 1, so query 2 matches key 1. Row 3 matches key 2, row 4 matches key 3. In words: key j advertises “I come before position j + 1”, and each query asks for the token before it. The shift matrix carries all the knowledge.

Two details the slide leaves out, and the device shows. First, softmax of a 0-and-1 table is not one-hot: with scores 1, 0, 0, 0 the winner gets only e/(e + 3) = 47.5%. The model fixes this by learning a bigger WK, say 6 S, which multiplies every score. Second, row 1 has no previous token. Its scores are all 0, so softmax spreads weight evenly, 25% each, and its output is not the clean 0 that the target wants. Real models add a start token or a mask for that row.

Shift by one with attention

Left: the weights A = softmax(c ST). Right: the output next to the target. Raise c, the scale on the scores, and the weights harden into a shift.

1.00

Exact arithmetic on the lecture’s example: X = I4, WQ = I, WV = I, WK = c S (so no 1/√dk shrink is shown). Heat is the weight; the target is (0, x1, x2, x3).

Drag c to 6 and rows 2 to 4 each put 99.3% of their weight on the right earlier token. The layer now implements a delay line, using content-based routing that happens to point at a fixed offset. Remember this trick. In a real transformer the same two numbers are learned from position codes: a query that says “one step back” and a key that says “I am here”. Chains of such steps build up longer tricks.

In the lecture’s copy task with WQ = I, WK = S, WV = I, why does token 3 end up copying token 2?

Chapter 4

A Toy a Convolutional Net Cannot Solve

Run a sequence task where the answer sits far away, and see why one attention layer fixes what five convolutions cannot

Theory is easy to nod at. The lecture now runs it on a toy built to need long reach. It is a sequence-to-sequence task: a signal goes in, a signal of the same length comes out. The input is a row of shapes standing on a line: triangles and rectangles, each with its own height. The target is the same row, but with the heights averaged within each pair. As the picture on slide 16 shows, the two triangles come out at one shared height, and so do the two rectangles.

Think about what the output at the first triangle must know. It must know the height of the other triangle, which may sit far down the line. Between the two there can be rectangles and empty space. The task is made so that the partner is never next door.

What a convolutional network sees

The baseline is a stack of five one-dimensional convolution layers. Each uses a kernel of 5 (a filter with 5 weights), with padding of 2 so the length does not change, and a ReLU between layers. A ReLU sets every negative number to 0 and leaves the rest alone. The hidden layers carry 64 channels, which means 64 different filters at each layer. The lecture prints its size as 62,537 parameters.

How far can one output sample see? One layer with a kernel of 5 sees 2 samples on each side. The second layer reads outputs that each saw 2 on each side, so it sees 4. Each added layer adds 2 on each side. This reach has a name: the receptive field. For L layers with kernel 5 it covers 1 + 4L samples. Five layers see 21 samples: 10 each way.

If the partner is 30 samples away, those five layers never see it. Training cannot fix that. No weight setting makes a network use a sample it has no path to. The best it can do is to guess the partner from the shapes it can see. That guess is poor. Suppose heights are spread evenly between 0 and 1. Knowing only your own height h, the best prediction of the pair’s average is (h + 0.5)/2. Its mean squared error is the variance of the hidden partner divided by 4: (1/12)/4 = 0.0208 per sample. It never reaches 0.

Can the output reach its partner?

Two triangles share one target height. The teal band is what the output at the left triangle can see through the convolution stack. The yellow arc is attention’s weight on the partner. Change the number of layers and the distance.

5
30

Illustrative toy: heights drawn evenly between 0 and 1, kernel 5, padding 2, reach 1 + 4L, as in the lecture’s stack. The error floor is the exact value for a predictor that cannot see the partner. The attention arc is the weight one trained layer would learn.

At the lecture’s five layers, the band covers 21 samples. A partner 30 away is outside it, and the read-out gives the floor of 0.0208 per sample. To reach 30 away you need 15 layers. To reach 48 away you need 24. Depth buys reach slowly, one more layer per two more samples.

Swap one layer for attention

The lecture changes one thing. It replaces one convolution in the middle by a self-attention layer built from three 1×1 convolutions. A 1×1 convolution has kernel size 1, so it is just a matrix applied to every position: our WQ, WK and WV. The new network has 64,081 parameters (the slide’s count), about the same as the 62,537 before. Same size, different reach.

pythonclass SelfAttentionLayer(nn.Module):
    def __init__(self, in_dim, out_dim, key_dim):
        super().__init__()
        self.conv_Q = nn.Conv1d(in_dim, key_dim, kernel_size=1, bias=False)
        self.conv_K = nn.Conv1d(in_dim, key_dim, kernel_size=1, bias=False)
        self.conv_V = nn.Conv1d(in_dim, out_dim, kernel_size=1, bias=False)

    def forward(self, x):                 # x: (batch, 64, T)
        Q = self.conv_Q(x)                   # (batch, 64, T)
        K = self.conv_K(x)                   # (batch, 64, T)
        V = self.conv_V(x)                   # (batch, 64, T)
        A = Q.transpose(1, 2).matmul(K).softmax(2)   # (batch, T, T): row = one query
        y = A.matmul(V.transpose(1, 2)).transpose(1, 2)  # (batch, 64, T)
        return y

Trace the shapes. The input has 64 channels and T positions. Each of Q, K and V keeps that shape. Transposing Q to (T, 64) and multiplying by K of (64, T) gives a (T, T) table: every position scored against every position. Softmax over the last axis normalises each row. Multiplying by the values gives (T, 64) again, and a last transpose restores (64, T). The output has the shape of the input, so the layer drops in anywhere a convolution sat. One more detail from the code: this version leaves out the 1/√dk shrink of Chapter 2. With key size 64 the network still trains, but it is a choice, not a rule.

What training shows

Both networks train on the same data with a mean squared error loss, which averages the squared gaps between prediction and target. Backpropagation sets all weights. The lecture plots the two training curves. The convolutional network’s loss drops at first and then flattens at a high value, as a network that cannot see the partner should. The attention network keeps falling, to a loss far below the plateau.

The predictions agree. On the lecture’s test sequences the convolutional output gets the shapes roughly right but wrong in height. The attention output lines up with the target. The attention patterns on slide 24 show why. Plot the n × n table A for one sequence and you see bright cells in blocks. Each shape’s row lights up at its partner’s columns. The network learned the pairing rule itself, with no one telling it where partners sit.

The same lesson reaches far beyond toys. Whenever an output needs information from far away in the signal, a stack of local filters pays in depth. Attention pays in a single n × n table. The price of that table is Chapter 6.

A convolution stack has 8 layers with kernel 5. A partner shape is 25 samples away. What happens?

Chapter 5

Many Heads, One Transformer

Run several attentions side by side, wrap them in a block that can be stacked, and give the block a sense of order

One attention gives each word one blend. But a word like “chased” needs several things at once: who did the chasing, what got chased, and which word came just before. One softmax cannot send a lot of weight to three different places and also keep them apart. The fix is simple: run several attentions in parallel.

Each copy is a head. Head h has its own matrices WQh, WKh and WVh. It runs the full formula of Chapter 2 and returns its own n × dk output. The H outputs are glued side by side (concatenated) and passed through one more matrix WO that mixes them. This is what the lecture shows from the Vaswani paper: parallel scaled dot-product attentions, then Concat, then Linear.

MultiHead(X)
The layer’s output: n rows of d numbers, the same shape as the input X.
[head1, …, headH]
The heads placed side by side. With dk = d/H numbers each, H heads fill exactly d columns.
WO
A d × d matrix that lets the heads share what they found.
headh
Plain attention with this head’s own three matrices. Each head can learn a different kind of match.

A surprise for the budget: more heads do not cost more weights. Each head has dk = d/H columns, so the three matrices of all heads together hold 3d2 numbers, and WO adds d2. For d = 512 that is 4 × 5122 = 1,048,576 weights, whether H is 1 or 16. The heads split the width. They do not multiply it.

One sentence, three heads

Pick a head. Lines go from each word on the left (the query) to the words it reads on the right (the keys). Then set the head count to see how the width splits.

8

The three patterns are hand-set and illustrative, in the spirit of the heads that analysis papers find in trained models (below). Parameter counts are exact for d = 512, ignoring biases.

What real heads do

Do trained heads really specialise? The lecture’s slide 27 cites Clark and colleagues (2019), who inspected BERT, a trained transformer. They found heads with clear jobs.

Head in BERTWhat it attends toAccuracy on that relation
Layer 8, head 10Direct objects attend to their verbs86.8% on the object relation
Layer 8, head 11Noun modifiers such as determiners attend to their noun94.3% on the determiner relation

Nobody told these heads what a determiner is. The job came from training on text. Not every head is so clean, though, and our toy heads above are tidier than real ones.

The block that gets stacked

Attention alone is not a network. The transformer of Vaswani and colleagues (2017) wraps it in a block that has the same input and output shape, so you can stack N of them. The device walks one block with the original sizes: d = 512, 8 heads and a feed-forward width of 2,048.

  1. Multi-head attention lets every token read the others. Tokens talk.
  2. A residual connection adds the block’s input back to its output: x + Attention(x). The original signal always keeps a clear path forward, so deep stacks train.
  3. Layer normalisation rescales each token’s d numbers to a steady mean and spread, which keeps the numbers from drifting from layer to layer.
  4. A feed-forward network (two matrices with a ReLU between, d to 4d to d) works on each token alone. Tokens think.
  5. A second residual and norm close the block.

Walk one block

Press Next to push ten tokens through the block. The right-hand label is the shape of the tensor leaving each stage.

Sizes from the original transformer base model: d = 512, 8 heads, feed-forward width 2,048, 6 stacked blocks. The count of 10 tokens is our choice.

The missing sense of order

Look at Chapter 2 again. Nothing in the formula knows where a token sits. Shuffle the rows of X, and the rows of Z come out shuffled the same way, with the same values. The layer is permutation equivariant. For a bag of words that is fine. For a sentence, “dog bites man” and “man bites dog” would look the same.

The cure is to add a code for the position to each token before the first block. The original paper used sinusoids: PE(pos, 2i) = sin(pos / 100002i/d) and PE(pos, 2i + 1) = cos(pos / 100002i/d). For a signals reader this is familiar. Each pair of numbers is a sine and cosine at one frequency, and the frequencies are spaced geometrically from fast to very slow. A shift in position is a rotation of each pair, so the dot product of two codes depends only on how far apart the positions are, not on where they are.

Read the position code

Left: the code of 32 positions, each row a position and each column one number, blue for positive and pink for negative. Right: how much two codes agree, as a function of the gap. Set a start position and a gap.

6
8

Exact: the paper’s formula with d = 32 numbers per code, so a code dotted with itself is 16. Many models today learn their position codes instead; the idea of adding a position signal is the same.

The dot product falls from 16 at gap 0 and wiggles as the gap grows. Move the start position and the number for a fixed gap does not change. Attention can therefore learn a query that says “look about 3 steps back” and have it work at every position.

A layer has d = 512 and uses 8 heads instead of 1. How do the numbers change?

Chapter 6

Size, Benchmarks and the n² Bill

Turn an image into a sequence, see how far these models have grown, and count what the n × n table costs

Chapter 5 built a block that takes n tokens in and gives n tokens out. Nothing in it says the tokens must be words. The lecture’s next stop is the ImageNet challenge, a long-running contest to name the object in a photo. Its slide points at vision transformers (ViT) as the entries that now do best. How do you feed a photo to a block made for tokens?

Cut the image into square patches. A 224 × 224 colour image cut into 16 × 16 patches gives 14 × 14 = 196 patches. Each patch holds 16 × 16 × 3 = 768 numbers. A learned matrix turns those into one d-vector, a position code is added, and you have 196 tokens. The transformer block does not change at all. Self-attention now lets a patch of fur look at a patch of face, however far apart they sit in the picture. This is Chapter 0’s dog image, made precise.

Two details finish the picture. The position code of Chapter 5 still applies: a patch’s row and column become a code, so the model knows where each patch sat. The original ViT also adds one extra learned token, the class token. Attention lets every patch pass information into it, and its final vector goes to the classifier that names the object.

Compare this with Chapter 4. A convolutional network sees a patch only through local windows, and builds reach one layer at a time. A vision transformer lets every patch see every patch from the very first layer.

How big, and how well

The lecture then shows size. Its chart plots parameter counts for ResNet-50 (about 26 million, a strong convolutional network), BERT-Large (340 million) and GPT-2 (1.5 billion), all read from slide 29, and the line keeps rising from there. For scale of the top end, the GPT-3 paper reports 175 billion. A parameter is one learned number. Going from 26 million to 175 billion is a factor of about 6,700.

How do we know size buys anything? The lecture shows two yardsticks. MMLU (Measuring Massive Multitask Language Understanding) poses multiple-choice questions from 57 subjects, including elementary mathematics, US history, computer science and law. The slide plots score against model size: bigger models land higher. The second yardstick is the Multistate Bar Exam, a test of legal knowledge that is a precondition to practising law in the US. The slide shows successive GPT models climbing a staircase of scores on it.

These are real results, but read them carefully. A benchmark measures one thing. A rise on a chart says that these models improved on these tests. It does not say how they reason.

The bill for size

Training such models costs enormous compute. The slide’s chart gives training cost in zettaFLOPs (1 zettaFLOP is 1021 floating-point operations). It shows GPT-3 at about 314 and PaLM at about 2,527, so PaLM needed about 8 times as much. The same slide lists BERT, RoBERTa and LaMDA, all far below PaLM.

Part of that bill comes straight from the n × n table. Count it. For n tokens, the table has n × n entries, one per query-key pair. Compute the table, and the matrix product by V, and you pay on the order of n2 d operations per layer, where d is the width. Double n and you pay four times as much.

Memory is the second bill. If each entry takes 2 bytes (16-bit numbers), one head in one layer holds 2n2 bytes. For a 224-pixel image, n = 196 and that is 77 kilobytes. Small. For a 1,024-pixel image with the same patches, n = 4,096 and the table is 33.6 megabytes. The image grew 4.6 times wider, and the table grew 437 times. For a text of 100,000 tokens the table is 20 gigabytes, for each head and each layer, if you were to store it all.

Size the attention table

The warm line is n, the teal line is n² pairs, on log axes. Choose text or an image, then drag. The dot shows where you are.

224

Exact arithmetic: n tokens give n² query-key pairs; one 16-bit table per head per layer is 2n² bytes. Real systems often avoid storing the whole table (see FlashAttention in the lessons linked at the end).

The device makes the same point as the numbers. The gap between the two lines is the cost of letting every position see every other. A fixed window pays n times its width instead, and pays far less at long lengths. That is the price tag behind Chapter 4’s gift: reach everywhere, in one layer, for n² work.

Climb the size ladder

Bars are on a log scale, so each gridline is ten times the one before it. Switch between the number of parameters and the training compute.

ResNet-50 (26 million), BERT-Large (340 million) and GPT-2 (1.5 billion) are read from the lecture’s slide 29; GPT-3’s 175 billion is the figure in its paper. Compute values (GPT-3 about 314, PaLM about 2,527 zettaFLOPs) are read from the chart on slide 32.

Read the first read-out as a rate: across the three steps the ladder gains about 19 times per step on average (the steps themselves are uneven: about 13 times, then 4 times, then 117 times). That growth is why the final three chapters of this lesson matter. A model that big needs fewer bits per number, or it cannot be stored or run cheaply.

An image 4.6 times wider (with the same 16 × 16 patches) is fed to a vision transformer. About how much bigger is each attention table?

Chapter 7

Words Steer Pictures, Video and Sound

See cross-attention carry a text prompt into a denoising network, then rebuild a sound from a spectrogram that has lost its phase

Type “A photograph of an astronaut riding a horse” and a model draws one. That is the lecture’s example for Stable Diffusion (Stability AI, 2022), and the picture on slide 33 does show an astronaut on a horse. Where does the attention of this lesson come in?

First, a two-minute picture of diffusion; Lecture 27 builds it from the maths. Take a real image and add a little random noise. Do it again, many times, until nothing but static is left. A network is then trained to undo one step: given a slightly noisy image, guess the noise that was added and subtract it. To make a new image, start from pure static and run that denoiser step after step. A picture appears out of the noise.

Plain diffusion draws a random picture. To draw your picture you must tell the denoiser what you want. That is conditioning. The lecture’s slide 34 draws the latent diffusion recipe. The image is first squeezed by an encoder into a small grid of numbers, the latent space, because denoising a small grid is far cheaper than denoising every pixel. The denoising network works in that space and a decoder turns the result back into pixels. The prompt arrives through the conditioning arrows, and the way it gets in is attention.

The text prompt as keys and values

Recall cross-attention from Chapter 2: one signal asks, another answers. Here the image latents ask and the text answers. A text encoder (the lecture’s figure shows CLIP-style conditioning) turns the prompt into one vector per word. Those become the keys and values. Each cell of the latent grid gives one query. Inside the denoiser, at many layers, this runs: Q = (latent cells) WQ, K = (word vectors) WK, V = (word vectors) WV.

Count the shapes. The grid has 64 cells, the prompt has 8 words, so the table A is 64 × 8. Row i says how cell i splits its attention over the 8 words. Z = AV gives each cell a blend of word meanings. A cell that is part of the horse should read “horse”. A cell of sky should read mostly the style words. Nobody hand-writes that. It comes out of training, because reading the right word lowers the denoising error.

The device below uses a small hand-set scene so that you can see the table. Choose a word and read down its column: how much attention each cell gives that word.

Which cells read this word?

The grid is a tiny latent picture: sky above, an astronaut on a horse, ground below. Pick a word. Yellow shows how much attention each cell gives it.

1.0

Illustrative toy: the scene, the word keys and the cell queries are hand-set, and the weights are a real softmax over the 8 words for each cell. The lecture’s slide 34 shows the real network; trained maps are less tidy.

Choose “astronaut” and the six cells of the rider glow. Choose “horse” and the body of the horse does. Choose “photograph” and the glow is faint but everywhere: that word sets the style for every cell. Raise the sharpness and each word’s region tightens. Notice what the layer never does: it never draws. It only decides which words each cell listens to, and the denoiser does the rest.

The lecture then shows Sora (OpenAI, 2024), which turns a text prompt into video, and slide 36 draws the same recipe stretched to video frames. The new difficulty is size. More frames mean far more cells, and Chapter 6’s n² table grows with the square of that count.

Diffusion on sound

The last example is the lecture’s own research. Villa-Renteria, Wang and Pilanci (2024) built a system that adds an instrument to a song from a text prompt such as “add jazz drums”. The recipe has four steps, and each is a tool from this course.

  1. Turn audio into a spectrogram. The short-time Fourier transform (Lecture 8) gives a picture: time across, frequency up, brightness for strength. Now a picture model can work on sound.
  2. Separate the spectrogram into stems: vocals, drums, bass, guitar and so on.
  3. Train a diffusion model to generate one stem given the rest, guided by a text prompt.
  4. Invert the spectrogram back to a waveform with the Griffin-Lim algorithm.

Step 4 hides a puzzle. A spectrogram picture keeps only the magnitude of each Fourier coefficient. The phase (the angle that says where in its cycle each sinusoid starts) is thrown away, because an image model draws brightness, not angles. Without phase you cannot just invert. Put in random phases and you get a buzzy mess.

Griffin-Lim finds phases by repeating two moves. Take the current guess of the signal and compute its STFT. Keep the phases it gives, but replace the magnitudes with the target ones. Invert, and you have a new guess. Each pass makes the spectrogram of the guess a little closer to the target. The device runs it for real on a short signal: a two-note chord followed by a sweep.

Recover the phase

Top: the target magnitude spectrogram. Middle: the true waveform (dashes) and the guess (teal). Bottom: the mismatch after each pass. Drag the number of passes up to 200.

0

Computed live: 512 samples, Hann window of 64, hop 16, magnitudes only, random starting phase (seeded). Mismatch is the distance between the guess’s spectrogram and the target, divided by the target’s size. The correlation ignores overall sign.

At pass 0 the mismatch is about 66%. One pass cuts it to about 39%, ten passes to about 25%, and then progress slows: about 17% after 40 passes and about 5% after 160. Now look at the waveform and at the correlation. The guess does not trace the true waveform, even when its spectrogram nearly matches the target. Magnitudes say how strong each frequency is at each moment. They do not fix every phase relation between frequencies.

So Griffin-Lim returns a signal with almost the same spectrogram, not the original signal. That is why it is an approximate inverse. The lecture’s system uses it for the last step, from spectrogram back to sound.

In cross-attention for a text-to-image model, what are the queries, and what are the keys and values?

Chapter 8

Fewer Bits for the Same Signal

Count what arithmetic costs in energy, then shrink the numbers with a uniform quantizer and a random rotation that tames outliers

The models of Chapter 6 are huge, and every weight is a number a chip must fetch, multiply and add. This course began with the question of how few bits a signal needs. The last third of this lecture asks it of a neural network: how few bits can each weight take before the model gets worse?

Why bits cost energy

The lecture shows a table from Horowitz (2014): the energy, in picojoules (pJ), of single arithmetic operations. One picojoule is a millionth of a millionth of a joule.

OperationEnergy
8-bit integer add0.03 pJ
32-bit integer add0.1 pJ
16-bit float add0.4 pJ
32-bit float add0.9 pJ
8-bit integer multiply0.2 pJ
32-bit integer multiply3.1 pJ
16-bit float multiply1.1 pJ
32-bit float multiply3.7 pJ

Look at the ratios. An 8-bit integer add costs 30 times less than a 32-bit float add (0.9 / 0.03). An 8-bit integer multiply costs 18.5 times less than a 32-bit float multiply (3.7 / 0.2). The lecture marks exactly those two gaps. A neural network is a sea of multiply-adds: one weight times one input, added to a running sum. So the price of one multiply-add is the multiply plus the add: 0.23 pJ in 8-bit integers and 4.6 pJ in 32-bit floats.

Price a token’s arithmetic

The bars are the table above on a log scale. The pink bars are the two operations of one multiply-add in the format you choose. Drag the model size.

7 billion

Exact arithmetic on the Horowitz table values. One token needs about one multiply-add per weight in a dense model, and the table covers arithmetic only: moving numbers in and out of memory costs more and is not counted here.

Set it to 7 billion weights. One token costs about 32 millijoules of arithmetic in 32-bit floats and about 1.6 in 8-bit integers: 20 times less. It is an arithmetic floor, not a battery meter, but the direction is clear. Fewer bits per number means less energy and also smaller storage. The lecture’s next slide cites Han, Mao and Dally’s Deep Compression (2015), which combined pruning (deleting small weights) with trained quantization on AlexNet, a 240 MB network. Their paper reports a 35 times smaller file with no accuracy loss. Pruning alone, or quantization alone, lost accuracy sooner on the lecture’s plot.

The uniform quantizer

Now the mechanics. A B-bit quantizer Q(x) rounds a number x to one of 2B levels. Choose a dynamic range R, so that −R ≤ x ≤ R. The levels sit evenly: q1 = −R, q2 = −R + Δ, and on up to q2B = R. The gap Δ is the resolution: Δ = 2R / (2B − 1). Nearest-neighbour rounding picks the closest level, so each number is off by at most Δ/2. For a vector, quantize every coordinate on its own.

The total error of a d-number vector is at most (Δ/2)√d, since d coordinates each contribute up to Δ/2. The lecture writes this as O(√d) times the resolution. Everything hangs on Δ, and Δ hangs on R.

The outlier problem, worked

Here is the trouble. Let x have 64 numbers. Sixty-three are small, around 0.3 in size. One is an outlier of 6.0. To fit the outlier, R must be 6.0. With B = 3 bits there are 8 levels, so Δ = 12 / 7 = 1.71. The levels are −6.00, −4.29, −2.57, −0.86, 0.86, 2.57, 4.29, 6.00. Now round a small number such as 0.3. The nearest level is 0.86, an error of 0.56. That error is bigger than the number itself. All 63 small coordinates are damaged to keep one big one. Without the outlier, R would be about 1 and Δ about 0.29, six times finer.

A random rotation spreads the outlier

The lecture’s fix is randomized embeddings (Lyubarskii and Vershynin, 2006, used for compression by Saha, Pilanci and Goldsmith, 2023). Multiply x by a random matrix S, then quantize Sx. Each entry of Sx is a random mix of all entries of x. The outlier’s size is spread across all 64 coordinates, so the entries become similar in size (“democratic”, in the lecture’s word) and look roughly Gaussian. The range R shrinks and so does Δ.

Two ways to build S, from slide 42. A Gaussian S has entries drawn from a normal distribution with variance 1/m; it costs O(d2) multiplications. A randomized Hadamard S = HD/√d uses a Hadamard matrix H (entries ±1) and a diagonal matrix D of random signs. It runs in O(d log d) additions and sign flips, with no multiplications at all. The lecture’s bounds, with high probability: ‖Sx‖∞ is at most about √(log d / d) ‖x‖2, and the quantization error stays O(1) for Gaussian S and O(√log d) for randomized Hadamard. To undo it, store the signs and apply the same orthogonal transform backwards.

Quantize with and without the rotation

Teal stems are the 64 numbers. Pink dots are their quantized values. Faint lines are the levels. Switch the random embedding on and watch the range, and the error, shrink.

3

Computed live on a seeded vector (63 numbers near 0.3 in size and one outlier of 6.0). The embedding is a fast Walsh-Hadamard transform with random signs, scaled by 1/√64, so it keeps the vector’s length and the error in the rotated domain equals the error after undoing it.

At B = 3 the original needs a range of 6.0. After the embedding the largest entry is a bit below 2, so the same 8 levels cover a range three times smaller and the error drops by about as much. Try B = 1: without the embedding the two levels sit at ±6, so every small number snaps to ±6. With it, the levels sit near ±1.7 and you keep a rough picture. New random signs give a different but similar result. That is the “with high probability” in the bounds.

For more on rounding error as noise, see Lecture 3. For the best levels for a known distribution, see Lecture 4. The next chapter does something sharper than a grid of levels.

A 4-bit uniform quantizer must cover one outlier, so R is set by it. Why do the small numbers suffer, and how does a random embedding help?

Chapter 9

Lattices: Better Rounding in Many Dimensions

Round a whole vector to the nearest point of a lattice, see the hexagon beat the square, and meet E8, the best 8-dimensional codebook

Chapter 8 rounded each coordinate on its own. That is the same as snapping the vector to a square grid in d dimensions. Is a square grid the best way to place a fixed number of points so that any vector lands near one? In one dimension, yes. In two or more, no.

The lecture calls the better shapes lattices. Take n independent vectors b1, …, bn in d dimensions, the basis. The lattice they generate is every combination with whole-number weights: the set of all x1b1 + … + xnbn where each xi is an integer. In matrix form that is {Bx : x ∈ Zn}, where B holds the basis vectors as columns. To quantize, round x to its nearest lattice point.

The slide draws two bases for the same lattice, Z2. For example, (1, 0) with (0, 1) is one basis, and (1, 1) with (2, 1) is another. The point set is identical, because both bases can build each other. The choice of basis changes how you write a point, not which points exist.

The square lattice is the scalar quantizer

Slide 44 makes a link. The square lattice is the product of uniform scalar quantizers. Rounding the first coordinate and the second one independently is rounding to the nearest point of the square lattice. So Chapter 8’s quantizer is a lattice quantizer, and a rather plain one.

What decides the quality? Each lattice point owns a cell: all the vectors nearer to it than to any other point. For the square lattice a cell is a square. The error is the distance from the vector to its point. To compare fairly, keep the number of points per unit area the same, so each cell has area 1. Then the mean squared error (MSE) is the average of the squared distance, over a vector that lands anywhere in a cell with equal chance.

For the square cell of side 1, the MSE is 1/12 per coordinate, which is 1/6 in two dimensions. A hexagonal cell is rounder. Its corners are closer to the centre than a square’s corners are, for the same area. The lecture states the gain: for the same density, the hexagonal lattice has lower MSE, by a factor of 5√3/9 = 0.962. That is a 3.8% cut in MSE, free, from geometry alone.

Race the square against the hexagon

Both lattices have one point per unit of area. Random points land in the plane. Each is rounded to its nearest lattice point in both lattices. Teal lines show the error of the first 120 points. Add points and watch the two averages settle.

400

Computed live with a seeded random draw. Exact values for a very large sample: square 1/6 = 0.1667, hexagonal 5/(18√3) = 0.1604, so the ratio tends to 5√3/9 = 0.9623, as in the lecture.

With few points the two averages bounce about, and the hexagon may even look worse. With a few thousand the ratio settles near 0.96. That is the usual shape of a Monte Carlo result: the claim is about the average, and a small sample shows noise. Using the same random points for both lattices makes the comparison fairer, which is why the device does.

Kissing numbers, and E8

In higher dimensions the question becomes: which lattice has the roundest cells? The lecture reaches it through packing. Place unit balls so that none overlap. The kissing number is the largest number of unit balls that can touch one central unit ball. It is 6 in the plane (the hexagon again), 12 in 3 dimensions and 240 in 8 dimensions.

That 240 comes from the E8 lattice: all x in Z8 or in (Z + ½)8 (all integers, or all halves) whose coordinates add to an even number. Maryna Viazovska won the Fields Medal in 2022 for proving that E8 gives the densest packing of identical spheres in 8 dimensions. With co-authors she later proved that the Leech lattice is optimal in 24 dimensions.

Why use E8 for rounding? Its cells are very round, and it has the same density of points as Z8: the basis on slide 47 has determinant 1. And finding the nearest point is cheap. Here is the method, known as the Conway and Sloane decoder, which the device runs.

  1. Round every coordinate to the nearest integer. If the sum is even, you hold a point of the set D8 (integer points with even sum). If the sum is odd, change the one coordinate whose rounding was worst to its other neighbour. Now the sum is even.
  2. Do it again for the half-integer points. Subtract ½ from every coordinate, repeat step 1, and add ½ back.
  3. Keep whichever of the two results is nearer to x. That is the nearest E8 point.

Round to Z⁸ and to E8

The warm bars are eight numbers. Grey marks are their nearest points of the plain grid Z⁸. Pink marks are the nearest point of E8. Draw new vectors and compare the errors.

Computed live. The average over 20,000 random vectors uses the same decoder. Exact values: Z⁸ gives 1/12 = 0.0833 per coordinate, E8 about 0.0717, so the ratio tends to 0.86.

A single vector may favour either point set, so one draw proves nothing. Only the average counts. Over many vectors the E8 average sits about 14% below the grid’s. Eight numbers, same density, 14% less squared error.

The lecture ends this stop with a use. QuIP# (Tseng and co-authors, February 2024) compresses language models with E8, at 2 to 2.5 bits per weight on average with reasonable fidelity. The slide notes that the codebook has 216 entries, which is 16 bits for 8 weights, or 2 bits per weight. It is built from a lookup table of just 28 entries, so decoding stays fast. Nearest-point search is cheap, as the decoder above shows.

Why does the hexagonal lattice give lower mean squared error than the square lattice at the same density of points?

Chapter 10

Low Rank Plus Low Precision

Split a weight matrix into a few strong directions stored with few bits, and see how a 7-billion-weight model keeps its quality at 2.4 bits

Chapter 8 and Chapter 9 shrank the numbers in a weight matrix. There is a second way to shrink it: shrink its shape. A weight matrix W with n rows and d columns holds n × d numbers. If W is built from only a few independent patterns, we can store the patterns instead of the matrix.

Singular values, in plain words

The tool is the singular value decomposition (SVD; Lecture 29 covers it in full). It says that any matrix is a sum of simple pieces. Each piece is a column vector times a row vector, called a rank-one matrix, and each comes with a strength, its singular value. List the strengths from largest to smallest: σ1 ≥ σ2 ≥ …

Keep only the strongest m pieces and you have the rank-m approximation. A classic theorem (Eckart and Young) says this is the best rank-m matrix you can build. Its error has a clean formula: the root of the sum of the squared strengths you dropped, √(σm+12 + σm+22 + …).

How much do you store? The full matrix has n × d numbers. The rank-m version is a tall matrix L of n × m and a wide matrix R of m × d, so it stores m(n + d) numbers. For n = d = 4,096 and m = 64, that is 524,288 numbers instead of 16,777,216: 32 times fewer.

Does a real model matrix have only a few strong pieces? Slide 48 plots the singular values of the query matrices of LLaMA-2 7B, on a log scale. The curve decays slowly across thousands of indices, then falls steeply at the very end. That tells us two things. There is no tiny set of directions that carries everything, so a small m alone loses detail. But the tail is not all equally important, and the first few hundred pieces carry real weight.

Low precision low rank (LPLR)

The lecture’s idea, from Saha, Srivastava and Pilanci (NeurIPS 2023), is to do both at once. Approximate A ≈ L R with m much smaller than both n and d, and store the factors with few bits: L in B bits per entry and R in B′ bits. The picture on slide 49 shows a full-precision A next to a tall L and a wide R, labelled with their bit widths.

A
The weight matrix, n rows by d columns, stored in full precision.
L
A tall factor, n by m, stored with B bits per entry.
R
A wide factor, m by d, stored with B′ bits per entry.
m ≪ min{n, d}
The rank: far smaller than either side, so L and R together hold few numbers.

Two knobs now trade against error: the rank m (how many patterns) and the bits B (how finely each is written). The device below uses a 64 × 64 matrix with a slowly decaying spectrum like slide 48’s shape. It does the real thing: truncate the SVD, round the entries of each factor with a uniform B-bit quantizer, multiply back, and measure the error.

Trade rank against bits

Left: the singular values, with the kept ones in purple. Right: relative error against rank, for your bit width (pink) and with no rounding (grey). Drag the rank and the bits.

16
4

Computed live on a seeded 64 × 64 matrix built from random orthonormal directions and the spectrum (1 + i/6)−1.1. Not a real LLaMA matrix. Storage compares m(n + d)B bits against 16 bits for every entry of the full matrix.

Slide the rank up with the bits fixed at 4 and the pink curve follows the grey one down, then flattens above it. Past some rank, the rounding error of the factors is what remains, not the dropped pieces. Now lower the bits to 2 and the pink curve lifts away much earlier. Notice the trade: a high rank at few bits can cost the same storage as a low rank at many bits, and the best mix depends on the spectrum.

CALDERA: the same idea on a language model

The lecture ends with the paper that applies it: CALDERA (Calibration Aware Low-Precision DEcomposition with Low-Rank Adaptation; Saha, Sagan, Srivastava, Pilanci, 2024). It writes each weight matrix as W ≈ Q + L R. Q is a heavily quantized copy of W, using the E8 lattice of Chapter 9 at 2 bits per weight. L R is a low-rank correction that captures what Q misses, with L and R stored in 4 or 16 bits. The baseline is QuIP#, the best quantization method as of April 2024 according to the slide.

The bit cost adds up as you would expect. The correction costs m(n + d)B / (n d) bits per weight. For a 4,096 × 4,096 matrix and rank 256 at 4 bits, that is 0.5 bits. On the wider 4,096 × 11,008 feed-forward matrices of LLaMA-2 7B it is 0.34. Averaged over the model that is about 0.4, so 2 + 0.4 gives the roughly 2.4 bits per weight in the table below.

The yardstick is perplexity, defined on the slide as the exponential of the training objective, so lower is better. As a rule of thumb, perplexity is the number of equally likely next words the model is torn between. Two test sets are used, Wiki2 and C4. The table shows LLaMA-2 results from slide 50.

Read the CALDERA table

Bars show perplexity, so shorter is better. Pick a model size and a test set, then touch a bar’s name to read its cost.

Numbers are copied from Table 1 of the CALDERA paper as shown on slide 50 (zero-shot perplexity, lower is better). Bits per weight for the unquantized models are 16. The table also lists five accuracy columns that are not plotted here.

Read the 7B bars. The unquantized model sits at 5.12 on Wiki2. The best 2.4-bit CALDERA model (rank 256, 4-bit factors) is at 6.19. The 2-bit QuIP# model with no low-rank correction is at 8.23. So the low-rank term at 0.4 extra bits closes more than half the gap. At 70B the same pattern holds: 3.12 unquantized, 4.50 for rank-64 CALDERA at 2.2 bits, 5.37 for QuIP# at 2 bits.

A 4,096 × 4,096 matrix is stored as rank-64 factors L and R with 4 bits per entry. About how many bits per original weight is that?

Chapter 11

Field Guide

Keep the numbers, the checklist and the core code, then follow the links to the lessons that go further

One idea ran through the whole lecture: let each position ask a question and blend the answers by how well they fit. Written as matrices, that is Z = softmax(QKT/√dk)V. Read as signal processing, it is an adaptive matched filter over a learned dictionary. Run in parallel, it makes heads. Stacked with feed-forward layers, residuals and position codes, it makes a transformer. Pointed at text, it steers diffusion. Its n² table and its giant weight matrices then ask for fewer bits: uniform quantizers, random rotations, lattices such as E8, and low-rank factors stored in low precision.

The numbers and terms

Term or numberWhat it saysChapter
Score aikiTq / √dk, a matched-filter output; variance 1 when entries have variance 11, 2, 3
Attention weightsRow-wise softmax: positive, each row adds to 1, so the output is a convex combination of the values2
Table size and costn × n entries; about n²d operations per layer; 2n² bytes at 16 bits per head per layer6
Convolution reach1 + 4L samples for L layers with kernel 5; attention reaches all n in one layer4
Multi-headdk = d/H; weights stay 4d² (1,048,576 at d = 512) for any H5
Original transformerd = 512, 8 heads, feed-forward width 2,048, 6 blocks5
BERT heads86.8% on the object relation (layer 8, head 10); 94.3% on the determiner relation (layer 8, head 11)5
Vision transformer input224 × 224 image, 16 × 16 patches: 196 tokens of 768 numbers6
Cross-attention in diffusionQueries from image latents; keys and values from the encoded prompt7
Griffin-LimKeep the phase of the guess, impose the target magnitude, invert; repeat7
Energy gaps8-bit integer add 30 times cheaper than 32-bit float add; multiply 18.5 times cheaper8
Uniform quantizerΔ = 2R / (2B − 1); error at most (Δ/2)√d8
Random embeddingError O(1) for Gaussian S, O(√log d) for randomized Hadamard, in O(d log d) additions8
Hexagon and E8MSE ratio 5√3/9 = 0.962 against the square; kissing numbers 6, 12, 240 in 2, 3, 8 dimensions9
QuIP#E8 codebook of 216 entries for 8 weights: 2 bits per weight9
LPLR and CALDERAA ≈ LR in low precision; bits per weight = 2 + m(n + d)B/(nd); 7B at 2.4 bits scores 6.19 against 5.12 unquantized (Wiki2)10

The checklist

  1. Say the three roles. Query: what I want. Key: what I offer. Value: what I hand over.
  2. Write the layer with shapes. Q, K, V are n × dk, n × dk, n × dv; A is n × n; Z is n × dv.
  3. Derive the shrink factor. Var(qTk) = dk, so divide by √dk.
  4. Name the signal-processing reading. Keys are atoms, scores are correlations, weights are a data-dependent convex combination.
  5. Show a task a window cannot do and attention can. Pair averaging, copy the previous token.
  6. Count heads and weights. dk = d/H, 4d² weights.
  7. Say why position codes exist. Self-attention is permutation equivariant.
  8. Price the table. n² pairs, 2n² bytes at 16 bits.
  9. Place the query and the keys in a diffusion model. Image latents ask; the prompt answers.
  10. Explain what an outlier does to a quantizer and what a random rotation fixes.
  11. Compare lattice and grid by MSE at equal density.
  12. Split bits between a rank and a precision.

The core as code

pythonimport numpy as np

def softmax(a, axis=-1):
    a = a - a.max(axis=axis, keepdims=True)          # stability
    e = np.exp(a)
    return e / e.sum(axis=axis, keepdims=True)

def attention(X, Y, Wq, Wk, Wv):
    Q, K, V = X @ Wq, Y @ Wk, Y @ Wv                  # (n,dk) (n,dk) (n,dv)
    A = softmax(Q @ K.T / np.sqrt(Q.shape[1]))        # (n,n), rows sum to 1
    return A @ V, A                                   # (n,dv)

def multi_head(X, Wq, Wk, Wv, Wo):                    # W*: lists of H matrices (d, d/H)
    heads = [attention(X, X, q, k, v)[0] for q, k, v in zip(Wq, Wk, Wv)]
    return np.concatenate(heads, axis=1) @ Wo         # (n,d)

def quantize(x, B, R=None):                           # uniform B-bit, range [-R, R]
    R = np.abs(x).max() if R is None else R
    step = 2 * R / (2**B - 1)
    return np.round((x + R) / step) * step - R

def rht(x, signs):                                    # randomized Hadamard, len(x) = 2^k
    y, h = (x * signs).copy(), 1
    while h < len(y):
        y = y.reshape(-1, 2, h)
        y = np.stack([y[:, 0] + y[:, 1], y[:, 0] - y[:, 1]], 1).reshape(-1)
        h *= 2
    return y / np.sqrt(len(y))                        # orthogonal: lengths are kept

def e8_nearest(x):                                    # Conway and Sloane decoder
    def d8(v):
        r = np.round(v)
        if r.sum() % 2:                               # odd sum: fix the worst coordinate
            i = np.argmax(np.abs(v - r))
            r[i] += 1 if v[i] > r[i] else -1
        return r
    a, b = d8(x), d8(x - .5) + .5
    return a if np.sum((x - a)**2) <= np.sum((x - b)**2) else b

Keep going

On this course: Lecture 24, deep learning sets up the networks that attention joins. Lecture 26, transformers for signals takes the block further. Lecture 27, diffusion builds the denoiser of Chapter 7 from the maths. Lecture 8 is the STFT behind Griffin-Lim. Lecture 3 and Lecture 4 are the quantizer foundations. Lecture 29 covers the matrix decompositions behind LPLR.

Elsewhere on the site: Attention and Transformers, Attention Variants, CS224N on transformers, FlashAttention, Sparsity and Quantization and Diffusion.

The takeaway. Attention lets every position ask its own question and blend the answers by fit, which is a matched filter that adapts to the input. That one move gives reach that stacked filters cannot match, and it costs an n × n table. The model sizes it enables then force the second half of the course’s question: how few bits can each number take?

Now press Present or Teach and explain one attention layer out loud, from memory: the three roles, the shapes, the square root, the matched filter, the copy trick, the heads and the bill. Then go back to the sentence at the top, choose “it”, and say why a window of 2 words cannot find “animal” while attention can.

Credit. This lesson re-teaches Lecture 25 of Stanford EE269 by Mert Pilanci (March 2, 2026), in our own words and devices. The lecture cites these sources: Xu et al. (2022), Uszkoreit (2017), Mercea et al. (2022), Bahdanau et al., Vaswani et al. (2017) and Clark et al. (2019). For compression it cites Han, Mao and Dally (2015), Horowitz (2014), Lyubarskii and Vershynin (2006), Saha, Pilanci and Goldsmith (2023), Villa-Renteria, Wang and Pilanci (2024), Tseng et al. (2024), and Saha, Srivastava, Pilanci and co-authors (2023, 2024).

EE269 Lecture 25: Attention
The course site · Course slides · Previous lecture · Next lecture · Back to Gleams