Keep only the most recent tokens and a language model breaks: perplexity jumps from 5.40 to 5,158. Keep the first four tokens as well, and it streams 4 million tokens on a fixed cache.
Pick a cache policy, then press Stream. A 65,000-token book flows through Llama-2-13B. Watch what each policy keeps, what it costs, and when it breaks. Then we build, piece by piece, the KV cache, the collapse, the sink and the fix.
You need a little Python and what a probability is. We build the rest from zero.
Session 8 of Georgia Tech CS 8803, LLM seminar. It rests on one paper: Xiao, Tian, Chen, Han and Lewis, Efficient Streaming Language Models with Attention Sinks (ICLR 2024). Every idea is re-taught here in our own words and devices.
The four whole-book perplexities are the paper's (Figure 1: Llama-2-13B, the first PG-19 test book, 65K tokens, cache 1,024). The trace's shape is illustrative. Memory uses Llama-2-13B's 800 KiB per token (Chapter 1).
Chapter 0
See why a chat that never ends needs a memory that stops growing
An assistant stays open on a desk all day. Each message adds tokens. To avoid redoing work, the model saves every past token's key and value vectors in a KV cache. The cache grows by one entry per token and never shrinks.
The GPU has a fixed number of gigabytes. So the question is not whether the cache runs out of room. It is when.
Drag through the day. Blue keeps every token. Teal keeps a fixed 1,024. The yellow line is what the card can give the cache. Count the weights, and the line drops.
Made-up traffic: 100 tokens a minute. Llama-2-7B in 16-bit numbers: 512 KiB of cache per token, 12.6 GiB of weights, a 24 GiB card. Activations ignored.
With made-up numbers: 100 tokens a minute for 8 hours is 8 × 60 × 100 = 48,000 tokens. At 512 KiB each, that is 48,000 × 512 KiB = 23.4 GiB. A bigger card buys a longer runway, but the runway is still finite.
The obvious fix keeps only the last L tokens. This is window attention. Memory stays flat. But the model's perplexity, a score of how surprised it is by the text (lower is better), jumps from 5.40 to 5,158. The paper below explains why, and fixes it by keeping four extra tokens.
| Policy | What it keeps | Work for T tokens | Book perplexity |
|---|---|---|---|
| Dense attention | every token | T² | 5,641 |
| Window attention | the last L | T × L | 5,158 |
| Window with recompute | rebuilds the last L for each token | T × L² | 5.43 |
| StreamingLLM | the first 4 and the last L | T × L | 5.40 |
Figure 1 of the paper: Llama-2-13B, the first book of the PG-19 test set (65K tokens), L = 1,024.
Failure. A long session dies with an out-of-memory error. Measure: cached tokens times bytes per token, against the memory left after the weights. Fix: put a ceiling on the cache that does not break the model. That is this session.
Chapter 1
Derive how many bytes one token costs, from the shape of the model
At each layer, every token makes three vectors. The query says what it looks for. The key says what it offers. The value is what it hands over.
The newest token compares its query with every past key, turns the scores into weights, and mixes the past values. (New to attention? Start with Attention and Transformers.)
A past token's key and value never change, because a token only looks backward. Only the newest token needs a query. So the model caches keys and values and throws each query away.
How many bytes does one token add? Call the number of layers nL. Call the width of the keys at one layer dkv: the number of key heads times the size of each head. Call the bytes per number b. One token costs B bytes.
B equals two, times n-L, times d-k-v, times b.
Take the width of one key, d-k-v. Double it for the value. Multiply by the n-L layers and by b bytes per number. That is B.
Llama-2-7B: n-L = 32 layers, d-k-v = 32 heads × 128 = 4,096, b = 2. B = 2 × 32 × 4,096 × 2 = 524,288 bytes = 512 KiB per token. A 4-million-token stream would need 1.9 TiB.
Pick a model and drag the token count. The bar is the cache; the marks are a 24 GiB and an 80 GiB card.
Layer counts and widths from the Llama 2 paper (Touvron et al., 2023). Llama-2-70B uses grouped-query attention: 8 key heads for 64 query heads.
Look at Llama-2-70B. It has 10 times the weights of the 7B model. Yet its cache per token is smaller: 2 × 80 × 1,024 × 2 = 320 KiB. It shares 8 key heads among 64 query heads. Query heads cost nothing here; only key heads fill the cache.
pythondef kv_bytes(n_tokens, n_layers=32, n_kv_heads=32, head_dim=128, b=2): return 2 * n_layers * n_kv_heads * head_dim * b * n_tokens print(kv_bytes(1) / 2**10) # 512.0 KiB per token, Llama-2-7B print(kv_bytes(48_000) / 2**30) # 23.4 GiB, the working day # in torch, per layer: k_cache, v_cache of shape (batch, n_kv_heads, seq_len, head_dim) # seq_len grows by 1 every step: the axis this session learns to bound
Failure. A server holds many idle chats and runs out of memory. Measure: the cache depends on tokens held, not on activity, so sum tokens times B over all open chats. Fix: a ceiling per chat, and a timeout per chat.
Chapter 2
Watch perplexity explode at the exact step the first token leaves the cache
Window attention keeps the keys and values of the last L tokens. When a new token arrives and the window is full, the cache drops the oldest one. Memory stays at L × B forever.
The paper tests it on Llama-2-13B with the first book of the PG-19 test set, 65,000 tokens of a real novel. Write a cache as x + y: x initial tokens plus y recent ones. The window 0 + 1024 scores perplexity 5,158.07. The cache 4 + 1020, same size, scores 5.40 (Table 1).
The trace is perplexity along a 20,000-token text, on a log scale. Move the cache size and watch where the jump lands.
Illustrative shape after the paper's Figure 3 (20K-token texts). Dense breaks at Llama-2's 4,096-token training length. The plateau heights are toy values.
How do we read 5,158? Call the model's loss on token t ℓt: minus the natural log of the probability it gave the true next token. Average it over all T tokens and raise e to that power. That is the perplexity PPL.
P-P-L equals e to the power of: one over T, times the sum over t of ell-t.
Score each token by its loss ell-t. Average the T losses. Raise e to that average. The result is PPL.
PPL 5.40 means an average loss of ln 5.40 = 1.69 nats. PPL 5,158.07 means ln 5,158.07 = 8.55 nats. The gap is 6.86 nats, or 6.86 / ln 2 = 9.9 bits of extra surprise on every token.
Another view: 1 / PPL is the typical probability on the true token. It falls from 1 / 5.40 = 18.5% to 1 / 5,158 = 0.019%. A blind guess over Llama-2's 32,000-token vocabulary has perplexity 32,000.
The jump comes at one step: when the stream passes L tokens and the cache drops the first token (Figure 3). A bigger window moves the step later. At 100 tokens a minute, a 2,048-token window buys about 20 minutes.
pythondef window_step(cache, new_kv, L): cache.append(new_kv) if len(cache) > L: cache.pop(0) # the first time this fires, token 0 leaves: the collapse return cache
Failure. A streaming bot writes fluent text, then garbage after a fixed number of tokens. Measure: perplexity against position on one long text; look for a jump at L. Fix: Chapter 5.
Chapter 3
Look inside the attention maps and find most of the weight on the first token
What is so special about the first token? Usually it is a start marker or an ordinary word. To find out, the authors average the attention maps of Llama-2-7B over 256 sentences of 16 tokens (Figure 2).
Two patterns appear. In layers 0 and 1, each token attends mostly to its neighbours. From layer 2 on, across all layers and heads, a large share of attention lands on the first token, whatever it says.
Each row is one query token; each column is a token it can see. Brighter means more attention. Move through the layers, then swap the first four tokens for line breaks.
A stylized map after the paper's Figure 2, not a re-run. The real share on the first token is "often above half" in most layers (Figure 12).
The paper names this token an attention sink: a token that collects a large share of attention whether or not it is relevant. On 4,096-token inputs, the last token often gives the first token more than half of its attention. That holds in every layer but the bottom two (Figure 12). Llama-2-70B shows the same pattern (Figure 13), and so does BERT, on its [SEP] token (Figure 14).
Is it the content or the position? The test: replace the first four tokens with four line breaks, "\n", and keep them in a 4 + 1020 cache.
| Cache (Llama-2-13B, PG-19 book 1) | Perplexity |
|---|---|
| 0 + 1024, window only | 5,158.07 |
| 4 + 1020, the real first tokens | 5.40 |
| 4 "\n" + 1020, four line breaks | 5.60 |
Worked: the line breaks cost (5.60 − 5.40) / 5.40 = 3.7% in perplexity. Dropping the first slots costs a factor of 5,158.07 / 5.40 = 955. The model needs something at the first positions. It barely cares what.
Failure. A tool trims "empty" tokens, such as a start marker or line breaks, from the front of long prompts, and the model degrades. Measure: the attention each layer gives position 0. Fix: keep the first tokens, whatever they say.
Chapter 4
Derive the collapse from the one equation every attention head runs
The newest token scores each cached key. Call the score for key i xi, a logit. There are N keys. Softmax turns the logits into attention weights ai.
a-i equals e to the x-i, divided by the sum over j from one to N of e to the x-j.
Raise e to each logit x-i. Add all N of them to get Z. Divide each one by Z. The weights a-i always add up to 1.
With made-up logits 8, 2, 1, 0, 1.5 (the first is the sink): e to each is 2,981, 7.39, 2.72, 1 and 4.48. Z = 2,996.5. The sink gets 2,981 / 2,996.5 = 99.48%. The other four get 0.25%, 0.09%, 0.03% and 0.15%.
The weights must add up to 1. A head cannot say "nothing here matters". When no key matches well, the leftover weight still lands somewhere. The paper argues the model learns to park it on one place.
Why the first token? A token only sees tokens before it. In a 4,096-token sequence, the first token is visible to all 4,096 queries; the last is visible to one. The first position is in view at every training step, so it is the easiest spot to train as a sink.
Now evict the sink. The other logits do not move, but Z loses its largest term. Call the sink's weight before eviction a1 and token i's weight after it a′i.
a-prime-i over a-i equals one over, one minus a-one.
Before, token i got e to the x-i over Z. After, it gets the same top over Z minus the sink's term. Z minus that term is Z times one minus a-one. So every survivor grows by one over, one minus a-one.
The sink held a-one = 0.9948. Each survivor grows 1 / 0.0052 = 192 times. The token at 0.25% jumps to 47.4%, though its logit never changed.
The bars are the softmax of the logits printed under them. Raise the sink's logit, then evict it and watch the others grow.
Made-up logits. The four recent tokens keep logits 2, 1, 0 and 1.5 throughout.
Failure. Every head in every layer feeds the next layer a mix that is now dominated by tokens the model meant to ignore. Measure: the evicted slot's share a-one in each layer. Fix: never evict it.
Chapter 5
Pin the first four tokens, roll the rest, and number the cache by slot
StreamingLLM splits the cache in two (Figure 4). The attention sinks are the first four tokens of the stream, kept forever. The rolling cache holds the most recent tokens, oldest out first, as in window attention. The weights do not change, and there is no fine-tuning.
The cache size is fixed at the sinks plus the window. For 4 + 1020 on Llama-2-7B: 1,024 × 512 KiB = 512 MiB, whether the stream is 2,000 or 4 million tokens long.
Each square is a token of the stream. Purple squares stay, warm squares roll, grey squares are gone. Compare the two rows of numbers under the cache.
Four sinks, as in the paper. The dashed square is the token the model writes next. The paper's own example (Section 3.2, Figure 4): generating token 9, the cache holds 0, 1, 2, 3, 6, 7, 8, and token 9 gets position 7.
Positions are the subtle part. Llama-2 uses RoPE and MPT uses ALiBi. Both feed the model the distance between a query and a key. If the cache used text positions, the jump from token 3 to token 6 would show a distance the model never saw in training. So StreamingLLM numbers tokens by their slot in the cache.
For RoPE, the cache stores keys before rotation and rotates them at each decoding step by their cache position. For ALiBi, it applies a contiguous distance bias instead of one that jumps.
pythonclass StreamingCache: def __init__(self, n_sink=4, window=1020): self.n_sink, self.window = n_sink, window self.sink, self.recent = [], [] # (k_unrotated, v) pairs def append(self, k, v): if len(self.sink) < self.n_sink: self.sink.append((k, v)) # pinned forever else: self.recent.append((k, v)) if len(self.recent) > self.window: self.recent.pop(0) # same eviction as Chapter 2, never touches a sink def keys_values(self, rope): kv = self.sink + self.recent return [(rope(k, pos), v) for pos, (k, v) in enumerate(kv)] # cache positions 0..n-1
Trace it with 4 sinks and a window of 6. Tokens 0 to 3 fill the sinks. Tokens 4 to 9 fill the window. Token 10 evicts 4; token 11 evicts 5. The cache holds 0, 1, 2, 3, 6, 7, 8, 9, 10, 11: always 4 + 6 = 10 entries.
Failure. An implementation caches keys after RoPE, with text positions. Past the window, the distances between sinks and recent tokens grow without end. Measure: perplexity past the first eviction with text positions and with cache positions. Fix: cache unrotated keys and rotate by slot.
Chapter 6
Read the ablation: one sink is enough for three models, Llama-2 wants four
Why four? The paper keeps 0 to 8 initial tokens and holds the total cache fixed. It scores each on 400,000 tokens of the PG-19 test set (Table 2).
Pick a model. Each bar is perplexity with that many initial tokens kept, on a log scale. Tap a bar to read it.
The paper's Table 2. Falcon, MPT and Pythia: total cache 2,048. Llama-2-7B: total cache 4,096.
For Falcon, MPT and Pythia, one sink token recovers almost everything. Llama-2-7B keeps improving to four.
Worked, on Llama-2-7B: 1 to 2 sinks cuts perplexity by (11.88 − 10.51) / 11.88 = 11.5%. 2 to 4 cuts it by (10.51 − 9.59) / 10.51 = 8.8%. 4 to 8 cuts it by only (9.59 − 9.54) / 9.59 = 0.5%. Each extra sink costs one slot, 512 KiB, so four is cheap insurance.
The paper's explanation: these models had no consistent first token in pretraining. Llama-2 puts a start token <s> before each paragraph, but before the text is cut into training windows. So position 0 of a window holds a mostly random token, and the model spreads its sink over several early positions.
Failure. A team uses one sink on every model to save a few slots. Llama-2-7B scores 11.88 instead of 9.59, and a short smoke test does not show it. Measure: sweep 0, 1, 2, 4, 8 sinks on a long text for each new model. Fix: default to 4.
Chapter 7
Give the model one dedicated place for spare attention from the first step of pretraining
If the sink is a work-around, design it in. The authors pretrain 160-million-parameter models from scratch, with the Pythia-160M recipe on the deduplicated Pile: batch 256, 143,000 steps, one 8-GPU A6000 server. Only the attention setup differs.
SoftMax1 gives the head a way to attend to nothing. Use the same logits xi as in Chapter 4.
SoftMax-one of x, at i, equals e to the x-i, divided by one plus the sum over j of e to the x-j.
Compute softmax as usual, but add 1 to the denominator. The share that the 1 takes goes to a key whose value is zero, so it adds nothing to the output.
With made-up logits 0, 0, 0, 0 (no key matches): softmax gives each 1/4 = 0.25. SoftMax1 gives each 1/5 = 0.20 and sends 0.20 nowhere. With logits 8, 2, 1, 0, 1.5 the strong key gets 99.45% instead of 99.48%: almost no change.
Four keys. Drag the best key's logit down until nothing matches. Blue is softmax; teal is SoftMax1; the grey slot is the phantom.
Made-up logits: the slider sets the best key; the other three are 0.
| 160M model | 0 + 1024 | 1 + 1023 | 2 + 1022 | 4 + 1020 |
|---|---|---|---|---|
| Vanilla | 27.87 | 18.49 | 18.05 | 18.05 |
| Zero Sink | 29,214 | 19.90 | 18.27 | 18.01 |
| Sink Token | 1,235 | 18.01 | 18.01 | 18.02 |
The paper's Table 3: perplexity on the first PG-19 test sample. For the Sink Token model, the first kept token is the sink token.
The Sink Token model reaches 18.01 with only its one sink kept, below the Vanilla model's best, 18.05. Zero Sink still needs real initial tokens. Evict the dedicated sink token and its model fails too: 1,235. The sink does real work; it is just in a reliable place.
It costs nothing on ordinary tasks. The Sink Token model matches or beats Vanilla on all seven zero-shot benchmarks, for example ARC-Challenge 19.6% against 18.6% (Table 4). Its loss curve tracks Vanilla's (Figure 6). A model with two sink tokens scores 25.73 if you keep only one: it relies on both (Table 10).
Failure. A team tries SoftMax1 on a released checkpoint. Both changes alter what the model learns, so they must be in place from the first pretraining step. Measure: none needed; there is no retrofit. Fix: StreamingLLM for today's models, a sink token for the next one.
Chapter 8
Measure StreamingLLM against the one baseline that keeps quality
One baseline keeps the quality: sliding window with recompute. For each new token it rebuilds the keys and values of the last L tokens from scratch. That forward pass runs attention over L tokens, about L × L dot products per layer. StreamingLLM reuses its cache, so the new token needs about L.
How much faster is it? Call the per-token latency of the recompute baseline at cache size L tre(L), and StreamingLLM's ts(L).
speedup of L equals t-r-e of L, divided by t-s of L.
Time one token with each method at the same L. Divide the recompute time t-r-e by the streaming time t-s. Because one grows like L squared and the other like L, the ratio grows with L.
Llama-2-13B at L = 4,096: t-r-e = 2,355 ms and t-s = 106 ms, so the speedup is 2,355 / 106 = 22.2. At L = 256 it is 99 / 48 = 2.1 (Figure 10).
Bars are milliseconds per token from the paper. Pick a model, then a cache size, and read the speedup.
The paper's Figure 10: one NVIDIA A6000, both methods in Hugging Face Transformers. Memory is close for the two methods, e.g. 34 GB against 36 GB for Llama-2-13B at 4,096.
Read the credit carefully. The 22.2 is the whole StreamingLLM method against the recompute baseline. The speed comes from reusing a fixed cache; plain window attention reuses one too, at the same cost. The sinks are what make that fast path give the right answers.
Does it hold on a real task? The authors join all ARC question-answer pairs into one stream for Llama-2-Chat models and score each answer by exact match (Table 5, cache 1,024).
| Model, dataset | One question at a time | Dense | Window | StreamingLLM |
|---|---|---|---|---|
| Llama-2-7B-Chat, ARC-E | 71.25 | OOM | 3.58 | 71.34 |
| Llama-2-13B-Chat, ARC-C | 63.31 | OOM | 0.34 | 65.61 |
| Llama-2-70B-Chat, ARC-E | 91.29 | OOM | 0.12 | 91.37 |
Dense attention runs out of memory. Window attention gives random outputs. StreamingLLM matches answering one question at a time. On language modelling, perplexity stays stable over 4 million tokens for Llama-2, MPT, Falcon and Pythia models up to 70B (Figure 5).
Failure. A team benchmarks at L = 256, sees 2.1 times, and drops the idea. Measure: latency at the cache size you will deploy. Fix: time it there; the gain grows with L.
Chapter 9
Find the hard edge of the window, and see where the same sink shows up elsewhere
The paper is direct: StreamingLLM "does not extend the models' context window or enhance their long-term memory capabilities." An evicted token is gone. Ask at hour six what you said first, and the model cannot know.
The StreamEval benchmark shows the edge. The model reads numbered lines and gets a question every 10 lines. Each line is 23 tokens. In the paper's sweep, the question asks about a line a fixed distance back (Table 7, Llama-2-7B-32K-Instruct).
Pick a cache. Bars are accuracy at each distance between question and answer. The dashed line is the cache's edge.
The paper's Table 7: 100 samples of 100 queries each. Distances are lines × 23 tokens.
Inside the cache, accuracy holds; past it, accuracy is exactly 0. Two more limits:
The sink is not only an LLM habit. Vision Transformers dump attention on background patches, and Darcet et al. add learnable register tokens to take it. Unlike sinks, several registers keep helping. The authors read the shared pattern as a sign that softmax itself drives it.
Failure. Users ask a streaming assistant about the start of a long session and get confident wrong answers. Measure: a StreamEval-style probe at growing distances. Fix: retrieval or summaries on top, or a context-extended base model for a larger window; the paper pairs StreamingLLM with two 32K models.
Chapter 10
Keep the terms, the numbers, the code and the open questions in one place
A dense KV cache grows by B bytes per token without end. Window attention caps it but collapses when the first token leaves, because softmax had parked most of its weight there. StreamingLLM pins four sink tokens, rolls the rest, and numbers the cache by slot. It streams 4 million tokens with no fine-tuning, but it remembers only what is in the cache.
| Term | Meaning | Number to remember |
|---|---|---|
| KV cache | saved keys and values of past tokens | 512 KiB per token, Llama-2-7B |
| Window attention | keep the last L tokens | perplexity 5,158.07 (0 + 1024) |
| Attention sink | token that collects spare attention | often over half, most layers |
| Eviction jump | survivors grow by 1 / (1 − a-one) | a-one 0.9948: 192 times |
| StreamingLLM | sinks + rolling cache, cache positions | 5.40 (4 + 1020) |
| Sink count | initial tokens kept | 4 by default; Llama-2-7B 9.59 |
| Sink Token | learnable placeholder in pretraining | 18.01 with 1 kept |
| Speedup | vs sliding window with recompute | 22.2 times, Llama-2-13B, L 4,096 |
| Stable length | tested stream length | 4 million tokens |
| Memory edge | StreamEval past the cache | 0.00% accuracy |
pythonimport numpy as np def softmax(x): e = np.exp(x - np.max(x)); return e / e.sum() def softmax1(x): # Zero Sink: a phantom key with logit 0 m = max(0.0, np.max(x)); e = np.exp(x - m) return e / (np.exp(-m) + e.sum()) def streaming_keep(n_seen, n_sink=4, window=1020): # text positions held in the cache sinks = list(range(min(n_sink, n_seen))) recent = list(range(max(n_sink, n_seen - window), n_seen)) return sinks + recent # cache positions are 0 .. len-1 x = np.array([8, 2, 1, 0, 1.5]) print(softmax(x).round(4)) # [0.9948 0.0025 0.0009 0.0003 0.0015] print(softmax(x[1:]).round(4)) # [0.474 0.1744 0.0641 0.2875]: the sink evicted print(streaming_keep(12, 4, 6)) # [0, 1, 2, 3, 6, 7, 8, 9, 10, 11]
The authors say the models do not fully use the context in their cache, and call for work on that. StreamingLLM suits short-term memory, such as daily chat; it is not for long-document question answering or summaries. The sink-token test ran at 160M parameters only.
Credit: Session 8 of Georgia Tech CS 8803, LLM seminar. Paper: Guangxuan Xiao, Yuandong Tian, Beidi Chen, Song Han and Mike Lewis, Efficient Streaming Language Models with Attention Sinks (ICLR 2024, arXiv 2309.17453; MIT, Meta AI, Carnegie Mellon and NVIDIA). Code: mit-han-lab/streaming-llm. The toy traces and all made-up numbers are ours.
Teach it back: open Present or Teach and explain the 192-times jump to a friend. Then go back to the stream and predict, before you press Stream, which policy breaks and when.