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.
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
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.
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.
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:
Chapter 1
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.
Angle-i equals m over s, times theta-i.
Divide the position m by the stretch s. Multiply by the speed theta-i. Turn pair i by that angle.
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.
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 score of q and k depends only on the gap m minus n, so RoPE is a relative position code.
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.
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.
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
Chapter 2
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.
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.
Pairs equals G times N over G squared, which equals N squared over G.
Each group scores every pair inside it. There are G groups. So grouping divides the work by G.
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):
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.
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
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 trains | Perplexity |
|---|---|
| All weights (full fine-tune) | 8.08 |
| LoRA, rank 8 | 11.44 |
| LoRA, rank 256 | 11.98 |
| LoRA rank 8 + norms | 10.49 |
| LoRA rank 8 + norms + embeddings | 8.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).
Chapter 3
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.
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.
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.
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.
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
Needle tests are synthetic. LongBench (Bai et al., ACL 2024) uses real tasks (slide 18):
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.
Chapter 4
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.
Bytes equal B-S times L times H times d times N, times 2, times 2 bytes.
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.
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.
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.
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.
Chapter 5
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.
| Method | Cost | Perplexity | Verdict |
|---|---|---|---|
| Dense attention | O(T²) | 5,641 | Slow, and fails past the training length |
| Window attention | O(TL) | 5,158 | Breaks when the first tokens are evicted |
| Sliding window with recompute | O(TL²) | 5.43 | Good quality, but rebuilds the cache for every new token |
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.
Softmax of x at i equals e to the x-i, divided by the sum over j of e to the x-j.
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 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).
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.
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.
Slide 30 swaps the first four tokens for four newlines, which carry no meaning (Llama-2-13B, perplexity):
| Cache | Perplexity |
|---|---|
| 0 sinks + 1,024 recent (window) | 5,158.07 |
| 4 true first tokens + 1,020 recent | 5.40 |
| 4 newlines + 1,020 recent | 5.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")
Chapter 6
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.
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.
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.
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
Chapter 7
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.
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.
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.
Each head gets a trainable gate, alpha, that blends two outputs.
Attn equals alpha times full-attn, plus one minus alpha, times streaming-attn.
Weight the full output by alpha and the streaming output by one minus alpha. Add the two.
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.
L equals L-distill plus lambda times L-reg, and L-reg is the sum of the absolute values of alpha-i-j.
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 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.
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
Chapter 8
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.
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.
Score equals the sum over i of the max of q-i times k-max-i and q-i times k-min-i.
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.
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.
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.
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.
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).
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,)
Chapter 9
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).
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 step | Slowdown |
|---|---|---|
| 16 | 77.1 ms | 1.52 times |
| 32 | 63.0 ms | 1.25 times |
| 64 | 51.0 ms | 1.01 times |
| 128 | 50.6 ms | 1.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.
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.
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.
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.
| RULER, Llama-3-8B | 32K | 64K | 128K | 160K | 192K | 256K |
|---|---|---|---|---|---|---|
| Dense | 90.5 | 86.8 | 83.8 | 79.3 | 79.6 | 79.4 |
| LServe | 91.0 | 85.6 | 81.0 | 79.0 | 76.1 | 75.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)
Chapter 10
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.
H-t equals A-bar times h-t-minus-one, plus B-bar times x-t; and y-t equals C times h-t.
Fade the old state by A-bar. Add the input x-t scaled by B-bar. Read the output with C.
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.
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.
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 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).
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.
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.
Chapter 11
Review the numbers, the terms and the code, then pick a tool for the memory problem in front of you
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.
| What | Number | Why it matters |
|---|---|---|
| RoPE slow pair at position 8,192, trained to 4,096 | 0.82 rad against 0.41 rad seen | Unseen angles break the model; halve the position (Ch 1) |
| LongLoRA, full fine-tune against plain LoRA against LoRA plus norms and embeddings | perplexity 8.08, 11.44, 8.12 | Train norms (under 0.004%) and embeddings (under 2%) too (Ch 2) |
| Grouped attention with 4 groups | one quarter of the pairs | N² / G, with a shift so groups talk (Ch 2) |
| Lost in the middle, 20 documents | about 76% first, 54% middle, 63% last | Below the 56% of no documents at all (Ch 3) |
| Llama-2-70B KV cache if MHA | 2.5 MB per token; 160 GB at batch 16 and 4,096 tokens | BS × L × H × d × N × 2 × 2 bytes (Ch 4) |
| Window attention, dense, recompute, StreamingLLM | perplexity 5,158; 5,641; 5.43; 5.40 | Keep the first tokens (Ch 5, 6) |
| Four newlines instead of the real first four tokens | 5.60 against 5.40 | Sinks are about position, not meaning (Ch 5) |
| StreamingLLM against recompute | up to 22.2 times faster; 4 million tokens | Stable, but evicted facts are gone (Ch 6) |
| DuoAttention gates | about 1,000 numbers; hours on 8 A100s; λ = 0.05 | Learn which heads need the full text (Ch 7) |
| DuoAttention with 8-bit weights and 4-bit KV | 3.3 million tokens on one A100 | Tricks multiply (Ch 7) |
| Quest page scores from the slide | 23 for page (a), 40 for page (b) | Per-channel max and min give an upper bound (Ch 8) |
| Quest speed | 7.03 times (attention), 2.23 times (end to end) | Read a constant number of pages (Ch 8) |
| LServe against vLLM | 1.3 to 2.1 times faster decoding | Static 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 passes | A scan needs about log2 N passes (Ch 10) |
| Jamba block | 8 layers, attention to Mamba 1 to 7, 256,000 tokens on 80 GB | Only attention layers keep a cache (Ch 10) |
| Term | Plain meaning | Where |
|---|---|---|
| Context window | How many tokens the model can look at when it writes the next one | 0 |
| KV cache | The saved key and value of every earlier token | 0, 4 |
| RoPE | Position as a rotation of each query and key pair | 1 |
| Position interpolation | Shrink positions so angles stay in the trained range | 1 |
| S2-Attn | Training attention in groups, half the heads shifted by half a group | 2 |
| Needle in a haystack | Hide a fact at a depth in long text and ask for it | 3 |
| Perplexity | How surprised the model is by real text; lower is better | 5 |
| Attention sink | An early token that soaks up spare attention | 5 |
| StreamingLLM | Sinks plus a rolling window, numbered by cache position | 6 |
| Retrieval head, streaming head | A head that searches all text; a head that watches sinks and recent tokens | 7 |
| Query-aware sparsity | Choosing what to read from the current query | 8 |
| Hierarchical paging | Big physical pages, small logical pages for scoring | 9 |
| State space model, selectivity | A fixed-size state updated per token; matrices that depend on the token | 10 |
| Parallel scan | Running totals in about log2 N parallel passes | 10 |
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
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.
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.