Long-Context LLMs

A chatbot can talk forever if its memory stays small. StreamingLLM keeps 4 anchor tokens and a rolling window, and holds perplexity at 5.40 where plain window attention reaches 5,158.

Learn why long text breaks a language model, and the tricks that stretch it: new position angles, smarter fine-tuning, cache eviction, head splitting, page selection and a different kind of layer.

Pick a way to remember, then drag the slider to make the text longer. Watch which tokens stay in the cache and what happens to the quality bar. Then we build, piece by piece, positions, sinks, heads, pages and state.

You need a little attention (each word looks back at earlier words and mixes them) and a little Python for the code. We build the rest from zero.

Based on Lecture 15 of MIT 6.5940: TinyML and Efficient Deep Learning Computing (Fall 2026), taught by Song Han and the MIT HAN Lab. Lecture 15 slides (PDF) are linked on the course page.

Remember a growing text

12

Illustrative: 40 toy tokens, a cache budget of 8, and a toy training length of 16. The perplexity values are the lecture's for Llama-2 on long text (dense 5,641, window 5,158, StreamingLLM 5.40, slides 27 and 31). Lower is better.

Chapter 0

Why a Longer Text Breaks a Language Model

See what a context window is, why each new word costs more than the last, and where the four parts of this lecture fit

You paste a 300-page book into a chatbot and ask which chapter explains why the ship sank. The model must hold about 100,000 words and find one fact. It runs short of three things: position signals it trained on, a way to find a fact in the middle, and memory to hold the text.

A token is a small piece of text, about three quarters of an English word. The context window is how many tokens the model can look at when it writes the next one. A long-context model has a window of 128,000 tokens or more.

Attention is how the model reads that window. To write the next token, it scores every earlier token for how useful it is now, then mixes them by score. Token N looks back at N earlier tokens, so a whole text costs 1 + 2 + ... + N looks, about half of N squared. A text of 1,000 tokens costs 500,500 looks and one of 2,000 costs 2,001,000: double the length, four times the work.

Count the looks back

Each row is one token. The filled cells are the earlier tokens it looks back at. The last row is the token being written now. Drag the length and watch the total.

12

Illustrative: a toy text of at most 32 tokens. Real models do this for every layer and every attention head, so the true counts are far larger.

Memory is the second bill. The model saves two vectors for every token it has seen, so it never redoes old work: a key (a page label) and a value (the page). The saved set is the KV cache. It holds one key and one value per token, per layer, per head, so it grows in step with N.

Lecture 15 of MIT 6.5940 (TinyML and Efficient Deep Learning Computing, Song Han and the MIT HAN Lab) has four parts, and each answers one question:

  1. Context extension: how do we make a model trained on 4,000 tokens read 32,000?
  2. Evaluation: how do we know a model uses its long window?
  3. Efficient attention: how do we shrink the KV cache and the work, without losing facts?
  4. Beyond transformers: can a different layer avoid the problem entirely?
  1. RoPE and position interpolation: how a model knows where a token is, and how to stretch it.
  2. LongLoRA: a cheap way to fine-tune for long text.
  3. Lost in the middle, and how we test: needle in a haystack and LongBench.
  4. The KV cache bill: how many gigabytes a long chat costs.
  5. Attention sinks: why window attention collapses.
  6. StreamingLLM: the fix, and its limit.
  7. DuoAttention: two kinds of heads, two kinds of cache.
  8. Quest: keep everything, read only the right pages.
  9. LServe: one system that combines the ideas.
  10. Mamba and Jamba: layers with no growing cache.
  11. The field guide: numbers, code and where next.
A text doubles from 1,000 to 2,000 tokens. About how much does the total number of looks back, over the whole text, grow?

Chapter 1

RoPE Tells the Model Where a Token Is, and Interpolation Stretches It

Rotate each query and key by its position, then squeeze new positions into the angles the model already knows

"The dog bit the man" and "The man bit the dog" use the same words and mean opposite things. Attention alone does not see order: shuffle the tokens and the scores stay the same. LLaMA marks position with RoPE, rotary position embedding (Su et al., 2021). RoPE cuts each query and key of d numbers into d / 2 pairs. It turns each pair like a clock hand, by an angle that grows with the position.

Call the position m, the speed of pair i theta-i, and a stretch factor s.

Say it aloud

Angle-i equals m over s, times theta-i.

anglei
angle-i how far pair i turns, in radians.
m
m the token's position in the text: 0, 1, 2 and so on.
s
s the stretch factor. 1 means no stretch; 2 halves every position.
θi
theta-i the speed of pair i: 10000 to the power −2(i − 1) / d. It is 1 for the first pair and about 0.0001 for the last pair of a 128-number head. The big base keeps far positions apart.
In plain words

Divide the position m by the stretch s. Multiply by the speed theta-i. Turn pair i by that angle.

With numbers

The slow pair has theta-i about 0.0001. Trained to position 4,096, it saw angles up to 0.41 rad. At m = 8,192 with s = 1 the angle is 0.82 rad, which it never saw. With s = 2 it is 0.41 rad again.

Attention scores a query at position m against a key at position n with a dot product.

Say it aloud

The dot product of R of m-theta times q with R of n-theta times k equals q transpose, times R of m minus n, theta, times k.

⟨ , ⟩
the dot product of multiply matching numbers and add: the attention score before softmax.
R(mθ)
R of m-theta a 2 × 2 rotation that turns one pair by m times theta.
q, k
q, k one pair of the query and one pair of the key, before rotation.
qT
q transpose q laid on its side so it can multiply a matrix.
m − n
m minus n the gap between the two positions.
In plain words

The score of q and k depends only on the gap m minus n, so RoPE is a relative position code.

With numbers

Use a toy theta of 0.5 rad and q = k = (1, 0). The query at m = 5 turns 2.5 rad; the key at n = 3 turns 1.5 rad. The score is cos(1.0) = 0.540. At m = 9 and n = 7 the gap and the score stay the same.

Models train to a maximum length: 2,000 tokens for LLaMA, 4,000 for Llama-2, 8,000 for GPT-4 (slide 6). Past it, the slow pairs meet angles they never saw and the output turns to nonsense. Position interpolation (Chen et al., 2023) picks s so that m / s stays in range; the slide stretches LLaMA from 2,000 to 32,000 tokens.

Push past the training length

The model was trained to position 4,096. Pick the slow pair, drag the position past 4,096, then choose a stretch factor. Left: the dial. Right: where the position lands on the trained range.

6,016
4

Illustrative: the fast pair uses θ = 1 and the slow pair θ = 0.0001, close to the first and last pairs of a 128-number head. The trained length of 4,096 is Llama-2's, as on slide 6.

After a 4x stretch, neighbours sit a quarter of a position apart, so the slide warns that the model needs a short fine-tune.

pythonimport numpy as np

def rope(x, pos, scale=1.0, base=10000):   # x (N, d), pos (N,)
    N, d = x.shape
    theta = base ** (-2 * np.arange(d // 2) / d)       # (d/2,) turning speeds
    ang = (pos / scale)[:, None] * theta           # (N, d/2); scale=2 is interpolation
    c, s = np.cos(ang), np.sin(ang)
    x1, x2 = x[:, 0::2], x[:, 1::2]             # the two numbers of each pair
    out = np.empty_like(x)
    out[:, 0::2] = x1 * c - x2 * s               # 2D rotation of every pair
    out[:, 1::2] = x1 * s + x2 * c
    return out
A model is trained to position 4,096 and you want 16,384 tokens. With position interpolation, what position do you feed for the token at 16,000, and what is the price?

Chapter 2

LongLoRA Fine-Tunes for Long Text at a Fraction of the Cost

Train with attention in small groups, then switch to full attention when the model runs

You stretched the positions and now must fine-tune on 32,000-token examples. A full fine-tune of LLaMA to long text (LongLLaMA) took 128 TPUv3 chips (slide 8). LongLoRA (Chen et al., 2023) tunes a 70B Llama-2 to 32,000 tokens on 8 A100 GPUs, with two ideas.

LoRA (Lecture 14) freezes each big weight matrix and trains a small update of two thin matrices beside it. That saves memory on the weights. At 32,000 tokens the bigger cost is attention, which grows with the square of the length.

Idea one: shifted sparse attention

During training, each token attends only inside a group of neighbouring tokens. Call the text length N and the number of groups G, so each group holds N / G tokens.

Say it aloud

Pairs equals G times N over G squared, which equals N squared over G.

pairs
pairs the query and key pairs that one head scores in training.
G
G the number of groups.
(N / G)2
N over G squared the pairs inside one group of N / G tokens.
N2
N squared the pairs of full attention over N tokens.
In plain words

Each group scores every pair inside it. There are G groups. So grouping divides the work by G.

With numbers

Take N = 32,768 and G = 4 (our choice, not the paper's). Full attention scores 32,7682 = 1.07 billion pairs per head, ignoring the causal half. Grouped attention scores 4 × 8,1922 = 268 million, one quarter.

Tokens in different groups never talk. S2-Attn (shifted sparse attention) fixes that in three steps (slide 10):

  1. Split the attention heads into two halves.
  2. In the second half of the heads, shift all tokens by half a group.
  3. Reshape the tokens into groups and run attention inside each group.

A token at a group wall in one half of the heads sits mid-group in the other half. So information crosses the wall, like bricks in staggered rows. At test time the model uses ordinary full attention. Slide 11: the shift saves training hours on top of FlashAttention-2.

Stagger the groups

Rows are tokens that look back, columns are tokens they look at. A filled cell means the pair can talk. Choose a pattern, then a group size.

Illustrative: 12 tokens, and the shifted pattern ignores the wrap-around of the last tokens. Full causal attention would use 78 pairs. Pair counts are exact for this toy.

The code rolls half the heads by −G / 2 tokens and folds N into groups. The comments give the shapes.

python# Shifted sparse attention, after the pseudocode on slide 10 (shapes in comments)
def s2_attn(qkv, G):                          # qkv (B, N, 3, H, D), G = group size
    B, N, _, H, D = qkv.shape
    a, b = qkv.chunk(2, 3)                  # split the heads into two halves
    qkv = torch.cat([a, b.roll(-G // 2, 1)], 3)  # shift tokens in the second half
    qkv = qkv.view(B * N // G, G, 3, H, D)   # (B*N/G, G, 3, H, D): groups as batch
    out = self_attn(qkv)                       # attention inside each group
    out = out.view(B, N, H, D)
    x, y = out.chunk(2, 2)
    return torch.cat([x, y.roll(G // 2, 1)], 2)  # shift the second half back

Idea two: train a little more than LoRA

Also train the input embedding (the table that turns a token into a vector) and the normalisation layers (small layers that rescale values). Norms are under 0.004% of the parameters and embeddings under 2% (slide 12). Table 3 shows why, on Llama-2 7B with a 32,768 target (perplexity, lower is better):

What trainsPerplexity
All weights (full fine-tune)8.08
LoRA, rank 811.44
LoRA, rank 25611.98
LoRA rank 8 + norms10.49
LoRA rank 8 + norms + embeddings8.12

A bigger rank does not close the gap; the norms and embeddings do. On passkey retrieval, a secret number hidden in filler, the tuned model recalls the key up to its fine-tuned length (slide 13).

In shifted sparse attention, why do half of the heads shift tokens by half a group?

Chapter 3

A Long Window Is Not the Same as Using It Well

Test where a model finds a fact, and learn why the middle of a long text is the danger zone

A model with a 128,000-token window answers a question about a contract clause smoothly, confidently and wrongly. Fluent long-context answers do not prove effective long-context processing (slide 15). A test must check where the model can find a fact.

Lost in the middle

Liu and colleagues (2023) put 20 documents, about 4,000 tokens, in one prompt. One document holds the answer, and the test moves it from first place to twentieth. Accuracy traces a U-shaped curve. For GPT-3.5-turbo it is about 76% with the answer first, about 54% in the middle and about 63% last.

With no documents at all (closed book), the same model scores about 56%. An answer buried in the middle leaves the model worse off than no help.

Hide the answer in the text

Pick a view. In the first, drag the answer's place among 20 documents. In the second, set how long a text your toy model handles and see the pass map.

10

The curve is read by eye from the plot on slide 15 (GPT-3.5-turbo-0613, 20 documents), so values are approximate. The needle grid is a toy rule: pass if the text is within the limit, with a small extra reach at the start and end of the text. It is not data.

Needle in a haystack

Insert one odd sentence, the needle, at a chosen depth in a long document, the haystack. The slide's needle is "The best thing in San Francisco is eating a sandwich and sitting in Dolores Park on a sunny day." At the end, ask: "What is the best thing to do in San Francisco?"

Each length and depth is one cell of a pass map. With 12 lengths and 10 depths you run 120 prompts. A needle at depth 25% of a 64,000-token text sits at token 16,000. At 64,000 tokens per prompt, one model reads 7.7 million tokens.

pythondef niah_cell(model, filler, needle, question, length, depth):
    ids = tok(filler)[:length]                     # the haystack, cut to length tokens
    cut = int(depth * length)                      # insert point, e.g. 0.25 * 64000 = 16000
    prompt = ids[:cut] + tok(needle) + ids[cut:] + tok(question)
    answer = model.generate(prompt)
    return "Dolores Park" in answer                # True = a green cell

LongBench: real tasks, not only needles

Needle tests are synthetic. LongBench (Bai et al., ACL 2024) uses real tasks (slide 18):

The failure, the measurement and the fix

The symptom is a confident wrong answer about a fact deep in the prompt. To measure it, ask the same question at ten depths and plot accuracy; a U or a red band says the model skips the middle. Until research closes the gap, put the question and key facts at the edges of the prompt. Cut filler documents, and run a depth map on your own data.

A model answers best when the key document is first or last in a 20-document prompt, and worst in the middle. What is the lesson for how you build the prompt?

Chapter 4

The KV Cache Is a Bill That Grows With Every Token

Compute the cache size from the model's shape, and see when it passes the size of the model itself

A chat service slows down after an hour and crashes when ten users chat at once. The weights did not change. The KV cache grew: the model keeps every earlier token's key and value so it never recomputes them.

Count what one token stores, then multiply. Call the number of chats served at once the batch size BS. Call the layers L, the key and value heads H, the size of each head's vector d, and the text length N.

Say it aloud

Bytes equal B-S times L times H times d times N, times 2, times 2 bytes.

bytes
bytes the size of the KV cache.
BS
B-S the batch size: chats served at once. Each chat has its own cache.
L
L the layers. Llama-2-70B has 80.
H
H the key and value heads per layer: 64 if the model used multi-head attention (MHA).
d
d the numbers in one head's vector: 128.
N
N the text length so far, in tokens.
2
times 2 one vector for the key and one for the value.
2 bytes
times 2 bytes one number in FP16, the usual half-precision format.
In plain words

Multiply the layers L, heads H and head size d to get the numbers in one token's keys. Double it for the values and again for 2-byte numbers. Multiply by the tokens N and the chats BS.

With numbers

Llama-2-70B if it used MHA (slide 20): 80 × 64 × 128 × 2 × 2 = 2,621,440 bytes, 2.5 MB per token. One chat of 4,096 tokens takes 10 GB. Sixteen such chats take 160 GB, two H100 GPUs for the cache alone.

At N = 2,048 the cache passes the model's own 140 GB near a batch of 28 (slide 21). It also costs time, because each new token reads the whole cache. At 3 TB per second, a round figure, reading 160 GB takes about 57 ms per token. This is the memory-bound regime of Lecture 13.

Fill the fridge

Pick a model, then drag the batch and the text length. The blue bar is the weights. The yellow bar is the KV cache. Watch where the yellow bar passes the blue one.

16
4,096

The 70B and 7B shapes come from the formula (80 layers, 64 heads; 32 layers, 32 heads; d = 128). The 8 KV head row uses the published Llama-2-70B layout, where heads share keys and values, so the cache is 8 times smaller. GB here means 230 bytes, as on the slide. One H100 holds 80 GB.

pythondef kv_bytes(bs, layers, kv_heads, head_dim, n_tokens, bytes_per=2):
    return bs * layers * kv_heads * head_dim * n_tokens * 2 * bytes_per   # the 2 is K and V

per_token = kv_bytes(1, 80, 64, 128, 1)             # 2,621,440 bytes = 2.5 MB
weights   = 70e9 * 2                              # 140 GB in FP16
n_cross   = weights / per_token                   # about 53,400 tokens at batch 1

The released Llama-2-70B shares each key and value among eight query heads, so its cache is 8 times smaller. The device's third button shows it.

The failure: a 7B model on one 80 GB GPU has 66 GB left after its 14 GB of weights. At 0.5 MB per token, a 4,096-token chat needs 2 GB, so 33 chats fit. At 32,768 tokens a chat needs 16 GB and only 4 fit. The fix is to shrink what each chat keeps, and the rest of the lecture shows how.

A model has 32 layers, 32 KV heads and head size 128, in FP16. What is its cache size per token for one chat?

Chapter 5

Window Attention Collapses Because the First Tokens Are Anchors

Find out why dropping old tokens breaks a model, and why the first token matters more than its meaning

A kitchen voice assistant chats all day. Slide 23 names two problems: the cache grows without limit, and models fail on texts longer than their training length. The obvious fix is window attention: keep only the last L tokens' keys and values. Memory is fixed, and the cost is O(TL) for T tokens instead of O(T2).

Once the text passes L and the first token leaves, the model collapses. Perplexity, how surprised the model is by real text, jumps from about 5 to 5,158. Slide 27 compares three methods on Llama-2-7B; the recompute row is the quality we want at the window's price.

MethodCostPerplexityVerdict
Dense attentionO(T²)5,641Slow, and fails past the training length
Window attentionO(TL)5,158Breaks when the first tokens are evicted
Sliding window with recomputeO(TL²)5.43Good quality, but rebuilds the cache for every new token

Where the attention goes

In Llama-2-7B attention maps (slide 28), the first two layers look at neighbours. In every later layer, almost every token puts a large share of its attention on the first token, whatever it says. These are attention sinks. Han's group first saw them in SpAtten in 2021 (slide 29).

The cause is the softmax, the step that turns scores into weights. Call the score of cached token i x-i.

Say it aloud

Softmax of x at i equals e to the x-i, divided by the sum over j of e to the x-j.

SoftMax(x)i
softmax of x at i the attention weight on cached token i.
exi
e to the x-i the score x-i made positive. A higher score gives a much larger number.
∑j
the sum over j add e to the x-j for every cached token j. Dividing by it makes the weights sum to 1.
In plain words

Make every score positive with e. Divide each one by the total. The weights must add to 1, so a token with nothing to look up still spends its whole budget somewhere.

With numbers

With made-up scores: 8 cached tokens, token 0 at 4 and seven at 0. e gives 54.6 and seven 1s, a total of 61.6. Token 0 gets 0.886 and each other token 0.016. Evict token 0 and each of the seven gets 1 / 7 = 0.143, nearly nine times more.

The model parks that spare weight on a token every later token can see. In left-to-right language modelling, only the first tokens are in everybody's past (slide 30).

Park the attention

A token with nothing to look up spreads its attention over 12 cached tokens. Drag the first token's pull, then evict it with the button.

4.0

Illustrative: scores for the other tokens are small made-up values near 0. The effect, a large share on the first token that moves to others when it leaves, is the lecture's explanation on slide 30.

Position, not meaning

Slide 30 swaps the first four tokens for four newlines, which carry no meaning (Llama-2-13B, perplexity):

CachePerplexity
0 sinks + 1,024 recent (window)5,158.07
4 true first tokens + 1,020 recent5.40
4 newlines + 1,020 recent5.60

The position matters, not the meaning. Encoders have sinks too: on background patches in vision transformers, and on [SEP] tokens in BERT (slide 38).

python# How much attention does each token get? attn is (heads, queries, keys), rows sum to 1.
sink_mass = attn[:, :, :4].sum(-1).mean()        # share of attention on the first 4 tokens
print(f"first 4 tokens get {sink_mass:.0%} of all attention")
A window model has a 1,024-token cache. At token 1,025 the first token leaves the cache and perplexity jumps from about 5 to 5,158. What best explains it?

Chapter 6

StreamingLLM Keeps the Anchors and Slides the Rest

Hold a few sink tokens forever, roll a window behind them, and number the cache from zero

The window broke because the anchor left. StreamingLLM (Xiao et al., 2023) keeps it. A model trained on a finite window then handles text of any length, with no extra training (slide 31).

The cache has two regions: the first four tokens, the sinks, which never leave, and a rolling window of the latest L tokens. The total stays at 4 + L tokens. Cost stays O(TL), and perplexity is 5.40, against 5,158 for the plain window.

Number the cache, not the text

After tokens 4 and 5 leave, the cache holds tokens 0 1 2 3 6 7 8 9. The model never saw a gap in positions during training. So StreamingLLM uses positions in the cache: 0 to 7, and token 9 gets position 7 (slide 32). Think of eight train seats with fixed numbers and changing passengers. Positions never pass the cache size, which also removes the problem of Chapter 1.

Ride the rolling cache

Press Step to generate the next token. The cache keeps 4 sinks and the latest 4 tokens. Switch between numbering the cache and keeping the original text positions.

Illustrative: 4 sinks, a window of 4 and a toy training length of 8 positions, copied from the sizes drawn on slides 31 and 32. A real window holds hundreds or thousands of tokens.

Forget this rule and perplexity drifts up on long chats. To see why, print the positions: with a 4,096-token cache and a 20,000-token text, text positions reach five times a 4,096-token training length. The fix is one line: number the cache.

What the numbers say

The limit

Non-stop chatting is not infinite context (slide 39). Evicted tokens are gone. Take Llama-2-7B-32K-Instruct with a 4 + 2,044 cache. It recalls a fact 460 tokens back with 85.80 accuracy, and a fact 2,300 tokens back with 0.00. A 4 + 4,092 cache recovers 61.60 at that distance. The next three chapters keep old facts within reach.

pythonfrom collections import deque

class StreamingCache:
    def __init__(self, sinks=4, window=1020):
        self.sinks, self.kv = sinks, []              # sink KV, never evicted
        self.recent = deque(maxlen=window)           # oldest entry drops out by itself
    def append(self, k, v):                       # k, v: (layers, heads, head_dim) for one token
        (self.kv if len(self.kv) < self.sinks else self.recent).append((k, v))
    def get(self):
        items = self.kv + list(self.recent)          # sinks first, then the window
        pos = range(len(items))                      # cache positions 0..n-1, not text positions
        return items, pos                            # apply RoPE with pos at attention time
A StreamingLLM cache holds 4 sinks and a window of 512. The model is writing token 2,000. What does the cache hold, and what position does the newest token get?

Chapter 7

DuoAttention Gives Full Memory Only to the Heads That Need It

Split attention heads into those that search the whole text and those that watch only the recent past

One hour of video at 1 frame per second is about 1 million tokens (a 224 × 224 image is 256 tokens). For Llama-3-8B at 1 million tokens, the cache takes 137 GB and each token about 92 ms to decode (slide 42). Eviction methods lose facts on needle tests.

A layer runs many heads side by side. DuoAttention (Xiao et al., 2024) finds two kinds (slide 44). A retrieval head searches the whole text for the tokens that matter. A streaming head looks only at the sinks and recent tokens. So retrieval heads keep a full cache and streaming heads keep a small constant one.

Pick the heads that keep everything

32 toy heads in 4 layers. Ringed heads are the real retrieval heads. Choose how many keep a full cache, picked by the learned gate or at random.

8

Illustrative: 32 heads, 8 of them retrieval heads, a text of 100,000 tokens, and a streaming cache of 4 sinks plus 256 recent tokens. The recall rule is a toy: recall is the share of retrieval heads that keep a full cache. The real model has about 1,000 heads.

How the heads are found

Each head gets a trainable gate, alpha, that blends two outputs.

Say it aloud

Attn equals alpha times full-attn, plus one minus alpha, times streaming-attn.

attn
attn the output of one head during training.
α
alpha this head's gate, from 0 to 1. Near 1 means the head needs the full text.
full_attn
full-attn ordinary causal attention over every token.
1 − α
one minus alpha the share left for the streaming output.
streaming_attn
streaming-attn attention over the sinks and recent tokens only.
In plain words

Weight the full output by alpha and the streaming output by one minus alpha. Add the two.

With numbers

With made-up values: alpha 0.9, full output 2.0, streaming output 1.0. Attn = 0.9 × 2.0 + 0.1 × 1.0 = 1.9, close to the full answer.

The loss keeps the gated model close to the full model and pushes gates down.

Say it aloud

L equals L-distill plus lambda times L-reg, and L-reg is the sum of the absolute values of alpha-i-j.

L
L the training loss for the gates. The model weights stay frozen.
Ldistill
L-distill the squared gap between the last hidden states of the full model and the gated model, on the last l tokens.
λ
lambda how hard to push gates down: 0.05 in the paper.
Lreg
L-reg the penalty on gates, an L1 (Lasso) term.
∑
the sum over i and j add over every layer i and head j.
|αi,j|
the absolute value of alpha-i-j the size of the gate of head j in layer i.
In plain words

Add the drift of the gated model, L-distill, to lambda times the total of the gates. A head keeps a high gate only if lowering it raises L-distill.

With numbers

With made-up values: four heads with gates 0.9, 0.1, 0.05 and 0.8, so L-reg = 1.85. With L-distill = 0.20, L = 0.20 + 0.05 × 1.85 = 0.29.

The training data, a synthetic passkey set, hides ten 32-word passkeys in a long story (slide 47). Only a retrieval head can recall a distant one, so its gate rises. About 1,000 gates train (32 × 32 for Llama-2-7B) in a few hours on 8 A100s.

Deployment

Keep 25% of Llama-2-7B's 1,024 heads full. At 100,000 tokens with 260-token streaming caches, the cache is 0.25 + 0.75 × 260 / 100,000 = 25.2% of full. Measured memory falls up to 2.45 times, because weights and activations do not shrink.

python# Deployment: one layer, two caches (shapes in comments)
is_retrieval = (alpha > tau)                         # (H,) bool, from the trained gates
order = argsort(~is_retrieval)                       # retrieval heads first: reorder Wq, Wk, Wv by it
k_full, v_full = cache.retrieval                     # (H_r, N, d) grows with the text
k_str,  v_str  = cache.streaming                     # (H_s, 4 + recent, d) constant size
out = cat([attend(q[:H_r], k_full, v_full),
           attend(q[H_r:], k_str,  v_str)], dim=0)  # concatenate heads, then the output projection
Why does DuoAttention train its gates on a passkey task instead of plain text?

Chapter 8

Quest Keeps Every Token and Reads Only the Pages the Query Needs

Bound each page's best possible score with two small vectors, then load only the top pages

Every method so far decides once which tokens to keep. SpAtten (slide 56) prunes tokens with a small total of past attention, and H2O works in the same spirit. Slide 57 names the risk: a dropped token may matter to a future query.

Slide 58 takes the text "... B ... is". No earlier query attends to B, so B looks useless. But the last token, "is", needs B. Which token is critical depends on the current query. Quest keeps the full cache and reads only what this query needs: query-aware sparsity.

Pages and a cheap bound

Quest groups keys into pages of, say, 16 tokens and reads only the top pages each step. To rank a page without reading it, Quest stores two small vectors per page. They hold the largest value of each channel over its keys, k-max, and the smallest, k-min. Call the current query q and its channel i q-i.

Say it aloud

Score equals the sum over i of the max of q-i times k-max-i and q-i times k-min-i.

score
score an upper bound on the query's dot product with any key in the page.
∑i
the sum over i add over the channels of the head vector, 1 to d.
max( , )
the max of keep the larger of the two products.
qi
q-i channel i of the current query.
kmax,i
k-max-i the largest value of channel i over the page's keys.
kmin,i
k-min-i the smallest value of channel i over the page's keys.
In plain words

For each channel, multiply q-i by both ends of the range and keep the larger product. Add over the channels. No key in the page can beat this, because q-i times a key's value is largest at one end of the range.

With numbers

Slide 75 uses q = (1, −2, 2, −2, 1, 1, 1, −3). Page (a) gives 2 + 2 + 4 − 2 + 4 + 5 + 2 + 6 = 23. Page (b) gives 4 + 4 + 6 + 6 + 2 + 4 + 5 + 9 = 40. Quest reads page (b) first.

Flip to the right pages

Six pages of four keys each. Pick a query. Quest ranks pages by their bound and reads the top ones. Change the query and the chosen pages change.

2

Illustrative: random keys with 4 channels, 4 tokens per page, made up for this lesson. The bound is exact and always at or above the true best score. Attention mass is the softmax share of the tokens in the chosen pages.

The algorithm and its cost

When a token joins the cache, Quest updates its page's k-max and k-min. At each step it scores every page, keeps the top K, and runs ordinary attention on their tokens only (slide 60). With 16-token pages the two vectors add 12.5% to the key cache, about 6% to keys plus values. Each step reads K pages instead of the whole cache (slide 59).

What the lecture measured

pythondef quest_step(q, K, V, kmax, kmin, top, page=16):    # q (d,), K,V (N,d), kmax,kmin (P,d)
    score = np.maximum(q * kmax, q * kmin).sum(-1)  # (P,) upper bound per page
    keep = np.argsort(-score)[:top]                  # the top pages for THIS query
    idx = np.concatenate([np.arange(p*page, (p+1)*page) for p in keep])
    w = softmax(K[idx] @ q / np.sqrt(len(q)))        # ordinary attention, on the chosen tokens only
    return w @ V[idx]                                # (d,)
Why can Quest pick pages for a query without reading the keys in them?

Chapter 9

LServe Puts the Tricks Into One Serving System

Mix static and dynamic sparsity, decouple page size from selection, and reuse choices from step to step

A real service must run quantised caches, streaming heads and query-aware pages together, on a GPU, in both pre-filling and decoding. LServe (Yang et al., MLSys 2025) unifies KV cache quantisation, static sparsity from DuoAttention, and dynamic sparsity from MInference (pre-filling) and Quest (decoding) (slide 69).

Static sparsity fixes the pattern in advance: a streaming head always reads the sink and local blocks. Dynamic sparsity picks per query: a dense head reads only its selected pages. A GPU works in blocks of tokens, so it never reads a skipped block (slides 70, 71).

The page size dilemma

A page is the unit of memory the cache manager hands out, as in vLLM. Big pages read faster. But a big page mixes many tokens, so its k-max and k-min bound is loose and selection loses accuracy (slide 72). Per-step decoding time at 8,192 tokens:

Page size (tokens)Decode stepSlowdown
1677.1 ms1.52 times
3263.0 ms1.25 times
6451.0 ms1.01 times
12850.6 ms1.00 times

The same slide's needle maps grow red patches as the page grows from 16 to 64 tokens, at a 4,096-token budget.

LServe's fix is hierarchical paging (slides 73 to 77). The physical page sets the memory layout and can be large, say 64 tokens. The logical page is what the selector scores and stays small, say 16. A physical page scores the best of its logical pages: in slide 75, max(23, 40) = 40.

Decouple the layout from the choice

The row of 128 tokens is cut into physical pages. Pick a size. Thin lines mark logical pages of 16. Then set how often the selector runs.

4 steps

Illustrative: 128 tokens, 3 hot regions of 16 tokens marked by the dotted outline, a read budget of 48 tokens. The decode step times (77.1, 63.0, 51.0 and 50.6 ms) are from the table on slide 72 at sequence length 8,192.

The reusable page selector

Scoring every page for every query can become the bottleneck of decoding (slide 78). Consecutive queries need nearly the same pages, which is temporal locality. So LServe runs the selector every few steps and reuses its choice in between. A reuse interval of 4 cuts selector work 4 times.

Accuracy and speed

RULER, Llama-3-8B32K64K128K160K192K256K
Dense90.586.883.879.379.679.4
LServe91.085.681.079.076.175.7

LServe tracks dense at moderate lengths and loses up to 3.7 points at 256K. On DS-R1-Llama-8B it keeps AIME@2024 at 43.3 and scores 85.4 on MATH500 against 84.2 dense (slide 79). Decoding runs 1.3 to 2.1 times faster than vLLM on A100 and L40S GPUs (slide 80).

python# Hierarchical page scoring: logical pages of 16 tokens inside physical pages of 64
logical = np.maximum(q * kmax_log, q * kmin_log).sum(-1)  # (P_logical,) bound per logical page
physical = logical.reshape(-1, 4).max(-1)               # (P_physical,) best logical page inside
keep = np.argsort(-physical)[:budget_pages]                # load whole physical pages: fast reads
# reusable selector: recompute `keep` only every `reuse` decoding steps
if step % reuse == 0: keep = select(q)
What does hierarchical paging let LServe do?

Chapter 10

Mamba and Jamba Replace the Growing Cache With a Fixed State

Read the text one token at a time, update a memory of fixed size, and train it with a parallel scan

A reader of a novel keeps a running summary, not every word. Mamba (Gu and Dao, 2024) keeps the MLP and swaps attention, the step that moves information between tokens, for a state space model (SSM). Its cost grows linearly with length (slide 82).

Call the input at step t x-t and the fixed-size memory, the state, h-t.

Say it aloud

H-t equals A-bar times h-t-minus-one, plus B-bar times x-t; and y-t equals C times h-t.

ht
h-t the state after token t. Its size never changes: this is the whole memory.
Ā
A-bar how much of the old state to keep: how to forget over time.
ht−1
h-t-minus-one the state before this token.
B̄
B-bar what part of the new input to write in.
xt
x-t the input at token t.
yt
y-t the output at token t.
C
C how to read the state to make the output.
In plain words

Fade the old state by A-bar. Add the input x-t scaled by B-bar. Read the output with C.

With numbers

With made-up single numbers: A-bar 0.5, B-bar 1, C 1, inputs 4, 1, 5. Then h-1 = 4, h-2 = 0.5 × 4 + 1 = 3, and h-3 = 0.5 × 3 + 5 = 6.5. The memory is one number for any input length.

Unrolled, each output is a weighted sum of past inputs, a convolution that trains in parallel (slide 83). Selectivity makes A-bar, B-bar and C depend on the input, so "hamburger" writes in strongly and "to" weakly (slide 84). The weights then change every step, which breaks the convolution (slide 85).

The fix is a parallel scan (Blelloch, 1989; slide 86). The running totals of (4, 1, 5, 3, 9, 2) take six steps one by one. Adding neighbours one, two, then four places back takes three passes: about log2 N for N tokens.

Scan the totals

Press Step to run the next pass. One by one needs a pass per token. The scan adds neighbours one, two, then four places back. Drag the length to compare the pass counts.

1,024

The six numbers (4, 1, 5, 3, 9, 2) are the example on slide 86. The pass counts are exact: N for the one-by-one loop, log2 N passes for the neighbour-doubling scan.

A hybrid: Jamba

A fixed state can lose an exact old sentence. Jamba (Lieber et al., 2024) mixes both: an 8-layer block has 1 attention layer and 7 Mamba layers, with Mixture-of-Experts (MoE) every second layer. Only attention layers keep a KV cache, so it fits on one 80 GB GPU at 256,000 tokens (slide 87).

Mix the layers

A block has eight layers. Drag how many use attention. The others are Mamba layers with a fixed state. Watch the cache at 256,000 tokens.

1

Illustrative: a 32-layer stack with the shape of Llama-2-7B (32 heads of size 128, FP16), one chat at 256,000 tokens. That is 16 KB per token per layer. Jamba's real shape differs. The 1 in 8 mix is the ratio on slide 87.

python# Selective SSM as a recurrence. x (T, d) input; a, b, c are computed from x, per token.
h = np.zeros(n_state)
for t in range(T):                       # slow in training, so Mamba uses a parallel scan instead
    a_t, b_t, c_t = a(x[t]), b(x[t]), c(x[t])   # the matrices depend on the token: selectivity
    h = a_t * h + b_t * x[t]                    # fixed-size state, no cache grows
    y[t] = (c_t * h).sum()                      # read the output from the state
# Why a scan works: the step "multiply by a, then add b" followed by (a2, b2)
# is again one step, (a*a2, a2*b + b2). That rule is associative, so steps group in any order.
Why does selectivity (A, B and C depending on the input) force Mamba to use a parallel scan instead of a convolution?

Chapter 11

The Field Guide: Long Context on One Page

Review the numbers, the terms and the code, then pick a tool for the memory problem in front of you

The one-paragraph summary

A long window has two problems: the model must understand positions it never trained on, and the cache grows without limit. RoPE interpolation (m′ = m / s) fixes the first with a short fine-tune, and LongLoRA makes that fine-tune cheap with shifted sparse attention plus trainable norms and embeddings. For the second, window attention fails because attention parks spare softmax mass on the first tokens, so StreamingLLM keeps 4 sinks plus a window and numbers the cache. DuoAttention keeps full caches only for retrieval heads. Quest keeps everything and reads only the top pages by an upper bound on the score. LServe combines both with hierarchical pages and a reusable selector. Mamba and Jamba change the layer so that the memory is fixed.

The numbers that matter

WhatNumberWhy it matters
RoPE slow pair at position 8,192, trained to 4,0960.82 rad against 0.41 rad seenUnseen angles break the model; halve the position (Ch 1)
LongLoRA, full fine-tune against plain LoRA against LoRA plus norms and embeddingsperplexity 8.08, 11.44, 8.12Train norms (under 0.004%) and embeddings (under 2%) too (Ch 2)
Grouped attention with 4 groupsone quarter of the pairsN² / G, with a shift so groups talk (Ch 2)
Lost in the middle, 20 documentsabout 76% first, 54% middle, 63% lastBelow the 56% of no documents at all (Ch 3)
Llama-2-70B KV cache if MHA2.5 MB per token; 160 GB at batch 16 and 4,096 tokensBS × L × H × d × N × 2 × 2 bytes (Ch 4)
Window attention, dense, recompute, StreamingLLMperplexity 5,158; 5,641; 5.43; 5.40Keep the first tokens (Ch 5, 6)
Four newlines instead of the real first four tokens5.60 against 5.40Sinks are about position, not meaning (Ch 5)
StreamingLLM against recomputeup to 22.2 times faster; 4 million tokensStable, but evicted facts are gone (Ch 6)
DuoAttention gatesabout 1,000 numbers; hours on 8 A100s; λ = 0.05Learn which heads need the full text (Ch 7)
DuoAttention with 8-bit weights and 4-bit KV3.3 million tokens on one A100Tricks multiply (Ch 7)
Quest page scores from the slide23 for page (a), 40 for page (b)Per-channel max and min give an upper bound (Ch 8)
Quest speed7.03 times (attention), 2.23 times (end to end)Read a constant number of pages (Ch 8)
LServe against vLLM1.3 to 2.1 times faster decodingStatic plus dynamic sparsity, big physical pages, reuse (Ch 9)
Prefix sum of (4, 1, 5, 3, 9, 2)(4, 5, 10, 13, 22, 24) in 3 passesA scan needs about log2 N passes (Ch 10)
Jamba block8 layers, attention to Mamba 1 to 7, 256,000 tokens on 80 GBOnly attention layers keep a cache (Ch 10)

The terms

TermPlain meaningWhere
Context windowHow many tokens the model can look at when it writes the next one0
KV cacheThe saved key and value of every earlier token0, 4
RoPEPosition as a rotation of each query and key pair1
Position interpolationShrink positions so angles stay in the trained range1
S2-AttnTraining attention in groups, half the heads shifted by half a group2
Needle in a haystackHide a fact at a depth in long text and ask for it3
PerplexityHow surprised the model is by real text; lower is better5
Attention sinkAn early token that soaks up spare attention5
StreamingLLMSinks plus a rolling window, numbered by cache position6
Retrieval head, streaming headA head that searches all text; a head that watches sinks and recent tokens7
Query-aware sparsityChoosing what to read from the current query8
Hierarchical pagingBig physical pages, small logical pages for scoring9
State space model, selectivityA fixed-size state updated per token; matrices that depend on the token10
Parallel scanRunning totals in about log2 N parallel passes10

A checklist before you choose

The core as code

The two ideas that run through the lecture fit in a few lines: number the cache, and score pages by an upper bound. Shapes are in the comments.

pythonimport numpy as np

def rope_angles(pos, d, scale=1.0, base=10000):
    theta = base ** (-2 * np.arange(d // 2) / d)          # (d/2,)
    return (pos / scale)[:, None] * theta                 # (N, d/2): interpolation divides the position

def streaming_keep(n_tokens, sinks=4, window=1020):
    keep = list(range(min(sinks, n_tokens))) + list(range(max(sinks, n_tokens - window), n_tokens))
    return keep, np.arange(len(keep))                    # kept token ids, cache positions 0..n-1

def page_bound(q, kmax, kmin):                         # q (d,), kmax/kmin (P, d)
    return np.maximum(q * kmax, q * kmin).sum(-1)         # (P,) upper bound on any key's score

def kv_bytes(bs, layers, kv_heads, d, n, b=2):
    return bs * layers * kv_heads * d * n * 2 * b          # the 2 is K and V

Where it sits in the field

Long context is the meeting point of three fields. Training: position tricks and cheap fine-tunes. Serving: cache layout, paging and quantisation, as in vLLM. Architecture: layers with fixed state, from RNNs to Mamba. The lecture shows that no single trick wins. The best systems stack them: fewer bytes per entry, fewer heads with full caches, fewer pages read per step.

Keep going

The takeaway. A long context has two bills: positions the model never saw, and a cache that grows with every token. Pay the first with interpolation and a short fine-tune. Pay the second by choosing what to keep (sinks, retrieval heads), what to read (query-aware pages) or what to replace (a fixed state). Then test at every depth.
A team serves a 128,000-token chat. Memory is the limit, and users ask about facts from the start of the chat. Which pairing fits best?

Credit

This lesson follows Lecture 15 of MIT 6.5940: TinyML and Efficient Deep Learning Computing (Fall 2026), taught by Song Han and the MIT HAN Lab. Read the lecture on the course page, where the slides are linked. The papers the lecture cites include RoFormer, Position Interpolation, LongLoRA, Lost in the Middle, LongBench, StreamingLLM, SpAtten, DuoAttention, Quest, LServe, Mamba and Jamba. Every number here comes from the slides unless a device says it is illustrative. The explanations and devices are our own.

Now press Teach and explain, from memory, why window attention collapses and how StreamingLLM repairs it. Then go back to the cache at the top and push the text length to 40 once more.

MIT 6.5940 Lecture 15: Long-Context LLMs
The course page and slides · Back to Lecture 14 · On to Lecture 16 · Back to Gleams