AAI, Built

Act III · The Transformer Era

Part 13 of 31

Attention as Geometry

Undergraduatestarts at this level57 min of film19 chaptersprerequisites: Part 3, Part 9, Part 10

What does a transformer compute when every character looks back at the ones before it?

The part opens on the series' own transformer reading a sentence, with an arc from each character to the earlier ones it weighs. Attention is first a weighted average: the Nadaraya-Watson smoother of 1964 on counts of 'her' in Great Expectations, with the distance score replaced by a learned affinity between a query and a key. It is also a memory read: one update of a modern Hopfield network is the same softmax formula, and its inverse temperature slides from an average of everything to the recall of one pattern. The division by the square root of d is derived from a variance, heads are shown to be low-rank maps, the causal mask decides who sees whom, and a four-block transformer is trained on the thirty novels and costed at 12 d squared weights a block. The part turns to position: sinusoids, ALiBi, no positions at all, and rotations whose scores depend only on the offset, trained side by side and stretched past their training length. It ends with what goes wrong and what heads learn: sinks, runaway scores and QK-norm, induction heads, one gradient step written as attention, and the limits of a fixed depth.

What you need. Dot products, matrix rank and rotations in the plane; the variance of a sum of independent terms; the softmax.

Mathematics and history
attention as a kernel smoother, RoPE, YaRN, sinks and gates, QK-norm, induction heads, in-context learning, expressivity
Models, data
our own small transformer

What you will be able to do

Undergraduate

  • Compute one head's output by hand: scores, softmax weights and the weighted average of the values, and say what the causal mask removes.
  • Explain why the scores are divided by the square root of d, and why attention without positions cannot tell 'dog bites man' from 'man bites dog'.

Master's

  • Derive Var(q . k) = d for independent unit-variance entries, and the softmax Jacobian that makes a saturated head hard to train.
  • Prove that rotary positions make the score depend on positions only through the offset n - m, for fixed queries and keys.
  • Count a block's parameters and matrix operations, and find the context length at which attention's work equals the weights'.

Research

  • Show that one gradient step on in-context least squares is a linear attention layer, and state what agreement between a trained layer and that step does and does not establish.
  • State the circuit-complexity bound on fixed-depth transformers with its precision assumptions, and the RASP-L conjecture on length generalization.

Engineering

  • Choose among sinusoidal, rotary, ALiBi and no positions, and extend a rotary model's context with position interpolation or YaRN and a short fine-tune.
  • Diagnose attention sinks and growing scores, and apply a sink logit, an output gate, QK-norm or a soft cap.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Undergraduate 20 min · Master's 50 min · Research 57 min · Engineering 32 min.

  1. 0Every character looks backUndergraduate2 min
  2. 1A weighted averageUndergraduate4 min
  3. 2A memory that recallsMaster's4 min
  4. 3Why divide by the square root of dUndergraduate3 min
  5. 4Heads are low-rank mapsMaster's3 min
  6. 5Who may look at whomUndergraduate3 min
  7. 6Our own transformerUndergraduate3 min
  8. 7What a block costsEngineering3 min
  9. 8Where is each character?Undergraduate3 min
  10. 9Positions as rotationsMaster's3 min
  11. 10Four answers, trained side by sideMaster's2 min
  12. 11Longer than it was trained forEngineering4 min
  13. 12Attention sinks, and three ways outMaster's3 min
  14. 13Keeping scores in rangeEngineering3 min
  15. 14Induction headsMaster's3 min
  16. 15Learning inside the promptResearch3 min
  17. 16What a transformer can computeResearch3 min
  18. 17Attention in 2026Engineering2 min
  19. Recap, problems, and what comes nextAll tracks2 min

Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.

Lecture

The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film. A dashed box stands for a number the film computes when it is rendered (hover over it to see what is computed); the README's figures for each chapter, where it lists them, follow the chapter's text.

Every character looks backUndergraduate2 min

This is a transformer reading. It's ours: we trained it on this series' thirty novels, and it's reading a sentence from the scoreboard's passage, which was excluded from gradient training. To guess each next character, every character looks back at the characters before it and decides how much each one matters. The thicker the arc, the more it looks. That look is called attention, and it powers many large language models today.

Our model has 16 of these looks, called heads, each its own way of weighing the past: here are all 16, on the same sentence. This part is about the mathematics of that look: what it computes, how it knows where things are, and what it can learn to do.

The idea is older than it looks: in 1964, a weighted average of neighbours; in 1982, Hopfield's memory that recalls; in 2014, a translator that learned where to look, and in 2017, a network of nothing but that looking. Then better positions, heads that copy and fast kernels, sinks and longer contexts, smaller memories, sparse and gated attention, and in 2026, models with full attention in only a quarter of their layers.

This is Part 13 of AI, Built, and the start of the third act: the transformer era. In it: what attention computes, as an average and as a memory; heads, masks and costs; our own transformer, trained and replayed; four ways to tell it where things are, and how to stretch them; the fixes inside today's attention blocks; and what heads learn to do, and what they cannot.

1A weighted averageUndergraduate4 min

Here are the same observations used in Part 7: occurrences of 'her' per thousand-word block of Great Expectations. This is a new normalized Gaussian kernel smoother, not the Gaussian-process posterior. Suppose we query zero-based block index one hundred and twenty. Average the observed block values with distance-based weights centered on that query. Nearby blocks receive more weight; distant Gaussian weights can be negligible, though mathematically positive. The normalized weights sum to one. Bar heights are rescaled relative to their peak, and tiny bars are omitted: they are not literal probabilities on this strip. Moving the query traces the Nadaraya-Watson estimate.

These three illustrations use bandwidths , , and blocks; they are not a claimed optimum. A narrow bandwidth can follow local variation. A wider finite bandwidth smooths more broadly; in the infinite-width limit, every observed block receives equal weight and the estimate approaches the global average. Separately, the original computation compares 40 bandwidths from 0.4 to 30 by leave-one-out mean squared error, excluding the held-out observation itself. That is different from Part 7's Gaussian-process marginal-likelihood selection.

Write it down. The guess at the query is a sum over the blocks: each block's value, times a weight. The weight is a softmax of a score: the exponential of the score, divided by the total, so the weights are positive and add up to one. Here the score is minus the squared distance divided by twice the bandwidth squared. Now deliberately change the scoring rule. Expanding a vector RBF score gives a dot product plus key-norm and query-norm terms. The query-norm term cancels within a softmax row; dot-only equivalence at matching scale needs equal key norms, otherwise a key-norm bias remains. Instead, learn the affinity between two vectors: a query and a key. That's attention, the heart of the transformer. The query asks what am I looking for; each key says what it offers; each value is what it passes on. And all three are computed from the characters by matrices the network learns. This softmax head has the normalized weighted-average form of a kernel smoother. Learned query-key affinities need not be a symmetric positive-semidefinite Gaussian-process covariance kernel.

Here is the softmax-attention definition used here. Attention scores each key against the query with a dot product divided by the square root of d, turns the scores into weights with a softmax, and returns the weighted average of the values. In 2014, Dzmitry Bahdanau, Kyunghyun Cho and Yoshua Bengio let a neural translation network look back at its source sentence, as in Part 10; in 2017 attention replaced recurrent sequence mixing, alongside feed-forward sublayers. A question: if every key is the same, what does attention return? Every weight is one over n: the plain average of the values. This softmax readout can only weigh and blend what it is given.

Here is an unscaled dot-product illustration; the earlier definition includes the square-root scale. Every key is an arrow; so is the query. The score of a key is its dot product with the query: how long both are, times how much they point the same way. The softmax turns the scores into weights. Turn the query, and the weights flow from key to key. A query is a direction to look in. Next, the same formula read another way: as a memory that reads stored values.

2A memory that recallsMaster's4 min

In 1982 the physicist John Hopfield described a network that remembers. Store some patterns of plus and minus ones by strengthening every pair of units that are on together: Hebb's rule, from Part 9. To recall, start from a cue and let each unit take the sign of the weighted vote of the others, updating one unit at a time and setting self-weights to zero. Each flip cannot raise an energy, so recall rolls downhill, into the nearest stored pattern, if all goes well. Here we store letters, a hundred units each. Give it a letter with a quarter of its pixels flipped, and let it settle.

How much can it hold? Store more and more random patterns in a hundred units, and test each with a cue in which fifteen percent of the units are flipped. The classical network falls below half its patterns at stored patterns, For random patterns, physicists computed its asymptotic capacity in 1985: about zero point one three eight patterns per unit. Every stored pattern adds a little noise to every other's vote, and the noise adds up. In 2016 Dmitry Krotov and John Hopfield sharpened the energy so that the closest pattern wins by far more, and in 2017 a team showed that an exponential energy stores exponentially many patterns.

In 2020 Hubert Ramsauer, Sepp Hochreiter and colleagues made the states continuous. The energy becomes minus a log-sum-exp of the overlaps with the stored patterns, plus a small term that keeps the state bounded. Minimize it one step at a time and the update is: weight every stored pattern by a softmax of its overlap with the current state, and add them up. Look at that formula. It is attention. The cue is the query, the stored patterns are both the keys and the values, and beta plays the part of one over the square root of d. On our letters, a sign readout after one update recovers of . And they proved a small-error, one-step retrieval bound for sufficiently separated patterns and a nearby cue. The paper's title: Hopfield Networks is All You Need.

Beta, the inverse temperature, is the knob that turns this memory into chapter one's smoother. Turn it down and the weights spread over every pattern: the result is an average of everything, with an overlap of only 0.09 with the pattern that was cued. In between, it averages a few similar patterns, a blend Ramsauer's team called a metastable state. Turn it up and one pattern takes all the weight: overlap 1.00. Attention lives on this curve, and the division by the square root of d sets where. In 2024 the Nobel Prize in Physics went to Hopfield and to Geoffrey Hinton for networks like these; Part 20 returns to their energies as a way to generate. A transformer head is a memory read: its query recalls from the keys, and returns a blend of the values.

3Why divide by the square root of dUndergraduate3 min

Take a query and a key whose d numbers are independent, with mean zero and variance one, roughly what a freshly initialized network makes. Measure how far their dot product spreads: 1.4 at d of 2, 23 at 512. It grows with the size of the vectors. Why? The dot product is a sum of d products. Each product has mean zero, since its two factors are independent. And variance one: the expected square of a product of independent numbers is the product of their expected squares. Independent terms add their variances, so the dot product has variance d: its spread grows like the square root of d. Divide by the square root of d and the variance is back to one, whatever the size: measured, 1.00 to 1.01.

Why does the spread matter? Because the softmax turns differences of scores into ratios of weights, exponentially. Feed it scores that spread like the square root of d and it stops averaging broadly: most weight concentrates on a few keys. Over keys, the entropy of the weights, a measure of how many keys share them, falls from bits at d of to at . Divided by the square root of d, the weights stay spread out, about to bits across these sizes, just under the bits of a perfectly even share.

There is a second cost, and it is worse. Training moves the scores by gradients, and those pass through the softmax's derivative. The derivative of weight i with respect to score j is p i times delta i j minus p j. When one weight is near one and the rest near zero, every term has a factor near zero: the softmax is nearly saturated, and this gradient path becomes weak. How much the weights respond peaks when the scores spread by about , and falls away on both sides. Scaled scores, with a spread of one, respond at . Unscaled at d of , the response is , and it keeps falling as the vectors grow. That is the reason Vaswani and colleagues gave in 2017. Greg Yang's mu P later argued for one over d in very wide networks; runaway scores return in chapter thirteen.

4Heads are low-rank mapsMaster's3 min

Let's write one head as matrices. Here x is the normalized input before rotations and score scaling. Character i's query is W Q times x i, and character j's key is W K times x j. Move the transpose inside, and the score is x i, times one matrix, times x j: a single by matrix, W Q K, that compares two positions of the stream. But it is a product of a tall, thin by matrix and a short, wide one, so its rank is at most . A head can only compare along directions of the stream. The same holds for what the head moves: W O times W V, also of rank at most . Nelson Elhage, Chris Olah and colleagues called these the QK and OV circuits: one decides where to look, the other what to carry.

Here are the singular values of W Q K for every one of our transformer's heads, largest first, on a log scale. These linear matrices fold in only layer norm's gain and mean subtraction, not its offset or input-dependent rescaling. At most directions per head pass the numerical cutoff; after that the values fall off a cliff, to the size of the computer's rounding error. And even within those , a head is lopsided: to directions hold ninety percent of the sum of its squared singular values. Sum a layer's pre-rotation QK matrices; the smallest rank of that sum across layers is . The summed comparison maps span many directions; each individual matrix stays low-rank.

So why split attention into narrow heads, instead of one head of ? It costs the same: heads of have exactly as many weights as one of . But each head has its own softmax, and so its own pattern. One head can make only one weighted average per character; the heads of our first layer make different ones at once: The layer's output is a sum over heads of pattern times low-rank move. There is a price: a narrow head cannot express every pattern. Srinadh Bhojanapalli and colleagues called it the low-rank bottleneck in 2020. Real models live with it, and spend their savings elsewhere: Part 15 shows how they share or compress the keys and values to make the memory of past tokens smaller.

5Who may look at whomUndergraduate3 min

A language model guesses each character from the ones before it, so attention must not see the future. Here is a grid of scores: one row for each query, one column for each key. Add minus infinity to every score above the diagonal. The exponential of minus infinity is zero, so the softmax gives the future no weight at all. This is the causal mask. Its gift is speed in training. One pass over characters makes guesses at once, each from its own past only, so every position is a training example. Check it on our transformer: change the second half of a passage. We measure the largest absolute change in raw logits, the scores before the output softmax. The change in the first half is , while the second half changes by up to . Take the mask and rotations away together, and the first half changes by . This combined ablation allows future information in.

Different masks reveal the main information flows in these transformer families. An encoder lets every position see every other. This full-attention mask alone does not enforce causality for next-token training; encoder models can generate with masked or iterative procedures. A decoder uses the causal triangle: it writes, one token at a time. The 2017 paper's translator had both. Its decoder looks at its own past, and through cross-attention at the whole source sentence: the queries come from the translation, the keys and values from the encoder's reading of the original. A prefix language model reads its prompt both ways and writes the rest left to right. Which of these won, and why, is the story of Part 14.

One more property, and a problem. Attention averages over a set. Each word gets its weight from its key, wherever it sits. So 'dog bites man' and 'man bites dog' give exactly the same average. In symbols: permute the inputs, and the outputs are permuted the same way. Without a mask and without positions, our own transformer is blind to order, to rounding error. The model must be told where each character is. That is chapter eight. The causal mask already leaks a little of it, and we will see how.

6Our own transformerUndergraduate3 min

Now build one. Each character enters as a vector, Part 3's idea, 128 numbers here. The column of vectors is the residual stream from Part 9: every layer reads from it and adds back to it. A transformer block has two halves. Attention moves information between positions: each character gathers from the ones before it. Then an MLP, a multilayer perceptron: Part 9's small network of weighted sums and bends, applied to each position on its own, like thinking over what was gathered. Each half first normalizes its input, with Part 9's layer norm: it shifts the vector's numbers to an average of zero, and rescales them to a standard size. Then the half adds its output back to the stream. Stack four blocks, read off a guess for the next character, and that is the whole machine: the mask from chapter five, the heads from chapter four.

Ours has blocks, heads in each and million numbers, and reads characters at a time. We trained it on the thirty novels, with about million sampled character targets, on an ordinary processor, without a graphics card.

Here is what it knows at each moment of its training: its score on the passage, what it writes after the same opening words, and where all sixteen heads look. At the start its guesses are random, 7.8 bits a character, a little worse than a uniform guess over its 167 characters, 7.4. It writes noise, and its attention is a blur. By step 250, 2.80 bits; 50% of the words it writes are real words, and the heads have begun to differ. By step 1,000, 2.30 bits and 83% real words. At the end, after 3,000 steps, 2.00 bits and 92% real words. Half of the whole improvement came in the first 50 steps; the rest is slow polish.

On the scoreboard, a new row: our transformer, . The reports are separated here because they score different target sets.

7What a block costsEngineering3 min

First, the numbers a block stores. Attention has four d by d matrices: queries, keys, values and the output. The MLP goes up to four d and back: eight d squared. So a block is twelve d squared, plus a few biases and layer-norm gains. Add the table that turns characters into vectors and the one that turns vectors back into guesses. For ours, with d of , blocks and characters, the formula gives , and counting the model's parameters one by one gives . Among the attention and MLP parameters, attention is ; the MLP holds the rest.

Now the arithmetic for each character. We use the matrix-FLOP counter convention, which leaves out normalization, activation and softmax arithmetic. Every matrix weight is used once per character, for one multiplication and one addition: two operations per weight. Attention adds work that no weight accounts for: the query against T keys, d numbers each, and the weighted sum of T values. Together, per character. We counted the registered matrix operations of a real forward pass with PyTorch's counter, for contexts from to characters. Jared Kaplan and colleagues' version counts only half the square, because the causal mask throws the other half away; kernels that skip the masked half really do save it. Training costs more: a forward and a backward pass came to times the forward alone, which is where the rule of six operations per weight per character comes from.

Which term wins? Per character, attention's share grows with the context, the weights' does not. Counting the causal half and neglecting the vocabulary projection, they are equal when two L T d equals twenty-four L d squared: when the context is roughly twelve times the width. For our model that is about characters, longer than anything it reads, so its cost is mostly weights. For GPT-3, tokens. But the attention term has a sting: summed over a whole text of T characters it grows as T squared, and every past key and value has to be kept to write the next character. That is why long contexts are expensive, and why Parts 15, 16 and 19 exist.

8Where is each character?Undergraduate3 min

Chapter five ended with a problem: attention cannot tell 'dog bites man' from 'man bites dog'. The 2017 paper's answer was to add a position signal to each character's vector before the first layer. Pairs of numbers oscillate at different speeds, a sine and a cosine each, from one turn every six positions to one in tens of thousands. Why sines? Because of the angle-addition formulas: moving k positions along is the same rotation of each pair, wherever you start, so a layer can learn to look a fixed distance back with one fixed matrix. Checked numerically, it holds to rounding error. And the dot product of two positions depends only on how far apart they are. GPT-2 went another way and simply learned one vector per position, 1,024 of them. That works, but a position beyond that 1,024-entry table has no entry at all.

A different idea: forget absolute positions and tell attention only how far apart two characters are. In 2018 Peter Shaw and colleagues learned a vector for each distance, and T5 learned a bias for each range of distances. In 2021 Ofir Press, Noah Smith and Mike Lewis made it as simple as possible. ALiBi adds no position vectors at all: it subtracts from each score a penalty proportional to the distance. Each head gets its own slope, from a geometric sequence: steep slopes penalize distant keys more, while shallow slopes leave them more competitive. They reported that a model trained on 1,024 tokens read 2,048 as well as a model trained at that length.

And the most surprising answer: give no positions at all. A decoder still has its causal mask, and the mask leaks position. Take a head that spreads its attention evenly over everything it may see: at position t, each of the t keys gets one over t. Its output is the average of the past. If the first token is marked, the share of that mark in the average is one over t, and a later layer can read the position off it. Adi Haviv and colleagues found in 2022 that language models without position signals still learn where they are, and Amirhossein Kazemnejad and colleagues that, on reasoning tasks, they generalize to longer inputs better than models with explicit positions. Meta's Llama 4 interleaves layers without positions among rotary ones. Rotary positions, used by many language models, are next.

9Positions as rotationsMaster's3 min

In 2021 Jianlin Su and colleagues proposed a method now used by many language models: instead of adding a position to the input, rotate the queries and keys. Take a query's thirty-two numbers in sixteen pairs; each pair is an arrow in a plane. At position m, turn pair j by m times an angle theta j. The first pair turns fast, a full turn every six characters; each pair after it turns more slowly, down to one turn in thirty-five thousand. Keys are turned the same way. Like the hands of a clock, fast hands tell you the position nearby, slow hands where you are in a long text. This is RoPE, rotary position embedding.

Why rotations? Here is the whole proof. Write R m for the rotation at position m. The score of a rotated query and a rotated key is q transposed, R m transposed, R n, k. The transpose of a rotation is the rotation backwards. And turning back by m then forward by n is turning by n minus m. For fixed queries and keys before rotation, the position factor depends only on the signed offset n minus m. The numerical check used one random pair at positions zero through thirty-nine.

Here is the same fact, seen on one pair: a query at position five and a key at position two. Their score depends on the angle between them. Now move both forward by the same amount, holding their pre-rotation content vectors fixed. Both arrows turn by the same angle, so the angle between them doesn't change, and neither does the score. For these fixed content vectors, shifting both positions equally leaves the rotated score unchanged.

And a bonus. Score a query against an identical key, with equal energy in every pair, then move them apart. The plotted score is an equal average of cosines, smoothed over nearby distances: the score oscillates as phases cancel. It is not monotone, and learned queries and keys can weight the pairs differently; this reference alone does not guarantee a recency bias. Since 2021, rotary positions have been adopted by many language models.

Which hands does a trained model actually use? In 2024 Federico Barbero and colleagues looked inside Google's Gemma: its fastest pairs build sharp positional patterns, like looking exactly one token back, while its slowest pairs, which hardly turn, seem to carry meaning. Designers have taken the hint. Qwen3-Next rotates only 64 of each head's 256 numbers and leaves the rest alone; Gemma 3 raises the global layers' base a hundredfold, from ten thousand to a million. That slows the low-frequency pairs most and leaves the fastest pair unchanged.

10Four answers, trained side by sideMaster's2 min

Now the experiment. Four small transformers, identical except for how they learn where each character is: sinusoids added to the input, rotary positions, ALiBi's linear penalty, and nothing at all. Here they are learning, replayed: held-out bits per character, step by step. Each is trained on the novels for steps of -character windows, with batches of 16, the same windows in the same order within each seed. Four heads per layer; three matched seeds. Checkpoint curves use 16 held-out prefix windows; final summaries use 48 full windows. Each run samples 2,048,000 target occurrences, not necessarily distinct corpus characters; the lines show seed means and bands the min-max range. This descriptive ordering uses display order to break ties.

First, inside the length they were trained on, the first characters.

Now read four times as far, characters, though none of them saw more than . Bits per character at each position in 48 fixed windows, three seeds each; raw seed values are averaged before plotting. The below-0.15 and at-least-0.5 groups are display thresholds, not statistical tests.

These are two extrapolation illustrations, not inferred mechanisms. ALiBi subtracts distance penalties, with slopes to . At distance , they cost and for the steepest and shallowest head. Beyond training, those penalties grow; content scores can still outweigh them. The other plot assumes an explicitly marked first token and uniform attention: its share is one over t, reaching of the training-edge share at position . Our NoPE training inserts no such marker, so this plot does not show the signal it learned. Sinusoidal and rotary coordinates also change outside the sampled training support; these illustrations do not establish which effect causes any measured loss change.

11Longer than it was trained forEngineering4 min

Our model was trained on stretches of characters. Compare times that length using 32 fixed windows and the same next-character targets for every method. The first quarter averages bits a character. The far quarter averages ; this comparison alone does not identify a cause. The gray baseline predicts those same targets using at most the last input characters, resetting the input window for later targets.

So people rescale the clocks. Position interpolation slows every hand by the same factor, , compressing position coordinates into the training span; fractional positions were not literally all sampled in training. The NTK-aware trick, named after part twelve's neural tangent kernel, slows the slow hands a lot and the fast ones hardly at all. YaRN leaves high-turn pairs alone, slows low-turn pairs fully, ramps in between, and uses a static score multiplier. On our model, with no retraining, the lowest measured far-end value among these rescalings, using display order for ties, is : bits at the far end, against for doing nothing Qwen2.5 uses YaRN with dual-chunk attention, and DeepSeek-V3 uses its own YaRN configuration, to reach a hundred and twenty-eight thousand tokens with YaRN.

Here is the static YaRN configuration tested here; its thresholds and multiplier are model-dependent choices. For each pair, count the full turns its hand makes over the training context: r, the context length over the pair's wavelength. Our fastest pair turns about times in characters; the high-turn rule leaves it alone. The slowest pairs never finish a turn, so YaRN slows them by the full factor of . In between is a ramp, gamma: zero below one turn, one above thirty-two. Each new angle blends the slowed angle and the original by gamma. In our heads, kept, on the ramp and slowed fully. The paper proposes an empirically chosen score multiplier: multiply every score by zero point one log s plus one, squared: for s of , .

A longer text also has more keys to share the weights. Say the best key scores delta above n minus one others: its weight is e to the delta over e to the delta plus n minus one. For fixed weight strictly between zero and one, the exact margin is ln of n minus one plus a constant. At large n this is approximately ln n plus that constant. We test a log-length score multiplier, unchanged through the training length. In this equal-other-scores illustration it counters dilution, but for a learned score distribution it does not guarantee fixed sharpness or entropy. David Chiang and Peter Cholak proposed it in 2022; Qwen and Llama 4 use versions of it. The lowest measured far-end value in this comparison, with display order breaking ties, is , at .

Each rescaling starts from the same saved model. Per run, updates of windows of characters: sampled next-character targets, about percent of the original sampled-target budget, from position interpolation and from YaRN; in the corner, their training loss. Dashed, before; solid, after. DeepSeek-V3 went from four thousand to a hundred and twenty-eight thousand tokens this way, with two thousand steps.

12Attention sinks, and three ways outMaster's3 min

In 2023 Guangxuan Xiao and colleagues found something strange: in large models, many heads put most of their weight on the very first token, whatever it is. They called these attention sinks, and showed that keeping the first four tokens lets a model read on for millions of tokens with a short window.

Why would a head stare at a meaningless token? Because of the softmax. Its weights must add up to one: a head cannot decline to attend. But many heads have work to do only some of the time: after a particular kind of token, say. The rest of the time, the right output is nothing. One way to add almost nothing is to put most weight on a token whose value is close to zero. A token that is always there, at the start, is the natural parking spot. Tianyu Guo, Song Mei and colleagues traced the whole syndrome to such active-dormant heads in 2024: the sink's value shrinks, and its vector in the residual stream grows enormous.

We can grow a sink on purpose. Guo's team built a task where one head is needed only some of the time. We made it from the novels' commonest characters: each character follows the novels' statistics for what comes next, except after a trigger, , where the next character copies the one before the trigger. Every sequence starts with a marker. We train a one-layer transformer for steps, three times over. After a trigger its head puts of its attention weight on the preceding character, on average.

Three recent designs give a head a better way to do nothing; we trained each on the same task, three seeds each. gpt-oss adds a learned number to the softmax's denominator, the score of an invisible key. Gated attention multiplies each head's output by a sigmoid of the input. Differential attention subtracts two softmax maps. Here is each design's start-marker coefficient during training; differential coefficients are signed, not probabilities. In large models, the gate cut the attention on the first token from 46.7 to 4.8 percent; Qwen3-Next and Kimi K3 now gate their attention.

13Keeping scores in rangeEngineering3 min

Chapter three divided by the square root of d to keep scores in range at the start. But training can grow the weights, and a score is a product of two of them: grow W Q and W K by a factor c with the layer input held fixed, and its scores grow by c squared. The charts rerun the full network, whose later hidden states can change. Here is the result for our own transformer. At c of 2, the largest score goes from to , the attention's entropy falls from bits to , and the share of rows where one key takes over ninety percent of the weight goes from to . And the model's guesses suffer: from bits a character to , and at c of . In large runs this happens by itself: in 2023 the team that trained Google's 22-billion-parameter vision transformer saw attention logits grow without bound until training diverged.

The fix the vision team used, and many language models since, is QK-norm. Before the dot product, divide each head's query and key by their root-mean-square size, then multiply by a learned gain. For nonzero query and key RMS, a vector divided by its root mean square has length exactly the square root of d. If the absolute gains stay bounded by g, Cauchy-Schwarz bounds the score magnitude by g squared times the square root of d, even as W Q and W K grow. Qwen3, GLM-4.5 and Gemma 3 all use it; Part 18 watches the logits in training, with and without it.

A gentler alternative is a soft cap: replace each score s by c times the hyperbolic tangent of s over c. Small scores pass almost unchanged; large ones level off at plus or minus c. Set c just above our trained model's largest score, , and grow the weights again: the scores can no longer pass , and . Gemma 2 capped its attention scores at fifty in 2024; Gemma 3 dropped the cap for QK-norm, which controls query and key scale before the dot product.

14Induction headsMaster's3 min

A finite probe of context use: show our transformer a held-out stretch of a novel, twice in a row.

One common motif uses two heads, in two layers. In an earlier layer, a head that only looks one step back: each character's vector now also says which character came before it. In a later layer, the second head reads an 'l' and asks: which earlier character came right after an 'l'? The 'c' in Falcon answers, because its note says: the one before me was an 'l'. So the head copies it: 'c'. Seen A then B? On seeing A again, predict B. Catherine Olsson and colleagues at Anthropic named these induction heads in 2022.

We inspect fixed probes during training, in a small attention-only model trained on random tokens with a repeated stretch inside. These are selected first-seed maps: a previous-position probe and an earliest-prior-match-successor probe, not a causal intervention. The original head score averages attention on the successor of the earliest earlier matching token over masked repeat queries in 64 fixed examples, which can differ from the planted source. Final-score pair selection uses best-candidate fallback if none pass. These finite summaries do not prove a universal onset of learning from a prompt.

Here are first-seed selected-head maps at checkpoints, beside repeat loss. Watch the saved maps rather than assuming formation. The largest logged loss-decrease marker is step . If no interval decreases, that marker selects the smallest increase. A separately corrected display metric averages the known-copy stripe over queries 60 through 78: from to across steps; repeat loss is then bits. This selected stripe window need not coincide with that marker, and association does not establish necessity or causation.

The weights provide an alignment probe, not proof of cooperation. K-composition, from Nelson Elhage and colleagues, measures how much a later head's keys read what an earlier head writes: the size of the product of its QK matrix and the earlier head's OV matrix, relative to their sizes. Two hundred Gaussian factorized-head draws have mean score about .

And our own transformer, trained on novels with no copying game at all? Its matrix probe is pre-RoPE, folding in LayerNorm gain and centering but omitting input-dependent normalization and affine offsets; it is not an exact end-to-end circuit.

15Learning inside the promptResearch3 min

Large models learn from examples in their prompt, without changing a single weight. Show one a few translations, and it translates the next. How can a forward pass learn? A forward pass is one run of the network: numbers go in, flow through each layer once, and a guess comes out. Nothing in it changes a weight. Here's a case small enough to take apart completely. Each prompt is a list of examples: four numbers x, and an answer y, which is a fixed weighted sum of them. Then a question: a new x, with the answer missing. The catch: every prompt uses different hidden weights, so one fixed regression vector cannot be used for every prompt. To answer, the model has to use the examples in front of it.

Take the simplest attention: one layer, with no softmax. Every token is an example's numbers and its answer, and attention adds to each token a weighted sum of the others. Train it on many prompts: its sampled training-batch error goes from to at the last logged checkpoint. Here are the two matrices it learned. Blue is positive, red negative. Now do something else: one step of gradient descent on the prompt's examples, starting from zero, for the least-squares loss of Part 6. The step is a sum of each answer times its x, and the prediction is a sum of each answer times how well its x matches the question: a dot product of x's, weighting the y's. That is attention, with these two matrices: an identity block that compares x's, and one entry that passes on the y's. This is the block structure the learned matrices resemble; prediction agreement is a separate measurement.

Check it on four thousand evaluation prompts. The scatter shows the first two hundred saved questions, while the correlation uses all four thousand. The GD step size was selected from fifty-nine choices on these same evaluation prompts. Each dot is one question: across, the answer from one step of gradient descent; up, the trained attention layer's answer. Johannes von Oswald and colleagues showed this in 2023.

Compare separately trained networks with one, two and three attention layers. Real transformers, with softmax attention and many layers, are messier than this, but the lesson carries over: a forward pass can run a learning algorithm on the prompt.

16What a transformer can computeResearch3 min

We have taken attention apart. What can the whole machine compute? In 2021 Gail Weiss, Yoav Goldberg and Eran Yahav wrote it down as a programming language, RASP, with only the operations a transformer has. Select builds an attention pattern from a comparison of keys and queries. Aggregate averages the selected values. And elementwise functions are the MLPs. Programs in it read like this: a histogram, how many times each token occurs, in one layer; sorting in two. Every program says how many layers and heads it needs, and in 2023 a team at DeepMind built Tracr, which compiles such programs into real transformer weights. We compiled two by hand.

The histogram first. With one-hot tokens, a head's QK matrix is a lookup table: any comparison of two tokens we like. Score each pair beta if the tokens match, and give a start marker the same score from every query. A token that occurs c times then splits its attention over its c copies and the marker, so the marker gets one over c plus one. Let only the marker carry a value, and a small ReLU layer reads the count back. The marker plays exactly the part of chapter twelve's sink. But telling one over c plus one from one over c plus two takes more bits as c grows: in bfloat16 the counts blur after ; in float16, after . Fixed precision is one reason length is hard.

Sorting takes two layers. In the first, each token selects every token smaller than itself, plus the marker: the marker's share gives its rank, how many come before it in sorted order. In the second, output position p selects the token whose rank is p and copies it. Nobody trained them: a transformer's weights can be a program.

What can't a transformer do? A fixed number of layers is a fixed amount of sequential work. William Merrill and Ashish Sabharwal proved in 2023 that a fixed-depth transformer, whose numbers have about log n bits and whose basic operations are log-space computable, can be simulated by constant-depth threshold circuits: the class T C zero. If, as most believe, that class is weaker than N C one, no fixed-depth transformer in this formal model can track a sequence of shuffles of five objects at every length. Depth matters in practice too: one layer could not build an induction head. One way to add sequential work is to generate: every new token passes through all the layers again, Part 28's story. Extra depth or recurrence are other possibilities. Hattie Zhou and colleagues propose the RASP-L hypothesis: models are more likely to generalize to longer inputs when a short causal RASP-L program solves every length, training completes, and diverse examples rule out shorter spurious shortcuts. This is a conjecture supported by experiments.

17Attention in 2026Engineering2 min

Why so much effort? Chapter seven's arithmetic, for a model as wide as DeepSeek-V3: at four thousand tokens, attention costs 0.05 of the weights; at a million, 12 times as much. Long contexts made attention the expensive part.

Many models in 2026 still compute this formula somewhere. What has changed is where, and how much. Inside the attention block, the fixes of the last few chapters: sink logits, output gates, QK-norm, and layers with no positions at all. The keys and values every past token leaves behind have been shrunk: shared between heads, or rebuilt from a small latent vector, the low-rank idea of chapter four applied to memory. Many models look at only part of the past: a sliding window, or a small, fast indexer that picks a few thousand past tokens for each query. And some replace most of their attention layers with a fixed-size memory that is updated as they read: three such layers for every attention layer in Qwen3-Next and Qwen3.5.

Here is what such a hybrid looks like: Kimi K3, released in 2026, has 93 layers, and only 24 of them are full attention. The rest keep a fixed-size memory, updated as they read. Why keep any attention at all? Because attention can look back at the stored keys and values for past tokens, while a fixed memory has to decide what to forget. A few attention layers keep the recall, the rest keep the cost down. How that memory works, and why it is attention in disguise, is where we go next, through the lineage of the models themselves in Part 14, to memory in Part 15.

Recap, problems, and what comes nextAll tracks2 min

Let's take stock. Softmax attention has a normalized weighted-average form related to Nadaraya-Watson smoothing, with learned affinities, and connects to modern Hopfield memory reads; the recall thumbnail uses a sign readout. Dividing by the square root of d controls initial score variance under independent-component assumptions; learned scores can still saturate. Heads compare and move along a few directions, the mask decides who sees whom, and our block has twelve d squared plus nine d parameters: bias-free QKVO, a biased four-d-width MLP and two affine LayerNorms. Its matrix-multiply work grows with context; that count omits vocabulary projection and elementwise arithmetic. Our transformer reached bits a character over its 21,376 scored passage targets. Positions can be added, rotated, penalized or left out, and stretched with care. A sink logit changes the softmax denominator with a null option; an output gate attenuates the weighted write. These act at different stages. Probes investigate copying and gradient-step-like maps, and we hand-compile programs, within limits. More layers, recurrence, or generated steps can relax some depth limits.

This comes back everywhere: the models built on this block in Part 14; the memory of keys and values in Part 15; attending to only some of the past in Part 16; long contexts and runaway logits in Part 18; fast serving in Part 19; thinking past a fixed depth in Part 28; and circuits in real models in Part 30.

Here are six problems to try, from the variance of a dot product to gradient descent written as attention. Pause here and work through them; full solutions are in this part's notes.

Next time: the lineage. The block we built today, stacked and scaled from a translation model in 2017 to GPT-3, ChatGPT and the open-weight frontier of 2026; and our own GPT-style and BERT-style models, trained side by side on the novels.

Anthropic's 'Mathematical Framework for Transformer Circuits' is the best next read. Thanks for watching, and see you in Part 14.

Where it goes next. The block built here is stacked and scaled in Part 14; its keys and values become the cache of Part 15; attending to only some of the past is Part 16; long contexts and runaway logits return in Part 18 and fast serving in Part 19; thinking past a fixed depth is Part 28, and circuits in real models are Part 30.

Key results

The part's results in one place, for revision.

Attention\(\displaystyle \operatorname{Attn}(q)=\sum_j p_j v_j,\qquad\allowbreak p=\operatorname{softmax}_j\Bigl(\frac{q\cdot k_j}{\sqrt d}\Bigr)\)
Why the square root of d\(\displaystyle \operatorname{Var}(q\cdot k)=d\,\sigma_q^2\sigma_k^2\)
A Hopfield read\(\displaystyle \xi^{\text{new}}=X^\top\operatorname{softmax}(\beta X\xi)\)
Rotary positions\(\displaystyle (R_mq)^\top(R_nk)=q^\top R_{n-m}\,k\)
What a block costs\(\displaystyle 12d^2+9d\ \text{weights};\qquad\allowbreak 2LTd=24Ld^2\iff T=12d\)
A gradient step as attention\(\displaystyle \hat y=\frac{\eta}{N}\sum_{i=1}^{N}y_i\,(x_i\cdot x_q)\)

Try it

Lab 13 · Learning inside the prompt: attention against one gradient step

Each prompt holds 16 examples (x, y) of its own hidden linear rule and a question. Train a one-layer, softmax-free attention on such prompts with the series' autodiff, then compare its answers and its learned matrices with one step of gradient descent on the prompt's examples.

Figure produced by Lab 13: Learning inside the prompt: attention against one gradient step
Produced by the lab below, seed 0, in 0.9 s.
python -m videos.ai.labs 13 needs numpy, scipy, matplotlib · download lab13.py · source on GitHub
one prompt: gradient step / attention form        +1.414586 / +1.414586
error before training / after                     4.05 / 0.976   (answering 0 costs 4.00)
error of one gradient step                        0.962   (theory 0.952)
correlation of the two answers                    0.9979   on 4,000 new prompts
learned step size (mean diagonal of the x block)  0.756   (best step N/(N+d+1) = 0.762)
distance of the x block from a multiple of I      0.050

Nothing told the layer about gradient descent, yet training on prompts alone drives it to an identity block that compares x's and one entry that passes on the y's: the same map as one least-squares step.
The code (110 lines; it asserts its own result)
"""Lab 13: train one layer of linear attention to learn inside the prompt, and compare it with a gradient step."""

import numpy as np

from videos.coursekit import labs
from explainer.ai.autodiff import Tensor

TITLE = "Learning inside the prompt: attention against one gradient step"
GOAL = ("Each prompt holds 16 examples (x, y) of its own hidden linear rule and a question. Train a one-layer, "
        "softmax-free attention on such prompts with the series' autodiff, then compare its answers and its learned "
        "matrices with one step of gradient descent on the prompt's examples.")
TASKS = [
    "Change the number of examples N from 16 to 4 and to 64. How do the learned step size and the error move?",
    "Add noise to the answers (y += 0.5 * rng.standard_normal) and retrain. Does the layer learn a smaller step?",
    "Give x unequal scales (multiply its first coordinate by 3). Is the learned x block still a multiple of I?",
]

D, N = 4, 16  # numbers per x, examples per prompt


def prompts(rng, B):
    """B prompts: G[b] = (1/N) sum_i z_i z_i^T over the example tokens z_i = (x_i, y_i); the question token
    z_q = (x_q, 0); the true answer w . x_q; and the examples themselves."""
    X = rng.standard_normal((B, N, D))
    w = rng.standard_normal((B, D))
    y = np.einsum("bnd,bd->bn", X, w)
    Z = np.concatenate([X, y[:, :, None]], axis=2)
    xq = rng.standard_normal((B, D))
    zq = np.concatenate([xq, np.zeros((B, 1))], axis=1)
    return np.einsum("bnj,bnk->bjk", Z, Z) / N, zq, np.einsum("bd,bd->b", w, xq), (X, y, xq)


def attention(P, Q, G, zq):
    """Linear attention's answer at the question: (1/N) sum_i (P . z_i) (z_i^T Q z_q).  Keys and queries are
    compared through Q; P reads the value that each example passes on."""
    read = (Tensor(G) * P).sum(axis=1)  # for each prompt: sum_i (P . z_i) z_i^T / N
    return ((read @ Q) * Tensor(zq)).sum(axis=1)


def gd_step(X, y, xq, eta):
    """The prediction after one gradient step from w = 0 on L(w) = (1/2N) sum_i (w . x_i - y_i)^2, by autodiff."""
    w = Tensor(np.zeros(D), requires_grad=True)
    (((Tensor(X) @ w - y) ** 2).sum() * (0.5 / len(y))).backward()
    return float((w.data - eta * w.grad) @ xq)


def run(seed=0):
    rng = np.random.default_rng(seed)
    lab = labs.Lab()
    eta_star = N / (N + D + 1)  # the step that minimizes the expected error for Gaussian x: E[S^2] = (N + D + 1)/N I

    # the algebra first: a gradient step is linear attention with keys x_i, query x_q and values (eta/N) y_i
    _, _, _, (X, y, xq) = prompts(rng, 1)
    by_gd = gd_step(X[0], y[0], xq[0], eta_star)
    by_attention = eta_star / N * float(np.sum(y[0] * (X[0] @ xq[0])))
    lab.row("one prompt: gradient step / attention form", f"{by_gd:+.6f} / {by_attention:+.6f}")
    assert abs(by_gd - by_attention) < 1e-10, "one gradient step from zero is linear attention"

    P = Tensor(0.1 * rng.standard_normal((1, D + 1, 1)), requires_grad=True)
    Q = Tensor(0.1 * rng.standard_normal((D + 1, D + 1)), requires_grad=True)
    params, m, v, curve = [P, Q], [0.0, 0.0], [0.0, 0.0], []
    for t in range(1, 1501):  # Adam on fresh prompts every step
        G, zq, target, _ = prompts(rng, 256)
        for p in params:
            p.grad = np.zeros_like(p.data)
        loss = ((attention(P, Q, G, zq) - target) ** 2).mean()
        loss.backward()
        curve.append(float(loss.data))
        for i, p in enumerate(params):
            m[i] = 0.9 * m[i] + 0.1 * p.grad
            v[i] = 0.999 * v[i] + 0.001 * p.grad ** 2
            p.data -= 0.02 * (m[i] / (1 - 0.9 ** t)) / (np.sqrt(v[i] / (1 - 0.999 ** t)) + 1e-9)

    G, zq, target, (X, y, xq) = prompts(rng, 4000)
    answer = attention(P, Q, G, zq).data
    step = eta_star / N * np.einsum("bn,bnd,bd->b", y, X, xq)  # one gradient step, on every test prompt
    mse, mse_step = np.mean((answer - target) ** 2), np.mean((step - target) ** 2)
    corr = np.corrcoef(answer, step)[0, 1]
    p, q = P.data[0, :, 0], Q.data
    M = p[D] * q[:D, :D] + np.outer(p[:D], q[D, :D])  # what multiplies w^T S ... x_q in the layer's answer
    off = np.linalg.norm(M - eta_star * np.eye(D)) / np.linalg.norm(eta_star * np.eye(D))
    lab.row("error before training / after", f"{curve[0]:.2f} / {mse:.3f}   (answering 0 costs {D}.00)")
    lab.row("error of one gradient step", f"{mse_step:.3f}   (theory {D * (1 - eta_star):.3f})")
    lab.row("correlation of the two answers", f"{corr:.4f}   on 4,000 new prompts")
    lab.row("learned step size (mean diagonal of the x block)", f"{np.trace(M) / D:.3f}   (best step N/(N+d+1) = {eta_star:.3f})")
    lab.row("distance of the x block from a multiple of I", f"{off:.3f}")
    lab.note = ("Nothing told the layer about gradient descent, yet training on prompts alone drives it to an identity "
                "block that compares x's and one entry that passes on the y's: the same map as one least-squares step.")
    assert abs(mse_step - D * (1 - eta_star)) < 0.12, "the gradient step's error matches d (1 - eta*)"
    assert abs(mse - mse_step) < 0.1 * mse_step, "the trained layer is as good as the best single gradient step"
    assert corr > 0.97, "and gives nearly the same answers"
    assert off < 0.2, "its matrices have the gradient step's block structure"

    fig, ax = labs.figure(2, size=(11, 4.4))
    shown = p[D] * q
    lim = np.abs(shown).max()
    im = ax[0].imshow(shown, cmap="RdBu", vmin=-lim, vmax=lim)
    names = [f"x{i + 1}" for i in range(D)] + ["y"]
    ax[0].set_xticks(range(D + 1), names)
    ax[0].set_yticks(range(D + 1), names)
    ax[0].grid(False)
    ax[0].set(title="The learned query-key matrix (blue positive)", xlabel="question's coordinate", ylabel="example's coordinate")
    fig.colorbar(im, ax=ax[0], shrink=0.8)
    ax[1].scatter(step[:400], answer[:400], s=8, color=labs.BLUE, alpha=0.7, label=f"400 prompts, correlation {corr:.3f}")
    r = np.abs(step[:400]).max()
    ax[1].plot([-r, r], [-r, r], color=labs.GOLD, lw=1.2, label="equal answers")
    ax[1].set(title="Trained attention against one gradient step", xlabel="answer of one gradient step", ylabel="answer of the attention layer")
    ax[1].legend(loc="upper left")
    lab.fig = fig
    return lab

Now change it

  1. Change the number of examples N from 16 to 4 and to 64. How do the learned step size and the error move?
  2. Add noise to the answers (y += 0.5 * rng.standard_normal) and retrain. Does the layer learn a smaller step?
  3. Give x unequal scales (multiply its first coordinate by 3). Is the learned x block still a multiple of I?

Problems, with solutions

Try each problem before opening its solution.

1. Why √d. If the entries of q and k are independent with mean 0 and variances σ_q² and σ_k², show that Var(q·k) = d σ_q² σ_k². What should the score be divided by?

Solution

q·k = Σᵢ qᵢkᵢ. Each term has mean E[qᵢ]E[kᵢ] = 0 and variance E[qᵢ²]E[kᵢ²] = σ_q²σ_k², by independence; the d terms are independent, so their variances add: d σ_q²σ_k². Dividing by √d σ_q σ_k gives variance one; at initialization, with unit variances, that is the √d of the formula.

2. Relative by construction. Fix the unrotated vectors q and k and each pair's frequency θⱼ. Let R_m rotate each pair by mθⱼ. Show that the explicit position dependence of (R_m q)·(R_n k), with q and k held fixed, is only through n − m. Show that ALiBi's bias −m_h(i − j), with fixed slope m_h, also depends only on an offset.

Solution

(R_m q)·(R_n k) = qᵀ R_mᵀ R_n k. A rotation's transpose is its inverse, R_mᵀ = R_{−m}, and rotations of the same pair commute: R_{−m} R_n = R_{n−m}. The score is qᵀ R_{n−m} k. ALiBi's bias is a function of i − j. Both expressions are unchanged by a common position shift when their unrotated vectors or slope remain fixed. This does not assert that the hidden representations or final attention weights of a trained network depend only on relative position.

3. What a block costs. For our bias-free QKVO, biased MLP of width 4d and two affine LayerNorms, show 12d² + 9d parameters per block. In the dominant causal-half matrix-FLOP convention, show that attention's 2LTd FLOPs per token equal the leading linear-map term 24Ld² at T = 12d. Omit vocabulary projection and elementwise work.

Solution

W_Q, W_K, W_V, W_O contribute 4d². The MLP has 8d² weights and 4d + d biases. Two LayerNorms have gain and bias vectors totaling 4d. Thus the block has 12d² + 9d parameters: 197,760 at d = 128. Counting a multiply and add per matrix weight gives the leading linear-map term 24Ld² per token. Equating the two stated leading matrix terms gives 2LTd = 24Ld², hence T = 12d: 1,536 for d = 128 and 147,456 for GPT-3's d = 12,288. This convention omits vocabulary projection, normalization, activation, softmax, bias additions and lower-order terms; it is not an equality of total model computation.

4. A place to put nothing. A head has a sink logit b and n keys with equal scores s. What share of its attention goes nowhere? For which b is it one half?

Solution

The share is e^b / (e^b + n e^s). It is one half when e^b = n e^s, that is b = s + ln n: a sink must outscore the keys by the log of their number to absorb half the weight.

5. Temperature. Fix a finite matrix X of stored patterns and the cue ξ for one continuous update ξ_new = Xᵀ softmax(βXξ). Show that β → ∞ returns the uniquely largest-overlap pattern when it is unique; ties give the average of the maximizing patterns. Show that β → 0 gives the average of all patterns. Apply no sign readout.

Solution

The weights are pᵢ ∝ exp(β xᵢ·ξ). For a unique maximum, every smaller-overlap weight vanishes relative to its weight as β → ∞. If r patterns tie for the maximum, their identical exponents give each limiting weight 1/r, with all other weights tending to zero. The continuous result is their arithmetic mean. As β → 0 every exponent tends to 1, so the update is (1/M) Σᵢ xᵢ. These are limits of one continuous update at a fixed cue, not claims about a subsequent sign readout, iterated attractors or retrieval accuracy.

6. A gradient step as linear attention. Show that one step of gradient descent from w = 0 on L(w) = (1/2N) Σᵢ (w·xᵢ − yᵢ)² predicts ŷ = (η/N) Σᵢ yᵢ (xᵢ·x_q) for a query x_q.

Solution

∇L(w) = (1/N) Σᵢ (w·xᵢ − yᵢ) xᵢ. At w = 0, w₁ = −η∇L(0) = (η/N) Σᵢ yᵢ xᵢ, so ŷ = w₁·x_q = (η/N) Σᵢ yᵢ (xᵢ·x_q). This has an unnormalized dot-product linear-attention form: query x_q, keys xᵢ, and scaled values (η/N)yᵢ. It uses no softmax, and its coefficients can be signed. This algebraic identity alone does not show that a trained attention layer implements gradient descent internally.

Notes and sources

Glossary

English 中文
attention; query, key, value 注意力;查询,键,值
kernel smoother (Nadaraya–Watson), bandwidth 核平滑器(纳达拉亚–沃森),带宽
scaled dot-product attention 缩放点积注意力
softmax saturation, Jacobian softmax饱和,雅可比矩阵
inverse temperature (β) 逆温度(β)
modern Hopfield network, metastable state 现代霍普菲尔德网络,亚稳态
attention head, multi-head attention 注意力头(头),多头注意力
QK circuit, OV circuit QK回路,OV回路
low rank, low-rank bottleneck 低秩,低秩瓶颈
causal mask 因果掩码
encoder, decoder, cross-attention, prefix language model 编码器,解码器,交叉注意力,前缀语言模型
permutation equivariance 置换等变性
transformer block Transformer模块
FLOPs per token 每个词元的浮点运算数
sinusoidal position encoding, learned absolute positions 正弦位置编码,学出来的绝对位置
relative positions, ALiBi 相对位置,ALiBi
no positional encoding (NoPE) 无位置编码(NoPE)
rotary position embedding (RoPE), wavelength, base 旋转位置编码(RoPE),波长,底数
context extension 上下文扩展
position interpolation, NTK-aware scaling, YaRN 位置插值,NTK感知缩放,YaRN
ramp (γ), attention temperature 斜坡(γ),注意力温度
log-n scaling log n缩放
attention sink, sink logit 注意力汇点,汇点logit
active–dormant head, value drain 活跃-休眠头,值的排空
gated attention (output gate) 门控注意力(输出门控)
differential attention 差分注意力
QK-norm QK归一化
soft cap (logit soft-capping) 软上限(logit软封顶)
induction head, previous-token head 归纳头,前一词元头
K-, Q-, V-composition K组合,Q组合,V组合
phase change (in training) (训练中的)相变
in-context learning, linear self-attention 上下文学习,线性自注意力
RASP; select, aggregate RASP;选择(select),聚合(aggregate)
Tracr Tracr
threshold circuit, TC⁰, NC¹ 阈值电路,TC⁰,NC¹
hybrid (linear + full attention) 混合架构(线性注意力加完整注意力)
About this partfrom its README

Part 13 opens the Transformer act of the series. It develops attention as a learned weighted average and memory read, then examines heads, masks, cost, position, longer contexts, sinks, induction and in-context learning. The CPU producer implementations are in compute.py.

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. Attention as Nadaraya–Watson; modern Hopfield networks = attention.
  2. √d from variance.
  3. Heads as low-rank maps; causal masks.
  4. Encoder, decoder, encoder–decoder (the 2017 paper's translation model; the lineage is Part 14).
  5. FLOP and parameter count per block.
  6. Positions: sinusoidal, ALiBi, RoPE with relative position proved, NoPE.
  7. Context extension: PI, NTK-aware, YaRN; log-n scaling.
  8. Sinks and sink logits; gated attention; differential attention.
  9. QK-norm and soft caps.
  10. Induction heads measured in our transformer (K-composition); ICL as gradient descent (computed).
  11. RASP and what a fixed-depth transformer can compute (TC⁰).
  12. Scoreboard row.

中文讲义

本讲的中文部分(与英文版对应)。

习题与解答

1. 为什么是根号d。 设q和k的各个分量相互独立,均值为0,方差分别为σ_q²和σ_k²。证明 Var(q·k) = d σ_q² σ_k²。分数应该除以什么?

解答

q·k = Σᵢ qᵢkᵢ。由独立性,每一项的均值是 E[qᵢ]E[kᵢ] = 0,方差是 E[qᵢ²]E[kᵢ²] = σ_q²σ_k²;d个项相互独立,方差相加,得 d σ_q²σ_k²。除以 √d σ_q σ_k,方差就变成1;初始化时方差为1,这就是公式里的根号d。

2. 天生就是相对的。 固定旋转前的向量q、k和每对分量的频率θⱼ。设R_m把每对旋转mθⱼ。证明:保持q、k不变时, (R_m q)·(R_n k)的显式位置依赖只通过n − m;固定斜率m_h时,ALiBi偏置−m_h(i − j)也只依赖位置差。

解答

(R_m q)·(R_n k) = qᵀ R_mᵀ R_n k。旋转的转置是其逆,R_mᵀ = R_{−m};同一对的旋转可交换, R_{−m} R_n = R_{n−m},因此分数为qᵀ R_{n−m} k。ALiBi偏置是i − j的函数。保持旋转前向量或斜率不变,同时平移两个位置, 这两个表达式不变。这不表示训练网络的隐表示或最终注意力权重只依赖相对位置。

3. 一个模块的成本。 对我们的无偏置QKVO、带偏置4d宽MLP和两个仿射LayerNorm,证明每个模块有12d² + 9d个参数。 只按主导的因果半矩阵FLOP口径,证明注意力每词元的2LTd FLOP在T = 12d时等于主要线性映射项24Ld²;忽略词表投影和逐元素运算。

解答

W_Q、W_K、W_V、W_O贡献4d²。MLP有8d²个权重和4d + d个偏置。两个LayerNorm的增益与偏置合计4d。 因此每块有12d² + 9d个参数,d = 128时为197,760。按每个矩阵权重一次乘法加一次加法,主要线性映射每词元共24Ld² FLOP。 令给定的两个主导矩阵项相等,2LTd = 24Ld²,得T = 12d:d = 128时为1,536,GPT-3的d = 12,288时为147,456。 这个口径省略词表投影、归一化、激活、softmax、偏置加法和低阶项,不表示模型总计算量相等。

4. 一个放“什么都没有”的地方。 一个头有汇点logit b,以及n个分数都等于s的键。它有多少注意力哪儿也没去?b取多少时是一半?

解答

份额是 e^b / (e^b + n e^s)。当 e^b = n e^s,也就是 b = s + ln n 时,它等于一半:汇点的分数要比那些键高出键数的对数, 才能吸走一半的权重。

5. 温度。 固定有限个存储模式组成的矩阵X和本次更新的查询ξ。对一次连续更新ξ_new = Xᵀ softmax(βXξ),证明: β → ∞时,若最大重叠模式唯一,就返回该模式;若并列,就返回所有最大者的平均。β → 0时返回全部模式的平均。此处不作符号读出。

解答

权重pᵢ ∝ exp(β xᵢ·ξ)。最大值唯一时,β → ∞使其他项的权重相对它趋于零。若r个模式并列最大,它们的指数相同, 各自的极限权重为1/r,其他模式的权重趋于零;连续输出为这些最大者的算术平均。β → 0时,每个指数趋于1,输出为(1/M) Σᵢ xᵢ。 这是固定查询下的一次连续更新极限,不是后续符号读出、迭代吸引点或召回准确率的结论。

6. 把一次梯度步写成线性注意力。 在L(w) = (1/2N) Σᵢ (w·xᵢ − yᵢ)²上,从w = 0出发走一步梯度下降,证明对查询x_q的预测为 ŷ = (η/N) Σᵢ yᵢ (xᵢ·x_q)。

解答

∇L(w) = (1/N) Σᵢ (w·xᵢ − yᵢ) xᵢ。在w = 0处,w₁ = −η∇L(0) = (η/N) Σᵢ yᵢ xᵢ,因此 ŷ = w₁·x_q = (η/N) Σᵢ yᵢ (xᵢ·x_q)。式子具有不带softmax的点积线性注意力形式:查询为x_q、键为xᵢ、缩放后的值为(η/N)yᵢ。 系数可以有正有负。这个代数恒等式本身不能证明训练后的注意力层在内部实现了梯度下降。

Build the film

python -m videos.ai.ai13.compute        # the part's numbers, into .cache/ai13
python tools/build.py ai13                  # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py ai13 Hook   # one chapter, silent, with a contact sheet

Scenes: videos/ai/ai13. Setup: see the course page. Source of these notes: the README and the scenes' narration.