Attention Sinks and StreamingLLM

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.

Stream a book through the cache

12,000

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

The Day-Long Chat

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.

Run a chat for a working day

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.

300

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.

PolicyWhat it keepsWork for T tokensBook perplexity
Dense attentionevery tokenT²5,641
Window attentionthe last LT × L5,158
Window with recomputerebuilds the last L for each tokenT × L²5.43
StreamingLLMthe first 4 and the last LT × L5.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.

  1. What the cache holds: bytes per token, derived.
  2. Window attention breaks: the collapse, and how to read perplexity. The hero's Window button.
  3. The sink: where the attention goes.
  4. Why softmax makes a sink: the arithmetic of eviction.
  5. The StreamingLLM recipe: sinks plus a rolling window. The hero's last button.
  6. How many sinks: one for some models, four for Llama-2.
  7. Train a sink in: SoftMax1 and the sink token.
  8. Speed and real tasks: 22.2 times faster than recompute.
  9. What it cannot remember: the hard edge of the window.
  10. Field guide: numbers, code, links and the credit.
Why can no GPU hold the dense KV cache of a chat that never ends?

Chapter 1

What the Cache Holds

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.

token arrives
its hidden state at this layer
↓ three projections
Q, K, V
Q is used once; K and V join the cache
↻ next token: its Q meets every cached K and V

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.

Say it aloud

B equals two, times n-L, times d-k-v, times b.

B
B the bytes of cache that one token adds, over all layers.
2
two one key and one value per token per layer.
nL
n-L the number of layers. Each layer keeps its own keys and values.
dkv
d-k-v numbers in one key: key heads times head size.
b
b bytes per number: 2 for 16-bit floats.
In plain words

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.

With numbers

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.

Price the cache

Pick a model and drag the token count. The bar is the cache; the marks are a 24 GiB and an 80 GiB card.

4,096

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.

Why does the model cache past keys and values but not past queries?

Chapter 2

Window Attention Breaks

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).

Find the step where it breaks

The trace is perplexity along a 20,000-token text, on a log scale. Move the cache size and watch where the jump lands.

1,024

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.

Say it aloud

P-P-L equals e to the power of: one over T, times the sum over t of ell-t.

PPL
P-P-L perplexity: about how many tokens the model hesitates between. Lower is better.
exp
e to the power of undoes the log, so the score is back in "number of choices".
1/T
one over T divide by the number of tokens scored, so the sum becomes an average.
Σt
the sum over t add one term for each token in the text.
ℓt
ell-t the loss on token t, in nats: minus the log of the probability of the true token.
In plain words

Score each token by its loss ell-t. Average the T losses. Raise e to that average. The result is PPL.

With numbers

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.

In Table 1, what separates perplexity 5,158 from perplexity 5.40?

Chapter 3

The Sink

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.

Scan the layers

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.

9

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 only5,158.07
4 + 1020, the real first tokens5.40
4 "\n" + 1020, four line breaks5.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.

The first four tokens are replaced with line breaks, and perplexity is 5.60 instead of 5.40. What does that show?

Chapter 4

Why Softmax Makes a Sink

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.

Say it aloud

a-i equals e to the x-i, divided by the sum over j from one to N of e to the x-j.

ai
a-i the attention weight on key i, between 0 and 1.
exi
e to the x-i the logit made positive. A logit 2 higher means about 7.4 times more weight.
Σj=1..N exj
the sum over j of e to the x-j the denominator Z: every key's term, added.
In plain words

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 numbers

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.

Say it aloud

a-prime-i over a-i equals one over, one minus a-one.

a′i / ai
a-prime-i over a-i how many times larger token i's weight becomes after the eviction.
1
one the whole attention budget.
1 −
one minus the share left once the sink's share is gone.
a1
a-one the sink's weight before eviction.
In plain words

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.

With numbers

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.

Evict the sink

The bars are the softmax of the logits printed under them. Raise the sink's logit, then evict it and watch the others grow.

8.0

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.

The sink held 99% of a head's attention. It is evicted. What happens to the other tokens' weights?

Chapter 5

The StreamingLLM Recipe

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.

Roll the cache

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.

9
3

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.

text position: 0 1 2 3 4 5 6 7 8 next: 9 cache position: 0 1 2 3 4 5 6 next: 7

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.

Why does StreamingLLM give each token its cache position rather than its text position?

Chapter 6

How Many Sinks

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).

Sweep the sink count

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.

stream: <s> P1 P1 P1 P1 <s> P2 P2 P2 P2 P2 <s> P3 P3 P3 P3 P3 P3 ... window 1: <s> P1 P1 P1 P1 <s> P2 P2 position 0 is <s>, by luck window 2: P2 P2 P2 <s> P3 P3 P3 P3 position 0 is an ordinary word

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.

Why does Llama-2-7B need four sink tokens when Falcon-7B needs one?

Chapter 7

Train a Sink In

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.

  1. Vanilla: ordinary softmax.
  2. Zero Sink: softmax with an extra 1 in the denominator, called SoftMax1.
  3. Sink Token: one learnable placeholder token at the start of every training sample.

SoftMax1 gives the head a way to attend to nothing. Use the same logits xi as in Chapter 4.

Say it aloud

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.

SoftMax1(x)i
SoftMax-one of x, at i the weight on key i. The weights may add up to less than 1.
exi
e to the x-i key i's logit, made positive, as before.
1
one a phantom key with logit 0, since e to the 0 is 1. Its key and value are all zeros.
Σj=1..N exj
the sum over j of e to the x-j the real keys' terms, as in softmax.
In plain words

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 numbers

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.

Give attention a way out

Four keys. Drag the best key's logit down until nothing matches. Blue is softmax; teal is SoftMax1; the grey slot is the phantom.

3.00

Made-up logits: the slider sets the best key; the other three are 0.

160M model0 + 10241 + 10232 + 10224 + 1020
Vanilla27.8718.4918.0518.05
Zero Sink29,21419.9018.2718.01
Sink Token1,23518.0118.0118.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.

Why does the Sink Token model need only one kept token, when Vanilla needs several?

Chapter 8

Speed and Real Tasks

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).

Say it aloud

speedup of L equals t-r-e of L, divided by t-s of L.

speedup(L)
speedup of L how many times faster StreamingLLM makes each token, at cache size L.
tre(L)
t-r-e of L milliseconds per token for the recompute baseline. It grows like L squared.
ts(L)
t-s of L milliseconds per token for StreamingLLM. It grows like L.
In plain words

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.

With numbers

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).

Time one token

Bars are milliseconds per token from the paper. Pick a model, then a cache size, and read the speedup.

4,096

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, datasetOne question at a timeDenseWindowStreamingLLM
Llama-2-7B-Chat, ARC-E71.25OOM3.5871.34
Llama-2-13B-Chat, ARC-C63.31OOM0.3465.61
Llama-2-70B-Chat, ARC-E91.29OOM0.1291.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.

Why does StreamingLLM's speedup over recompute grow with the cache size L?

Chapter 9

What It Cannot Remember

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).

Ask about the past

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.

A question asks about a line 4,600 tokens back. The cache is 4 + 4092. What does Table 7 report, and why?

Chapter 10

Field Guide

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.

TermMeaningNumber to remember
KV cachesaved keys and values of past tokens512 KiB per token, Llama-2-7B
Window attentionkeep the last L tokensperplexity 5,158.07 (0 + 1024)
Attention sinktoken that collects spare attentionoften over half, most layers
Eviction jumpsurvivors grow by 1 / (1 − a-one)a-one 0.9948: 192 times
StreamingLLMsinks + rolling cache, cache positions5.40 (4 + 1020)
Sink countinitial tokens kept4 by default; Llama-2-7B 9.59
Sink Tokenlearnable placeholder in pretraining18.01 with 1 kept
Speedupvs sliding window with recompute22.2 times, Llama-2-13B, L 4,096
Stable lengthtested stream length4 million tokens
Memory edgeStreamEval past the cache0.00% accuracy

Checklist

  1. Compute B for your model; multiply by tokens held and by open chats.
  2. Never evict the first tokens. Keep 4 unless you have swept your model.
  3. Cache keys before RoPE and rotate them by cache position at each step.
  4. Sweep the window size on your own traffic; bigger is not always better.
  5. If a task needs a document's start, keep more of the start, or truncate the middle instead.
  6. If you pretrain a model, put one sink token at the start of every sample.
  7. Add retrieval or summaries if users ask about the distant past.
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]

What the paper leaves open

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.

Keep going

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.

The takeaway. Softmax must spend all of its attention, so the model parks the spare on the first tokens. Keep those few tokens and a fixed cache streams forever. Lose them and every head's weights inflate at once.

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.

CS 8803 LLM Seminar, Session 08: Attention Sinks and StreamingLLM
Read the paper · Back to Gleams