AAI, Built

Act III · The Transformer Era

Part 15 of 31

Memory

Undergraduatestarts at this level52 min of film17 chaptersprerequisites: Part 10, Part 11, Part 13, Part 14

What should a model keep of everything it has read, and what can it afford to forget?

The part opens with the bill for remembering everything: a key and a value for every token in every layer, tens of gigabytes for one long conversation with Llama 3.1. It first shrinks that cache, by sharing keys and values between heads, by DeepSeek's latent attention, and by evicting tokens while keeping the attention sink. Then it drops the softmax: regrouped, attention becomes a recurrence on one matrix, the fast weights of 1992, written by outer products and read with a key. Hopfield's network and a count of overlaps show why adding fills up with crosstalk; decay forgets on purpose, and the delta rule, one step of least squares per token, corrects. An associative scan and chunks in the WY form train such recurrences in parallel, and state-space models reach the same place from control theory, with Mamba letting each input choose its step. The part turns at a recall test, where six small models show what a fixed memory can and cannot look up, and at the hybrids that keep attention in one layer of four. It ends with how long a context really is, retrieval as a memory outside the model, and the open bets of 2026.

What you need. Matrix products and outer products, eigenvalues of a rank-one update, and a first-order linear differential equation.

Mathematics and history
KV caches, GQA and MLA, linear attention, SSMs, the (gated) delta rule, test-time training, hybrids, retrieval
Models, data
DeepSeek, Qwen3-Next, Kimi Linear

What you will be able to do

Undergraduate

  • Price a KV cache from layers, key-value heads, head size and context length, and say what grouped queries and latent attention save.
  • Explain how regrouping the product turns attention without a softmax into a fixed-size memory that is written with outer products and read with a key.

Master's

  • Show that N random unit keys in d dimensions give a relative read error of about (N - 1)/d when pairs are added.
  • Derive the delta rule as one gradient step on the squared read error, and find the eigenvalues of I - beta k k^T for a projection and a reflection.
  • Show that the scan operator is associative, and derive the zero-order hold for a linear state-space model.

Research

  • Classify linear attention, decay, the delta rule, the gated delta rule, Titans and softmax attention as online learners: name each one's loss and optimizer.
  • State what remains open: how much attention a hybrid needs, how a fixed memory should grow, and how to measure what a model does with a million tokens.

Engineering

  • Choose a cache policy (a window, kept sink tokens, heavy hitters) and say what each risks evicting.
  • Judge a long-context claim against needle, RULER and NoLiMa style tests, and decide between a longer window, a hybrid and retrieval, with the kNN-LM's bound on what a wrong neighbour costs.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Undergraduate 17 min · Master's 45 min · Research 52 min · Engineering 26 min.

  1. 0Everything it has readUndergraduate3 min
  2. 1The cacheUndergraduate3 min
  3. 2Keeping less of the cacheEngineering3 min
  4. 3Attention without the softmaxUndergraduate2 min
  5. 4A matrix that remembersUndergraduate4 min
  6. 5Forgetting and correctingMaster's3 min
  7. 6The delta rule as geometryMaster's3 min
  8. 7Training a recurrence in parallelMaster's4 min
  9. 8State-space modelsMaster's4 min
  10. 9Selectivity: Mamba and afterMaster's3 min
  11. 10A memory that learnsResearch3 min
  12. 11A recall testMaster's2 min
  13. 12HybridsEngineering3 min
  14. 13How long is a context, really?Undergraduate3 min
  15. 14Retrieval as memoryEngineering3 min
  16. 15The frontier, late 2026Research3 min
  17. 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.

Everything it has readUndergraduate3 min

Every token a transformer reads, it keeps: a key and a value, in every layer. For Llama 3.1 with seventy billion parameters, each number stored in bf16, sixteen bits or two bytes, that's 320 kilobytes a token. A long conversation, a hundred and twenty-eight thousand tokens, needs 39 gigabytes of memory, just to remember what it has read.

The alternative is to read like we do: keep a memory of a fixed size, and update it as each word arrives. Then the question is what to keep, and what to forget.

How we got here. In 1982 John Hopfield built a network that stores memories in its connections and returns to one when given a piece of it. In 1992 Jürgen Schmidhuber had one network write, token by token, the weights of another: fast weights, the idea at the heart of this part. In 1997 the LSTM gave a recurrent network a memory cell with gates, Part 10's story. In 2014 neural Turing machines and memory networks read and wrote a memory with attention. In 2017 the transformer simply kept everything. From 2019, Transformer-XL reached further back, and Longformer and BigBird looked at less of it. In 2020 linear attention turned a transformer back into a recurrent network, and retrieval put a memory outside the model. Then came state-space models, retrieval from trillions of tokens, and Mamba, a memory that chooses what to keep. And by 2026, the frontier's open models make three of every four layers a fixed-size memory, and read a million tokens.

This is Part 15 of AI, Built: memory. First, attention's own memory: the cache, how models shrink it, and what can be thrown away. Then a matrix as a memory, from Hopfield and fast weights to linear attention. How to write to it, and how to train such a memory on a whole text at once. State-space models, and memories that learn while they read. Then we measure which memories can look things up, and mix them. And last, long contexts, how well they really work, and memory outside the model. Every model in this part is trained here, and we'll watch each one learn.

1The cacheUndergraduate3 min

When a model writes, it makes one token at a time, and each new token's query looks at every earlier token's key and value. Recomputing all of those for every new token would be wasteful, so the model keeps them: the KV cache. The cache grows with every token, and every new token has to read all of it. Serve many long conversations at once, and this memory, not the model's weights, is what fills the graphics cards.

How big is it? Take Llama 3.1, seventy billion parameters, eighty layers. If every attention head kept its own keys and values, each token of context would cost 2.5 megabytes. Llama shares: its sixty-four query heads are split into eight groups, and each group shares one key and one value. That's 8 times less, 320 kilobytes a token, and the quality barely changes. Noam Shazeer's multi-query attention, in 2019, went all the way: one key and one value for every head, 40 kilobytes here, but it costs some quality; grouped queries, from Joshua Ainslie and colleagues in 2023, are the compromise. DeepSeek-V3 goes further, and so does the hybrid Qwen3-Next. Let's see how.

DeepSeek's trick is multi-head latent attention. A latent is a short hidden summary from which the full thing can be rebuilt. Each token is squeezed into a short latent vector, 512 numbers, and only that is cached. Keys and values for all 128 heads are unpacked from it by two more matrices when needed. And they don't even need to be unpacked: since a query's score is a product of matrices, the key's matrix can be folded into the query, part three's linear algebra, so attention reads the latent directly. Against full attention of the same shape, that's 71 times less memory.

There's a catch, and it's part thirteen's rotations. Without positions, the key matrix folds into the query once, and every cached latent is scored directly. We checked it with random weights: identical, to rounding error. But with rotary positions, the query is rotated by its position and the key by its own, and what's left between them is a rotation by their distance. It sits in the middle and changes with every pair, so there's no single matrix to fold. Folding anyway gives scores off by 18 percent. DeepSeek's answer is to decouple: the positions go into a small extra key, the same for every head, cached next to the latent, 512 numbers plus 64. The content part folds as before, and the scores match exactly again. Serving this cache fast, paging it, sharing it between conversations and storing it in fewer bits, is Part 19's subject. Here we ask what a memory should keep.

2Keeping less of the cacheEngineering3 min

The cache can't grow forever, so the first question is which tokens a model can do without. Full attention lets every token look at every earlier one. In 2019 Rewon Child's Sparse Transformer looked only at a window of recent tokens, plus a strided pattern, and in 2020 Longformer kept a window and added a few global tokens that see and are seen by everything. BigBird added a few random keys too, and proved that this sparse pattern can still compute anything full attention can. Sparse reads cut computation; a sliding window permits eviction, while arbitrary old random keys must remain available. Transformer-XL, in 2019, went the other way: it cached the previous segment's states and let each segment read them, so a stack of layers reaches many segments back.

A sliding window has a hidden flaw, found in 2023 by Guangxuan Xiao and colleagues. Part 13 showed that many heads park their attention on the very first token, an attention sink, when they have nothing to do. Here is the series' own model, the one trained on the thirty novels: each square is a head, and the number is the share of its attention that lands on the first token of the window. Spread evenly, the first token would get percent. Instead,

That matters for the cache. We had the series' model read the first tokens of the scoreboard's passage one at a time, as a server would, with room for only tokens of keys and values per head, positions counted inside the cache.

A second idea, H2O from Zhenyu Zhang and colleagues, also in 2023, is to keep the tokens that matter. Add up the attention each cached token has drawn so far; when the cache is full, evict the one with the least, but always keep a window of the most recent ones. A few heavy hitters draw most of the attention, and the sink is one of them. Here are the three policies on the same passage, with caches of , and tokens per head. Evicting is a guess about the future made from the past: a token that seemed unimportant may be the one a later question needs. Part 16 chooses tokens by content instead.

3Attention without the softmaxUndergraduate2 min

Here's attention for a whole text of T tokens: queries times keys, then times values. The product of queries and keys is a T by T table of scores: it grows with the square of the length. But matrix products can be grouped either way. Multiply keys and values first, and the table in the middle is only d by d, however long the text. The catch is the softmax: it sits between Q K and V, and blocks the regrouping. Replace it with simple positive features of the queries and keys: pass each one through a fixed function, phi, that makes every number positive, so that their dot product can stand in for the softmax's exponential. Then you're allowed: that's linear attention.

Now read the text one token at a time. With the product regrouped, everything the model needs from the past is one d by d matrix, the state. Each new token writes into it: its value times its key, an outer product, which multiplies every number of the value by every number of the key: a whole grid, like a times table, added on. To read, multiply the state by the query. The memory never grows: a transformer without the softmax is a recurrent network, one that reads a token at a time and carries a fixed-size memory forward, updating it at each step. Katharopoulos and colleagues showed this in 2020.

The payoff grows with length. Softmax attention's work grows with the square of the text; the recurrence's grows in a straight line. At a million tokens, that's 3,906 times fewer multiplications. So why doesn't everyone use it? Because a fixed-size memory has to forget, and how it writes decides what it forgets.

4A matrix that remembersUndergraduate4 min

A memory you return to by its content is old. In 1982 John Hopfield described a network of neurons, each plus or minus one, that stores patterns in its connections by Hebb's rule from 1949: neurons that fire together wire together, a sum of outer products of the patterns with themselves. We stored five random patterns of a hundred neurons. Give it the first one with thirty bits flipped, and let each neuron in turn take the sign of its input. Every update can only lower an energy, so the state rolls downhill into the nearest valley: the stored pattern, recovered from a damaged copy.

But a matrix of N by N numbers can't hold many patterns this way. As we store more, the patterns start to interfere: the valleys merge, and spurious ones appear. With a hundred neurons, half the cues come back exactly at about 0.15 patterns per neuron, and the theory for large networks puts the limit at 0.138. Remember this: storing by adding outer products fills up. It will come back as crosstalk in a moment.

The same sum of outer products became a memory of keys and values. In 1972 Teuvo Kohonen and James Anderson stored a value under a key as a matrix: add value times key transposed, and read with the key. In 1992 Jürgen Schmidhuber made it fast weights: a slow network that, at every step, writes outer products into the weights of a fast network, a memory of the sequence so far. In 2016 Jimmy Ba, Geoffrey Hinton and colleagues revived it as a decaying memory of the recent past. Meanwhile neural Turing machines and memory networks, which Part 10 met, kept a separate memory and addressed it with attention. And in 2020 linear attention, the last chapter's recurrence, turned out to be the same matrix. In 2021 Imanol Schlag, Kazuki Irie and Schmidhuber named it: linear transformers are secretly fast weight programmers, and they gave them a better way to write.

Here is that memory at work, written and read one step at a time. The memory is a matrix S, eight by eight, empty at first. To store a value under a key, multiply them into an outer product, a grid of every value number times every key number, and add it on. Four keys, four values, four additions. To read, multiply the matrix by a key. Each key gets its own value back, plus a little of the others, in proportion to how much their keys overlap: errors from 0.11 to 0.29 here, for keys that are nearly, but not quite, at right angles.

With many pairs, that leak is the whole story. Read pair j, and you get its value plus every other value, weighted by how much its key overlaps key j. Random keys in d dimensions overlap by about one over the square root of d, so the leaks add up like N over d. With d equal to 64, by 64 pairs the noise is as big as the answer: the same filling-up as Hopfield's network. Adding can never erase.

5Forgetting and correctingMaster's3 min

The first fix is to forget on purpose. Before each write, shrink the whole memory a little. Here are 128 pairs, read back by age. Adding blurs every pair the same. Decaying keeps the recent pairs sharp, and lets the old ones go. RetNet, gated linear attention and Mamba-2 all decay, and the best let each token choose how much: forget a lot at the start of a new topic, almost nothing in the middle of a sentence.

The second fix is smarter. Before writing, read what the memory already says for this key, and write only the difference: what should be there, minus what is there. That's the delta rule, Widrow and Hoff's learning rule from 1960. It matters when the world changes. The door is open; later, the door is closed. Adding stores both, and answers with a mixture. The delta rule replaces the old value with the new. Here are 16 keys, rewritten 256 times with new values, then asked for the latest. Adding: an error of 19, it remembers every value ever written. Decaying: 0.92. The delta rule: 0.23.

Watch the difference on the eight-by-eight memory from the last chapter. The same four pairs are written, and then key 2 is given a new value. Adding piles the new value on top of the old: reading that key now returns a blend of both, an error of 0.98. The delta rule first reads what the memory holds for the key, and writes only the difference: the new value comes back exactly, an error of 0. The other keys move a little, through their overlap with this one; with keys at right angles they wouldn't move at all.

And here is why the delta rule works. Measure how wrong the memory is about one pair: the squared gap between what it reads for the key and the value. Its gradient is the gap times the key. One step of gradient descent on it is exactly the delta rule: least squares, solved online, one example at a time, which is what Widrow and Hoff's least-mean-squares rule did for their ADALINE in 1960. So the memory is a little model, trained by Part 11's gradient descent on the text as it's being read; Part 13's attention layer that learned in context was doing the same. Add decay to the delta rule, and you have the gated delta rule inside Qwen3-Next and Kimi Linear, the next chapter; make the memory a whole network, and you have test-time training, chapter ten: a small network whose weights keep learning while the model reads.

6The delta rule as geometryMaster's3 min

Let's look at the delta rule as geometry. The memory S is a linear map: give it a key, and it gives back an answer. Here it is acting on the plane. Feed it the key k, and it answers S k, but the value we want stored is v. The update multiplies S by I minus beta k k transpose, then adds beta v k transpose. That first matrix only touches the direction k: it shrinks it by one minus beta, and leaves every direction at right angles alone. With beta a half, the answer for k moves halfway to v, and the answer for the perpendicular direction doesn't move at all. With beta one, the old answer is erased exactly and replaced by v: a projection. And with beta up to two, it overshoots into a reflection, a matrix with eigenvalue minus one. That sounds like a bug, but it's a feature: Grazzi and colleagues showed it lets these memories track parity, the very problem part twenty-eight's transformer could not solve in one go. Parity asks: is the count of ones so far odd or even? It's a light switch that flips at every one, and a reflection is exactly that flip.

Now the whole family side by side. Linear attention only adds. Decay, as in Mamba-2 and gated linear attention, shrinks the whole memory by alpha before each write: everything fades a little. The delta rule edits only the direction of the current key. The gated delta rule does both: a decay alpha to clear the memory out when the topic changes, and a delta step to correct one fact at a time. That's the rule in three of every four layers of Qwen3-Next. Kimi Linear's version gives each channel of the memory, each of its feature dimensions, its own decay, a diagonal matrix instead of one number, so some features fade fast and others hold for thousands of tokens. Two more members came by their own roads. The matrix LSTM of xLSTM, from Sepp Hochreiter's group in 2024, is Part 10's LSTM with a matrix for its memory cell: a decaying memory with an exponential gate on what it writes. RWKV-7, from Bo Peng and the RWKV community in 2025, generalizes the delta rule: a decay for every channel, and a learned rate, channel by channel, at which it erases along one key before writing along another. Its authors prove that it can track the state of any finite automaton, which, under standard assumptions, a transformer of fixed depth cannot. Written this way, every member is the same shape: the old memory times a transition matrix, plus a write, and the transition is always a diagonal plus a low-rank part. That shape is what makes them fast to train.

7Training a recurrence in parallelMaster's4 min

Every memory so far is written one token at a time, and each step waits for the one before: thousands of steps in a row, while a graphics card wants a few big operations. Training on a whole text at once needs another way. Take the simplest case, one number: multiply the memory by a_t, add b_t. That's the decaying memory, a state-space model, one channel of Mamba. Write each step as a pair, a and b. Two steps in a row are again one step: multiply by a_1 a_2, and add a_2 b_1 plus b_2. And it doesn't matter how you group three of them: first two first, or last two first, the result is the same. The combination is associative, and that is all a parallel prefix scan needs, a trick from the 1980s for adding up running totals in parallel. Eric Martin and Chris Cundy brought it to recurrent networks in 2018, Part 10 used it for minGRU, and Mamba runs on it.

Here's the scan on eight steps. In the first round, every step combines with the one just before it. In the second, with the one two before, and in the third, four before. After three rounds every position holds the combination of all the steps up to it: every h_t at once. For 4,096 steps that's 12 rounds. This simple version does more work in all, T times the number of rounds; Guy Blelloch's up-and-down sweep does about two T. We checked both against the plain loop, and with four-by-four matrices in place of the numbers: the same answers, to rounding error.

For the delta rule, the coefficient is a matrix, I minus beta k k transpose, and combining two of them costs a full matrix product: scanning with them would be slow. The way out is to cut the text into chunks of sixty-four and handle each chunk at once. Within a chunk, the memory gets multiplied by sixty-four of those I minus beta k k transpose matrices: sixty-four small corrections, one after another. Multiplied out, they collapse into one: the identity minus a sum of sixty-four rank-one terms, w times k transpose. Numerical analysts call it the WY form; they found it decades ago for products of Householder reflections, matrices just like these. And all the w's come from one triangular solve, the UT transform: each w depends only on the ones before it, and the hardware works them all out with a few big matrix products instead of sixty-four waits in a row. With them, a chunk's outputs and its final memory are just matrix products, and the decay of the gated version folds into the same form. We checked it on our computer: for random tokens, step by step and chunk by chunk agree to rounding error, with sequential steps instead of . That's how Qwen3-Next and Kimi Linear were trained.

8State-space modelsMaster's4 min

A different road to the same place started in control theory. A state-space model is a differential equation: a hidden state h that evolves, pushed by the input x, read out as y. Picture a leaky bucket: the input pours in, the level slowly leaks away, and the level is what you read. Read a text in steps of size delta, and it becomes a recurrence: shrink the state, add the input. The step size sets the memory. Small steps, and an input lingers for a long time; large steps, and it's gone in a few tokens.

How should a continuous memory be read in steps? Solve the equation exactly over one step: the state decays by the exponential of delta A, plus the input, accumulated with the same decay. If the input is held constant over the step, the integral can be done. It comes out as A inverse times e to the delta A, minus the identity, times B. That's the zero-order hold: a recurrence with A bar and B bar that is exact for such inputs. We checked it on a small oscillator: the zero-order hold matches a fine numerical solution to within times ten to the minus . The bilinear rule's error shrinks with the square of the step, its measured slope . S4 used the bilinear rule; Mamba uses the zero-order hold for A.

But which A? Albert Gu and colleagues asked what it would mean for a state to remember a whole signal. Their answer, HiPPO, in 2020: keep the coefficients of the best polynomial fit to everything seen so far. That fit can be updated as each sample arrives, by an equation of exactly this form, with a particular matrix A. Here it is memorizing a signal online, one sample at a time, 2,000 of them, with eight numbers and with thirty-two. At any moment, the memory can be unpacked into its picture of the whole past: coarse with eight numbers, close with thirty-two. For 4 of the 5 sizes, the error at the end is within a hundredth of the best possible polynomial fit, which the memory never stored: the recurrence keeps it up to date.

A state-space model with a fixed A and B has one more face. Unroll the recurrence, and each output is a weighted sum of past inputs, with weights C times A bar to the j, times B bar: a convolution, with a kernel as long as the text. We checked that both give the same outputs. A convolution can be trained on a whole sequence at once with the fast Fourier transform. That was S4, by Gu, Karan Goel and Christopher Ré, in 2021: HiPPO's matrix, made fast by a clever structure. It was the first model to solve Path-X, a test that asks whether two dots in a sixteen-thousand-pixel image are connected, read one pixel at a time. But its kernel is the same for every input: an S4 layer cannot decide, from what it reads, what to keep.

9Selectivity: Mamba and afterMaster's3 min

But a fixed step size can't tell what matters. Here's an input stream of noise with two marked values worth remembering. With a fixed step, each marked value washes out in the noise that follows. Mamba's idea, in 2023, was to let each input choose its own step size: a big step to take in something important, almost no step at all for noise, so the state holds still. Now the state keeps the marked value until the next one replaces it. A memory that chooses. With delta, B and C all depending on the input, the convolution trick is gone; Gu and Tri Dao ran the recurrence as last chapter's scan, written to keep the state in the chip's fastest memory, and reported five times the throughput of a transformer at inference.

In 2024 Tri Dao and Gu showed that a selective state-space model, with its A reduced to a single number per step, is the decaying memory of chapter five: linear attention with a gate, its B playing the key and its C the query. That is Mamba-2, and its state-space duality gives the layer two faces. Unroll the recurrence, and every output is a weighted sum of earlier values: exactly attention, with the query-key scores multiplied by a mask L. Entry i, j of the mask is the product of the gates between token j and token i: how much of token j survives until step i. Where the gate forgets, the mask goes dark below that row. That mask is semiseparable, which just means: every block below the diagonal has rank one, because each entry is a number for its row times a number for its column. We checked: masked attention and the recurrence agree to rounding error. So the same layer can run as a recurrence while it writes, using constant memory, and as masked attention while it trains, using big matrix products.

The line continues. In March 2026 Aakash Lahoti, Gu, Dao and colleagues published Mamba-3, with three ideas from state-space thinking. First, a better step: instead of holding the input from one end of the step, use both ends, a trapezoid; with a learned bias added, they could drop the short convolution that sits in front of every layer of this family. Second, a complex-valued state, which can rotate as well as shrink: like the delta rule's reflections in chapter six, it lets the memory flip and count, and track parity, which Mamba-2 cannot. Third, several inputs and outputs per step, a rank-r write: more arithmetic for every byte of state read, which suits graphics cards, without slowing generation. They report the perplexity of Mamba-2 with half the state, and, at one and a half billion parameters, a little ahead of Gated DeltaNet.

10A memory that learnsResearch3 min

Chapter five ended with a thought: the delta rule is one step of gradient descent, so the memory is a model, trained on the text as it is read. Yu Sun and colleagues took that literally in 2024. The hidden state is the weights W of a small model, and reading a token is one training step on a loss made from that token: rebuild one learned view of it from another. If the model is linear, that is the delta rule again: TTT-Linear. But it can be anything trainable, a two-layer network, TTT-MLP, whose weights are a richer memory than one matrix. They reported that, from 125 million to 1.3 billion parameters, Mamba stopped improving with more than sixteen thousand tokens of context, and their layers kept improving.

We can test that on a toy. Each sequence has its own hidden rule, a small random network that turns a key into a value, and the memory reads one pair at a time, taking one gradient step on each. After every sixteen pairs we ask it about keys it has never seen, under the same rule. It isn't looking anything up: it has to have learned the rule.

Ali Behrouz, Peilin Zhong and Vahab Mirrokni at Google built the idea into Titans, at the turn of 2025. Their memory is a small deep network beside a window of ordinary attention, and they call the gradient surprise: a token the memory gets badly wrong produces a large gradient, and gets written in hard. They add momentum, so a surprise keeps being written for a few steps after, and a forgetting gate, a weight decay that clears old memories out. Here is our toy again, with the hidden rule swapped for a new one halfway. The surprise jumps when the rule changes. The paper reports needle tests passed beyond two million tokens; we can't check that here.

Step back, and every memory in this part is a learner. Linear attention takes a gradient step on a loss that rewards the memory for agreeing with the value: it can only add. Decay adds weight decay. The delta rule steps on the squared error, so it corrects; the gated delta rule adds weight decay to that. Titans and TTT make the memory a deeper model and use a better optimizer. And softmax attention trains nothing: it keeps every pair and answers with a weighted average of their values, Part 13's kernel regression, paying for it with a growing cache. Which of these can actually look things up? That's the next chapter.

11A recall testMaster's2 min

Here's a test of pure memory, multi-query associative recall, from Simran Arora and colleagues at Stanford: a list of keys, each followed by its value; then some of the keys again, in a new order, and the model must answer with their values. It's the skill a model needs to quote a name or a number from far back in a document, and in 2023 they found it explains most of the gap in quality between attention and the fast memories. We trained six kinds of small two-layer models on it: softmax attention, linear attention, a Mamba-2-style selective state-space model, the delta rule, the gated delta rule, and a hybrid with a gated delta layer under an attention layer. Lists of 16 pairs, keys from 2 to 16 numbers long, so the fixed memories range from far too small to big enough; the same weights, give or take a few gates, the same 1,000 steps, 3 seeds each.

Here is training, replayed, for keys of numbers. On the left, one list the models never train on: each square is one of its answers, lit when the model gets it right. On the right, the share right on a fixed batch. At first every model guesses. Then, one by one, they discover the trick: find the earlier copy of the key, and copy what came after it.

And here is every run at the end, against the size of the key, which sets the size of the fixed memories.

Why? Count what each memory holds after reading the list. A fixed memory with keys of numbers holds numbers a layer, whatever the length. Attention's cache holds every key and value it has seen, here, and for a text a thousand times longer. Exact recall is what attention buys with that growing cache; a fixed memory has to be big enough, or know what to overwrite.

12HybridsEngineering3 min

Fixed-size memories are cheap, but they forget; attention remembers everything exactly, at a price. So the newest models mix them. Jamba, from AI21 in 2024, put one attention layer among every eight, the rest Mamba; MiniMax-01, in January 2025, did the same with its lightning attention. NVIDIA's Nemotron-H kept attention in four of its twenty-eight mixing layers, and IBM's Granite 4.0 in one of ten. Qwen3-Next and Kimi Linear, in the autumn of 2025, used one attention layer in four, the other three running the gated delta rule. And in 2026 that layout reached the frontier's open models: Qwen3.5, from eight hundred million to nearly four hundred billion parameters, and Kimi K3, two point eight trillion, with twenty-four attention layers among ninety-three. The fast layers carry the gist of a long text cheaply; the few attention layers look up exact details when they're needed.

We built a small one. Two models on the thirty novels, with the same width, depth, MLPs, data and steps, three seeds each. One is a plain transformer with four attention layers. The other, like Kimi Linear, has three gated-delta layers and then one attention layer with no positional encoding at all: the recurrent layers below it carry the order. Here they train. Inside a window of 256 tokens the transformer's cache is small anyway; the hybrid's advantage is meant for long texts. That is the next chapter.

And here is the hybrid's writing as it learns, continuing the same opening at four moments of training. At step 0, noise. Then words, then something like sentences: about as far as 0.7 million weights and 1.6 million tokens can go.

The memory bill shows why. For one conversation of a hundred and twenty-eight thousand tokens, Llama 3.1's grouped-query cache takes 39 gigabytes; DeepSeek-V3's latent cache, 8.4; Qwen3-Next, with attention in only a quarter of its layers, 3.0, about 13 times less than Llama. Its delta-rule layers add just 36 megabytes of state, the same at any length.

13How long is a context, really?Undergraduate3 min

How do you test a long context? In November 2023 Greg Kamradt hid one sentence, the needle, at a chosen depth in a long stack of essays, and asked the model about it. Vary the depth and the length, colour each cell by whether it answered, and you get the needle-in-a-haystack picture that every long-context model now shows. A weak one goes dark in the middle of long texts: the lost-in-the-middle effect of Nelson Liu and colleagues, which Part 29 returns to. But the needle is an easy test: its question repeats its words, so a single attention head that matches words can find it.

So the tests got harder. In 2024 Cheng-Ping Hsieh and colleagues at NVIDIA built RULER: many needles at once, values passed along chains of variables, counting the commonest words, and questions about the text. Among seventeen models claiming at least thirty-two thousand tokens, its abstract says only half still did well at that length. In 2025 NoLiMa reduced literal matching: the needle and the question have minimal lexical overlap. At thirty-two thousand tokens, eleven of thirteen models fell below half their short-text score. And Chroma's report on context rot tested eighteen models and found length-related reliability declines across its tasks, including simple ones. The length a model accepts is not the length it can use.

We can run a small RULER of our own. Four of the last chapter's two-layer models, trained on three tasks at tokens: find one needle in a stream of filler words; find the one of four needles that's asked for; and follow a chain, A is seven, B equals A, C equals B, what is C? Then we test them on longer streams, up to tokens.

Our two language models from the last chapter were trained on windows of 256 tokens. What happens past the end? Here is the loss at each position of held-out text a thousand tokens long, read in one go.

Where does that leave the frontier? Google's Gemini 1.5, in 2024, offered a million tokens, and reported finding needles in up to ten million. Kimi Linear's report gives evidence for hybrids on long texts: on RULER at 128 thousand tokens, 84.3 against 81.3 for full attention trained the same way, and only 78.8 when its attention layers use rotary positions. On OpenAI's MRCR v2 test, eight similar requests in the long-prompt bin labelled one million tokens, Anthropic reported in February 2026 that Claude Opus 4.6 scored 76 percent mean match ratio, compared with 18.5 for Sonnet 4.5, under different thinking settings. And DeepSeek-V4 reads a million tokens by compressing its keys and values, four and a hundred and twenty-eight to one, and choosing among them: Part 16's subject. These are each maker's own measurements.

14Retrieval as memoryEngineering3 min

Every memory so far lives inside the model. The other way is to keep memory outside it, as a library. Turn every passage of a large collection into a vector, an embedding, and the question into another; the passages nearest the question are the ones to read. In 2020 Vladimir Karpukhin and colleagues trained two encoders so that questions land near their answers, dense passage retrieval; REALM trained the retriever together with the language model; and Patrick Lewis and colleagues named the recipe: retrieval-augmented generation, find the passages, put them in the context, and generate. An assistant can search a library larger than its context window, then read the selected passages within that window.

A language model can retrieve too, one token at a time. Urvashi Khandelwal and colleagues, in 2020, stored every token of the training text as a pair: the model's hidden state just before it, and the token itself. At test time, find the stored states nearest to the current one, and let their next tokens vote, weighted by closeness. Mix the vote with the model's own prediction, a share lambda to the memory. With no extra training, it took 2.9 points off the perplexity of the best model of the day on Wikipedia text. We built one for the series' model: all 6.6 million tokens of the thirty novels, as hidden states. Here is the token where it helps most in the scoreboard's passage. The model alone gives the right next token 0.031 percent; the nearest stored states, from places in the novels that looked the same, vote 96 percent for it.

How much does it help? The passage, chapter two of The Maltese Falcon, is not among the thirty novels, so the memory can't simply recall it: it helps with what novels share.

Where does the memory of the novels help? Here are the tokens of the passage where it saves the most bits.

Retrieval scales too: in 2021 DeepMind's RETRO looked up chunks of a two-trillion-token library and came close to GPT-3 on the Pile with a twenty-fifth of the parameters. And here is the scoreboard.

15The frontier, late 2026Research3 min

Two years ago, a fixed-size memory in a frontier model was an experiment. In January 2025 MiniMax-01 shipped lightning attention in seven layers of every eight, and read up to four million tokens; in April, NVIDIA's Nemotron-H kept attention in a few layers of a Mamba-2 stack. That autumn came the gated delta rule: Qwen3-Next and Kimi Linear, three layers in four. Then MiniMax's next model went back to full attention, and we'll see why. NVIDIA's Nemotron 3 mixed Mamba-2 with experts and a million tokens; Qwen3.5 made the gated-delta hybrid the whole family's design, and Mamba-3 improved the state-space line. DeepSeek-V4 took another road, compressing the cache instead; and in July 2026 Kimi K3, two point eight trillion weights, put Kimi Delta Attention in sixty-nine of its ninety-three layers.

In October 2025 Haohai Sun, who led MiniMax-M2's pretraining, explained the reversal. Their hybrid matched full attention on the usual benchmarks, but at larger scale it showed clear deficits in complex, multi-hop reasoning. The deeper problem, he wrote, is evaluation: the tests that reveal such gaps are expensive, and small experiments may not predict large ones. And the tools are young: linear layers are often limited by memory bandwidth, and serving tricks built for caches, like prefix caching and speculative decoding, have to be rebuilt. A sliding-window hybrid fared worse as the context grew; the heads that retrieve and copy, they found, form early in pretraining and are hard to add later. It's our recall test, at a frontier lab's scale. Moonshot and Qwen bet the other way; both bets are in production.

Meanwhile the people who build agents learned the lesson of the last two chapters the practical way. A model's window is a budget, and every token spent dilutes its attention; Anthropic's guide of September 2025 calls the decline context rot. So context engineering decides what goes in: instructions and tools, the documents retrieval finds, the conversation so far compacted into a summary when the window fills, and only the recent turns in full. What doesn't fit goes to notes the agent writes and reads back later, or to sub-agents that work in clean windows and report back a summary. It is this part's memory, managed by hand: a cache that is evicted, compressed, and retrieved.

So the questions are open. How much attention does a model need: one layer in four, in eight, or none? How big must a fixed memory be, and how should it grow? Can a memory learn what to keep as well as attention learns where to look? And how do we even measure what a model does with a million tokens?

Recap, problems, and what comes nextAll tracks2 min

Let's take stock. Attention's memory is its cache; models shrink it by sharing keys and values or squeezing them into a latent, and a server can evict some of it, as long as it keeps the sink. Drop the softmax and attention becomes a recurrence on a matrix, the fast weights of 1992, written by outer products and read with a key; adding fills it with crosstalk, decaying forgets, and the delta rule, one step of least squares, corrects. An associative scan, or chunks in the WY form, trains such a recurrence in parallel. State-space models came from the other side, HiPPO's memory of a whole signal and S4's convolution, and Mamba made them choose.

All of this comes back. Choosing which tokens to read, sparse attention and DeepSeek's indexer, is Part 16. Serving the cache fast is Part 19. The delta rule's reflections and state tracking meet reasoning in Part 28. Agents, in Part 29, manage their memory by hand, with notes, compaction and retrieval. And Part 30 looks for where a trained model keeps its facts.

Here are six problems, from pricing a cache to the cost of a nearest-neighbour vote. Pause here and work through them; full solutions are in this part's notes.

Next time: sparsity. The biggest models don't use all their weights for every token: a router sends each token to a few experts among hundreds, and attention can read only the tokens that matter. How do you route, and how do you keep every expert busy?

Songlin Yang's papers and blog on linear attention and the delta rule are the best way in, and Albert Gu's thesis for state-space models. Thanks for watching, and see you in Part 16.

Where it goes next. Choosing which tokens to read, sparse attention and DeepSeek's indexer, is Part 16; serving the cache fast is Part 19; the delta rule's reflections and state tracking meet reasoning in Part 28; agents manage memory by hand with notes, compaction and retrieval in Part 29; Part 30 looks for where a trained model keeps its facts.

Key results

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

The cache, per token\(\displaystyle 4\,L\,H\,d_h\ \text{bytes}\quad\allowbreak (\text{keys }\allowbreak \text{and }\allowbreak \text{values, }\allowbreak \text{16-bit})\)
Linear attention as a memory\(\displaystyle S_t=S_{t-1}+v_tk_t^\top,\qquad\allowbreak y_t=S_t\,q_t\)
Crosstalk of adding\(\displaystyle \frac{\mathbb{E}\,\|Sk_j-v_j\|^2}{\|v\|^2}\approx\frac{N-1}{d}\)
The delta rule\(\displaystyle S_t=S_{t-1}\bigl(I-\beta k_tk_t^\top\bigr)+\beta\,v_tk_t^\top\)
The scan's operator\(\displaystyle (a_1,b_1)\bullet(a_2,b_2)=(a_1a_2,\ a_2b_1+b_2)\)
Zero-order hold\(\displaystyle \bar A=e^{\Delta A},\qquad\allowbreak \bar B=A^{-1}\bigl(e^{\Delta A}-I\bigr)B\)

Try it

Lab 15 · A matrix that remembers: crosstalk, and the delta rule

Store N key-value pairs in one matrix by adding outer products, read them back, and compare the error with the (N - 1)/d the part derives for random keys in d dimensions. Then check with the series' autodiff that the delta rule is one gradient step on the squared read error, and overwrite facts under three write rules.

Figure produced by Lab 15: A matrix that remembers: crosstalk, and the delta rule
Produced by the lab below, seed 0, in 0.3 s.
python -m videos.ai.labs 15 needs numpy, scipy, matplotlib · download lab15.py · source on GitHub
adding, 16 pairs in 64 dimensions: read error            0.223   (theory (N-1)/d = 0.234)
adding, 64 pairs in 64 dimensions: read error            0.988   (theory (N-1)/d = 0.984)
delta rule, 64 pairs in one pass: read error             0.594
gradient step against S(I - beta k k^T) + beta v k^T     largest difference 1.8e-15
after 4 rewrites of 16 keys: error on the latest values  adding 3.90   decaying 0.39   delta rule 0.21

Adding never erases: its error is the crosstalk (N - 1)/d plus every value ever written under the key. Decay forgets everything a little. The delta rule, one least-squares step per token, replaces the old value and leaves the directions at right angles to the key alone.
The code (115 lines; it asserts its own result)
"""Lab 15: a matrix as a memory: fill it with outer products, count the crosstalk, then write with the delta rule."""

import numpy as np

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

TITLE = "A matrix that remembers: crosstalk, and the delta rule"
GOAL = ("Store N key-value pairs in one matrix by adding outer products, read them back, and compare the error with "
        "the (N - 1)/d the part derives for random keys in d dimensions. Then check with the series' autodiff that "
        "the delta rule is one gradient step on the squared read error, and overwrite facts under three write rules.")
TASKS = [
    "Make the keys exactly orthogonal (np.linalg.qr of a random matrix) for N <= d. What happens to every error?",
    "Run the delta rule with beta = 0.5 and beta = 2 in the overwrite test. Which one forgets the old value?",
    "Sweep the decay alpha from 0.5 to 1 in the overwrite test and find the best value. Why is 1 the worst?",
]

D, DV = 64, 16  # numbers in a key, numbers in a value


def pairs(rng, n):
    K = rng.standard_normal((n, D))
    return K / np.linalg.norm(K, axis=1, keepdims=True), rng.standard_normal((n, DV))


def write(S, k, v, rule, alpha=0.9, beta=1.0):
    """One write into the memory S (values x keys)."""
    if rule == "add":  # linear attention: S + v k^T
        return S + np.outer(v, k)
    if rule == "decay":  # shrink everything first, then add
        return alpha * S + np.outer(v, k)
    return S + beta * np.outer(v - S @ k, k)  # delta: write only the difference from what is read


def read_error(S, K, V):
    """Mean squared read error over the pairs, relative to the size of a value."""
    return np.mean(np.sum((K @ S.T - V) ** 2, axis=1)) / np.mean(np.sum(V ** 2, axis=1))


def run(seed=0):
    rng = np.random.default_rng(seed)
    lab = labs.Lab()

    # 1. adding fills up: the error of reading pair j is the sum of the other values, each times a key overlap
    Ns = np.array([2, 4, 8, 16, 32, 64, 128])
    added, delta = [], []
    for n in Ns:
        ea, ed = [], []
        for _ in range(max(30, 480 // n)):
            K, V = pairs(rng, n)
            Sa = np.zeros((DV, D))
            Sd = np.zeros((DV, D))
            for k, v in zip(K, V):
                Sa, Sd = write(Sa, k, v, "add"), write(Sd, k, v, "delta")
            ea.append(read_error(Sa, K, V))
            ed.append(read_error(Sd, K, V))
        added.append(np.mean(ea))
        delta.append(np.mean(ed))
    added, delta, theory = np.array(added), np.array(delta), (Ns - 1) / D
    for i in (3, 5):
        lab.row(f"adding, {Ns[i]} pairs in {D} dimensions: read error", f"{added[i]:.3f}   (theory (N-1)/d = {theory[i]:.3f})")
    lab.row(f"delta rule, {Ns[5]} pairs in one pass: read error", f"{delta[5]:.3f}")
    assert np.all(np.abs(added / theory - 1) < 0.12), "crosstalk grows like (N - 1)/d"
    assert np.all(delta < 0.75 * added), "writing only the difference leaves less crosstalk (later writes still disturb)"

    # 2. the delta rule is one step of gradient descent on the squared read error, by autodiff
    K, V = pairs(rng, 1)
    k, v, beta = K[0], V[0], 0.7
    S0 = rng.standard_normal((DV, D))
    S = Tensor(S0, requires_grad=True)
    (((S @ k - v) ** 2).sum() * 0.5).backward()
    by_gradient = S0 - beta * S.grad
    by_rule = S0 @ (np.eye(D) - beta * np.outer(k, k)) + beta * np.outer(v, k)
    u = np.linalg.qr(np.column_stack([k, rng.standard_normal(D)]))[0][:, 1]  # a direction at right angles to k
    gap = np.abs(by_gradient - by_rule).max()
    lab.row("gradient step against S(I - beta k k^T) + beta v k^T", f"largest difference {gap:.1e}")
    assert gap < 1e-12, "the delta rule is a gradient step on (1/2)|Sk - v|^2"
    assert np.allclose(by_rule @ k, (1 - beta) * S0 @ k + beta * v), "the answer for k moves a share beta toward v"
    assert np.allclose(by_rule @ u, S0 @ u), "directions at right angles to k are untouched"

    # 3. the world changes: 16 keys, each given a new value four times; then ask for the latest
    M, rounds, err = 16, 4, {"add": [], "decay": [], "delta": []}
    for _ in range(30):
        K, _ = pairs(rng, M)
        mem = {rule: np.zeros((DV, D)) for rule in err}
        for _ in range(rounds):
            V = rng.standard_normal((M, DV))
            for j in rng.permutation(M):
                for rule in err:
                    mem[rule] = write(mem[rule], K[j], V[j], rule)
        for rule in err:
            err[rule].append(read_error(mem[rule], K, V))
    err = {rule: float(np.mean(e)) for rule, e in err.items()}
    lab.row("after 4 rewrites of 16 keys: error on the latest values", f"adding {err['add']:.2f}   decaying {err['decay']:.2f}   delta rule {err['delta']:.2f}")
    lab.note = ("Adding never erases: its error is the crosstalk (N - 1)/d plus every value ever written under the "
                "key. Decay forgets everything a little. The delta rule, one least-squares step per token, replaces "
                "the old value and leaves the directions at right angles to the key alone.")
    assert err["add"] > rounds - 1, "adding answers with every value ever written"
    assert err["delta"] < err["decay"] < err["add"] and err["delta"] < 0.5, "the delta rule corrects"

    fig, ax = labs.figure(2, size=(11, 4.2))
    ax[0].loglog(Ns, added, "o-", color=labs.BLUE, label="adding outer products")
    ax[0].loglog(Ns, theory, "--", color=labs.MUTED, label="theory: (N - 1)/d")
    ax[0].loglog(Ns, delta, "o-", color=labs.GOLD, label="delta rule, one pass")
    ax[0].axvline(D, color=labs.GRID, lw=1.2)
    ax[0].annotate("N = d", (D, added.min()), textcoords="offset points", xytext=(-34, 0), color=labs.MUTED)
    ax[0].set(title=f"Reading back N pairs from a {DV} x {D} matrix", xlabel="pairs stored, N", ylabel="read error / size of a value")
    ax[0].legend(loc="upper left")
    names = ["adding", "decaying (0.9)", "delta rule"]
    bars = ax[1].bar(names, [err["add"], err["decay"], err["delta"]], color=[labs.BLUE, labs.PURPLE, labs.GOLD], width=0.6)
    ax[1].bar_label(bars, fmt="%.2f", color=labs.INK, padding=3)
    ax[1].set_axisbelow(True)
    ax[1].set(title="16 keys rewritten 4 times: error on the latest value", ylabel="read error / size of a value", ylim=(0, err["add"] * 1.15))
    lab.fig = fig
    return lab

Now change it

  1. Make the keys exactly orthogonal (np.linalg.qr of a random matrix) for N <= d. What happens to every error?
  2. Run the delta rule with beta = 0.5 and beta = 2 in the overwrite test. Which one forgets the old value?
  3. Sweep the decay alpha from 0.5 to 1 in the overwrite test and find the best value. Why is 1 the worst?

Problems, with solutions

Try each problem before opening its solution.

  1. A model has L layers and H key-value heads of d_h numbers, stored in bf16. How many bytes does its cache take per token? Evaluate for Llama 3.1 70B (L = 80, H = 8, d_h = 128) at 128,000 tokens, and with one key-value head.

    Solution

    Keys and values: 2 × L × H × d_h numbers of 2 bytes, 4·L·H·d_h bytes a token. Llama 3.1 70B: 4 × 80 × 8 × 128 = 327,680 bytes = 320 KiB; at 128,000 tokens 41.9 GB = 39.1 GiB. With one key-value head (MQA): 40 KiB a token, 4.9 GiB.

  2. For N random unit keys in d dimensions, show E[(k_i · k_j)²] = 1/d for i ≠ j, and that adding N pairs gives a relative read error of about (N − 1)/d.

    Solution

    For independent unit vectors, E[k_i k_iᵀ] = I/d by symmetry, so E[(k_i·k_j)²] = E[k_jᵀ E[k_i k_iᵀ] k_j] = ‖k_j‖²/d = 1/d. Reading pair j gives S k_j − v_j = Σ_{i≠j} v_i (k_i · k_j); with independent values of equal norm the cross terms average out and E‖S k_j − v_j‖² = Σ_{i≠j} ‖v_i‖² E[(k_i·k_j)²] = (N − 1)‖v‖²/d. Relative error (N − 1)/d: as big as the answer by N ≈ d (the chapter's curve, d = 64).

  3. With ‖k‖ = 1, show the delta rule gives S_t k = (1 − β) S_{t−1} k + β v and leaves S_t u = S_{t−1} u for u ⊥ k. Find the eigenvalues of I − β k kᵀ; for which β is it a projection, a reflection?

    Solution

    S_t = S_{t−1}(I − βkkᵀ) + βvkᵀ, so S_t k = S_{t−1}k − βS_{t−1}k(kᵀk) + βv(kᵀk) = (1 − β)S_{t−1}k + βv, and for u ⊥ k, kᵀu = 0 gives S_t u = S_{t−1}u. I − βkkᵀ has eigenvalue 1 on the (d − 1)-dimensional space ⊥ k and 1 − β on k. β = 1: eigenvalues 1 and 0, the projection onto k⊥ (the old answer erased, then v written). β = 2: eigenvalues 1 and −1, a reflection (a Householder matrix); for 0 < β < 2 the map is a contraction along k, and β ∈ (0, 2] keeps it stable while allowing the sign flip that lets these memories track parity.

  4. Show that (a₁, b₁) • (a₂, b₂) = (a₁a₂, a₂b₁ + b₂) is associative, find its identity, and count the rounds of a scan over 10⁶ tokens.

    Solution

    ((a₁,b₁)•(a₂,b₂))•(a₃,b₃) = (a₁a₂, a₂b₁+b₂)•(a₃,b₃) = (a₁a₂a₃, a₃a₂b₁ + a₃b₂ + b₃), and (a₁,b₁)•((a₂,b₂)•(a₃,b₃)) = (a₁,b₁)•(a₂a₃, a₃b₂+b₃) = (a₁a₂a₃, a₂a₃b₁ + a₃b₂ + b₃): equal. Identity (1, 0). A Hillis–Steele scan takes ⌈log₂ 10⁶⌉ = 20 rounds; Blelloch's up and down sweeps take 2 × 20 = 40 rounds but only about 2 × 10⁶ combines.

  5. For h′ = −λh + x, derive the zero-order hold Ā = e^{−λΔ}, B̄ = (1 − e^{−λΔ})/λ. When is Euler's Ā = 1 − λΔ unstable? For eigenvalues −0.3 ± 2i, find the largest stable Euler step.

    Solution

    Over a step with x held constant, h(t+Δ) = e^{−λΔ}h(t) + ∫₀^Δ e^{−λ(Δ−s)} ds · x = e^{−λΔ}h(t) + (1 − e^{−λΔ})/λ · x. Euler's |1 − λΔ| ≤ 1 needs Δ ≤ 2/λ; beyond it the recurrence blows up. For complex μ = −0.3 ± 2i, |1 + Δμ|² = (1 − 0.3Δ)² + 4Δ² ≤ 1 ⇔ Δ(4.09Δ − 0.6) ≤ 0 ⇔ Δ ≤ 0.6/4.09 ≈ 0.147: the chapter's Euler steps of 0.2 and 0.4 are unstable, which is why their errors exploded. The zero-order hold is stable for every Δ: |e^{Δμ}| = e^{−0.3Δ} < 1.

  6. A kNN-LM mixes p = λ p_kNN + (1 − λ) p_LM. Show it never costs more than log₂ 1/(1 − λ) bits on a token, and find when it saves bits.

    Solution

    p ≥ (1 − λ) p_LM, so −log₂ p ≤ −log₂ p_LM + log₂ 1/(1 − λ): at most log₂ 1/(1 − λ) bits worse (0.15 bits at λ = 0.1, 0.42 at λ = 0.25). It saves bits exactly when λ p_kNN + (1 − λ) p_LM > p_LM, that is when p_kNN > p_LM: the neighbours give the true token more probability than the model does.

Notes and sources

Glossary

English 中文
KV cache; per token, per layer KV缓存;每个词元,每层
multi-query attention (MQA), grouped-query attention (GQA) 多查询注意力(MQA),分组查询注意力(GQA)
multi-head latent attention (MLA); latent; absorption (folding the key matrix into the query) 多头潜在注意力(MLA);潜在向量;吸收(把键矩阵并进查询)
decoupled rotary key 解耦的旋转键
cache eviction; sliding window; global tokens; random keys 缓存逐出(挤出);滑动窗口;全局词元;随机键
segment-level recurrence (Transformer-XL) 段级递推(Transformer-XL)
attention sink; StreamingLLM 注意力汇点;StreamingLLM
heavy hitter (H₂O) 重量级词元(heavy hitter,H₂O)
linear attention; feature map φ 线性注意力;特征映射φ
outer product 外积
associative memory; correlation matrix memory 联想记忆;相关矩阵记忆
Hopfield network; Hebb's rule; energy; capacity 霍普菲尔德网络;赫布规则;能量;容量
fast weights; fast weight programmer 快权重;快权重编程器
crosstalk 串扰
decay; forget gate 衰减;遗忘门
delta rule; least mean squares (LMS); online least squares δ规则;最小均方(LMS);在线最小二乘
gated delta rule (Gated DeltaNet); Kimi Delta Attention (KDA) 门控δ规则(Gated DeltaNet);Kimi Delta Attention(KDA)
projection; reflection; Householder matrix 投影;反射;豪斯霍尔德矩阵
parity; state tracking; finite automaton 奇偶性;状态追踪;有限自动机
matrix LSTM (mLSTM, xLSTM); RWKV-7 矩阵LSTM(mLSTM,xLSTM);RWKV-7
associative scan, parallel prefix scan; up-sweep, down-sweep 结合律扫描,并行前缀扫描;上扫,下扫
chunkwise training; WY form; UT transform 分块训练;WY形式;UT变换
state-space model (SSM); zero-order hold; bilinear (Tustin) rule; Euler step 状态空间模型(SSM);零阶保持;双线性规则;欧拉步
HiPPO; Legendre polynomials HiPPO;勒让德多项式
S4; convolution kernel; Path-X S4;卷积核;Path-X
selectivity; selective SSM (Mamba); step size Δ 选择性;选择性状态空间模型(Mamba);步长Δ
state-space duality (Mamba-2); semiseparable mask 状态空间对偶(Mamba-2);半可分掩码
exponential-trapezoidal discretization; complex state; MIMO (Mamba-3) 指数梯形离散化;复数状态;多输入多输出(Mamba-3)
test-time training (TTT); surprise; momentum; forgetting gate (Titans) 测试时训练(TTT);意外度;动量;遗忘门(Titans)
multi-query associative recall (MQAR) 多查询联想回忆(MQAR)
hybrid architecture; NoPE (no positional encoding) 混合架构;NoPE(无位置编码)
needle in a haystack; lost in the middle; RULER; NoLiMa; context rot 大海捞针;迷失在中间;RULER;NoLiMa;上下文腐烂
variable tracking; multi-key needle 变量追踪;多键针
context engineering; compaction; sub-agent 上下文工程;压缩(compaction);子智能体
dense retrieval (DPR); retrieval-augmented generation (RAG); RETRO 稠密检索(DPR);检索增强生成(RAG);RETRO
kNN-LM; datastore; interpolation weight λ; continuous cache kNN-LM(k近邻语言模型);数据存储;插值权重λ;连续缓存

Sources

Books and notes: S. J. D. Prince, Understanding Deep Learning (2023), ch. 12; S. Yang, DeltaNet Explained (blog, 2024) and the flash-linear-attention library; A. Gu, Modeling Sequences with Structured State Spaces (thesis, 2023).

  • Associative memory: Hebb (1949); Kohonen (1972), Anderson (1972); Hopfield, PNAS (1982); Amit, Gutfreund & Sompolinsky (1985); Schmidhuber, Learning to control fast-weight memories (1992); Ba, Hinton, Mnih, Leibo & Ionescu, Using fast weights to attend to the recent past (2016); Graves, Wayne & Danihelka, NTM (2014); Weston, Chopra & Bordes, memory networks (2014); Sukhbaatar et al. (2015).
  • The cache: Shazeer, MQA (2019); Ainslie et al., GQA (2023); DeepSeek-AI, DeepSeek-V2 (2024), V3 (2024).
  • Keeping less: Child et al., Sparse Transformer (2019); Dai et al., Transformer-XL (2019); Beltagy et al., Longformer (2020); Zaheer et al., BigBird (2020); Xiao et al., StreamingLLM (2023, arXiv 2309.17453); Zhang et al., H₂O (2023, arXiv 2306.14048).
  • Linear attention and its write rules: Katharopoulos et al. (2020); Widrow & Hoff (1960); Schlag, Irie & Schmidhuber (2021); Yang et al., DeltaNet (2024); Yang, Kautz & Hatamizadeh, Gated DeltaNet (2025); Grazzi et al. (2025); Kimi Team, Kimi Linear (arXiv 2510.26692, 2025); Beck et al., xLSTM (2024); Peng et al., RWKV-7 (arXiv 2503.14456, 2025); Sun et al., RetNet (2023); Yang et al., GLA (2024).
  • Parallel training: Blelloch, Prefix sums and their applications (1990); Martin & Cundy (2018); Bischof & Van Loan, the WY representation (1987); Joffrain et al., the UT transform (2006).
  • State spaces: Gu, Dao, Ermon, Rudra & Ré, HiPPO (2020); Gu, Goel & Ré, S4 (2022); Gu & Dao, Mamba (2023); Dao & Gu, Mamba-2 (2024); Lahoti et al., Mamba-3 (ICLR 2026, arXiv 2603.15569).
  • Memories that learn: Sun et al., TTT (arXiv 2407.04620, 2024); Behrouz, Zhong & Mirrokni, Titans (arXiv 2501.00663, 2024); Wang, Shi & Fox, Test-time regression (2025).
  • Recall and long context: Arora et al., Zoology (2023); Kamradt, needle in a haystack (2023); Liu et al., Lost in the Middle (2023); Hsieh et al., RULER (2024); Modarressi et al., NoLiMa (2025); Hong, Troynikov & Huber, Context Rot (Chroma, 2025); Google, Gemini 1.5 (2024); Anthropic, Claude Opus 4.6 announcement (February 2026); Anthropic, Effective context engineering for AI agents (September 2025).
  • Hybrids: Lieber et al., Jamba (2024); MiniMax, MiniMax-01 (2025); NVIDIA, Nemotron-H (2025), Nemotron 3 (2025); IBM, Granite 4.0 (2025); Qwen Team, Qwen3-Next (2025), Qwen3.5 (model card, 2026); Moonshot AI, Kimi K3 (model card, 2026); H. Sun, Why did M2 end up as a full attention model? (MiniMax, 2025); DeepSeek-AI, DeepSeek-V4 (2026).
  • Retrieval: Karpukhin et al., DPR (2020); Guu et al., REALM (2020); Lewis et al., RAG (2020); Khandelwal et al., kNN-LM (2020); Grave, Joulin & Usunier, continuous cache (2017); Borgeaud et al., RETRO (2021).
About this partfrom its README

Part 15 of the series: what a model remembers while it reads, and the costs and limits of each memory. The 17 scenes cover the KV cache, eviction and attention sinks, linear attention, associative and fast weights, decay and delta rules, parallel recurrence training, state-space models, Mamba, test-time training, recall tests, hybrids, long-context benchmarks, retrieval, the frontier and a recap.

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. KV-cache arithmetic; MQA/GQA; MLA (absorption, decoupled RoPE).
  2. Cache eviction (StreamingLLM, H2O).
  3. Linear attention as an RNN.
  4. The delta rule (online least squares, Householder) and gated delta; WY/UT chunkwise.
  5. SSMs: HiPPO/S4, ZOH discretization, Mamba selectivity, Mamba-2 duality, newer variants after verification.
  6. RWKV-7, mLSTM.
  7. Titans and test-time training.
  8. MQAR recall test (computed).
  9. Hybrids: Jamba, Nemotron-H, Qwen3-Next, Kimi Linear.
  10. Long-context evaluation (needle, RULER).
  11. Retrieval as memory: dense retrieval, the kNN-LM on the novels (scoreboard row).

Visuals: the associative scan; the memory matrix written and read.

中文讲义

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

习题(中文)
  1. 一个模型有 L 层、H 个键值头,每个头 d_h 个数,用 bf16 存储。每个词元的缓存占多少字节?对 Llama 3.1 70B (L = 80,H = 8,d_h = 128)算出 12.8 万个词元的缓存,再算只有一个键值头时的情形。
  2. d 维空间里 N 个随机单位键,证明 i ≠ j 时 E[(k_i · k_j)²] = 1/d,并证明累加 N 对之后,读回的相对误差约为 (N − 1)/d。
  3. 设 ‖k‖ = 1,证明 δ 规则给出 S_t k = (1 − β) S_{t−1} k + β v,并且对 u ⊥ k 有 S_t u = S_{t−1} u。求 I − β k kᵀ 的特征值;β 取多少时它是投影,取多少时是反射?
  4. 证明 (a₁, b₁) • (a₂, b₂) = (a₁a₂, a₂b₁ + b₂) 满足结合律,求它的单位元,并数一数对 10⁶ 个词元做扫描需要几轮。
  5. 对 h′ = −λh + x,推导零阶保持 Ā = e^{−λΔ},B̄ = (1 − e^{−λΔ})/λ。欧拉法的 Ā = 1 − λΔ 什么时候不稳定? 特征值为 −0.3 ± 2i 时,欧拉法最大的稳定步长是多少?
  6. kNN-LM 混合 p = λ p_kNN + (1 − λ) p_LM。证明它在一个词元上最多多花 log₂ 1/(1 − λ) 比特,并求它什么时候能省下比特。

解答

Solutions
  1. 键和值共 2 × L × H × d_h 个数,每个 2 字节,即每个词元 4·L·H·d_h 字节。Llama 3.1 70B:4 × 80 × 8 × 128 = 327,680 字节 = 320 KiB;12.8 万个词元是 41.9 GB = 39.1 GiB。只有一个键值头(MQA)时:每个词元 40 KiB,共 4.9 GiB。
  2. 独立的单位向量由对称性有 E[k_i k_iᵀ] = I/d,于是 E[(k_i·k_j)²] = E[k_jᵀ E[k_i k_iᵀ] k_j] = 1/d。读第 j 对得到 S k_j − v_j = Σ_{i≠j} v_i (k_i · k_j);值彼此独立、范数相同,交叉项平均为零,E‖S k_j − v_j‖² = (N − 1)‖v‖²/d, 相对误差 (N − 1)/d:N 接近 d 时,噪声就和答案一样大(本章的曲线,d = 64)。
  3. S_t k = S_{t−1}k − βS_{t−1}k + βv = (1 − β)S_{t−1}k + βv;u ⊥ k 时 kᵀu = 0,所以 S_t u = S_{t−1}u。I − βkkᵀ 在与 k 垂直的 d − 1 维子空间上特征值为 1,在 k 方向上为 1 − β。β = 1 时特征值是 1 和 0,是到 k⊥ 的投影;β = 2 时是 1 和 −1,是一个反射(豪斯霍尔德矩阵);β 在 (0, 2] 内都稳定,而正负号的翻转让这些记忆能追踪奇偶性。
  4. 两种组合都得到 (a₁a₂a₃, a₂a₃b₁ + a₃b₂ + b₃),所以满足结合律;单位元是 (1, 0)。希利斯–斯蒂尔扫描需要 ⌈log₂ 10⁶⌉ = 20 轮;布莱洛赫的上扫加下扫需要 40 轮,但总共只做大约 2 × 10⁶ 次组合。
  5. 输入在一步内不变时,h(t+Δ) = e^{−λΔ}h(t) + (1 − e^{−λΔ})/λ · x。欧拉法要求 |1 − λΔ| ≤ 1,即 Δ ≤ 2/λ,否则 递推会发散。对复数 μ = −0.3 ± 2i,|1 + Δμ|² = (1 − 0.3Δ)² + 4Δ² ≤ 1 ⇔ Δ ≤ 0.6/4.09 ≈ 0.147:本章 0.2 和 0.4 的 欧拉步长都不稳定,所以误差爆炸。零阶保持对任何 Δ 都稳定:|e^{Δμ}| = e^{−0.3Δ} < 1。
  6. p ≥ (1 − λ) p_LM,所以 −log₂ p ≤ −log₂ p_LM + log₂ 1/(1 − λ):最多差 log₂ 1/(1 − λ) 比特(λ = 0.1 时 0.15 比特, λ = 0.25 时 0.42 比特)。当且仅当 p_kNN > p_LM 时能省下比特:邻居给正确词元的概率比模型自己给得多。

Build the film

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

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