Paper notes

StreamingLLM: Keep the First Few Tokens in the KV Cache and Sliding Windows Stop Breaking

StreamingLLM (ICLR 2024) finds that language models dump much of their attention on the first few tokens, the attention sinks; evict them from a sliding-window KV cache and perplexity explodes. Keeping 4 initial tokens fixes it with no fine-tuning, but it does not extend the context.

Published Updated 40 min read

On this page
  1. Why this paper is worth reading
  2. Background: two problems with the KV cache
  3. The core idea: attention sinks
  4. Method: the cache is sinks plus a rolling window
  5. Experiments and conclusions
  6. Hands-on check: window collapse, sinks, the recompute ceiling and memory distance
  7. The implementation is right: it matches dense attention and the token-by-token official algorithm
  8. Perplexity: window attention collapses after position 1024, StreamingLLM nearly coincides with dense
  9. Zooming in on the eviction
  10. How many initial tokens to keep? Comparison with Table 2
  11. Cache size: bigger is better here, unlike Table 6
  12. What the sink needs: a position or a content
  13. Where attention goes: the sink absorbs weight but writes almost nothing
  14. Beyond the native window: 40,960 tokens
  15. How far back can it remember: a mini StreamEval
  16. The arithmetic: cache memory and the cost of re-computation
  17. Limitations and follow-ups
  18. What to take from this paper
  19. Further reading
  20. FAQ

StreamingLLM (Efficient Streaming Language Models with Attention Sinks, from MIT, Meta AI, Carnegie Mellon University and NVIDIA) is a KV-cache policy that needs no fine-tuning: the cache always keeps the first 4 tokens (the paper calls them “attention sinks”), adds a sliding window of the most recent tokens, and evicts everything else. It starts from one very specific failure: if you treat the KV cache as a sliding window, perplexity explodes the moment the cache fills and the first tokens are evicted (Figure 1 of the paper: Llama-2-13B on a 65K-token text scores 5158 with window attention; adding 4 initial tokens back gives 5.40, on par with the 5.43 of recomputing the window at every step).

Note what it solves: “keep reading forever”, not “remember everything”. Content outside the window really is invisible, and the authors say plainly that StreamingLLM does not extend the context window (Appendix A) and is a poor fit for long-document QA. Separating that from the word “infinite” in the title is the most important step in reading this paper.

The paper appeared on arXiv on 29 September 2023; this article follows v4 (7 April 2024, the ICLR 2024 version). I reproduced its main mechanism on Qwen2.5-0.5B: first checking that my implementation is equivalent to the official algorithm written token by token, then looking at perplexity, the number of sinks, where attention goes, and how far back the model can actually remember. Some results differ from the paper (this model needs only one sink, and window attention’s perplexity partly recovers after the initial spike); all of that is in the hands-on section. External information (model card, paper pages) was checked in November 2026.

Why this paper is worth reading

  • It explains a failure everyone runs into. Treating the KV cache as a sliding window is the most natural thing to do, and it is also the first thing to break. The paper traces the cause to softmax normalization and the “sink”, and the fix is one sentence: do not evict the first few tokens.
  • Sinks keep coming back. Appendix H of the paper shows that BERT’s [SEP] plays the same role, and Appendix B treats the concurrent Vision Transformer “registers” (Darcet et al., 2023) as the same kind of phenomenon. OpenAI’s gpt-oss model card (August 2025) describes a learned bias in the softmax denominator of every attention head, “similar to off-by-one attention and attention sinks”, and cites this paper in its references, which is an example of the paper’s SoftMax1 idea (Section 3.3) ending up in a new model.
  • It reached inference frameworks quickly. The paper’s impact statement says StreamingLLM has been adopted by serving solutions including NVIDIA TensorRT-LLM, Intel Extension for Transformers, Hugging Face Transformers and MLC LLM; that is the authors’ own statement and I did not check each framework’s implementation.
  • It draws the line between streaming and long context. StreamEval and LongBench (Appendices C and D) quantify it: streaming guarantees stability, not memory.
  • The mechanism is small, which suits hands-on work. The core logic is a few dozen lines; a 0.5B model on a laptop shows window attention collapsing and lets you measure how much attention the sink soaks up.

Background: two problems with the KV cache

Autoregressive decoding caches the Key and Value of every earlier token (see KV Cache). In streaming settings, such as an assistant that has to work through days of conversation, that causes two problems:

  1. Memory and latency grow linearly with length. The KV cache per token is layers × KV heads × head dimension × 2 (K and V) × 2 bytes (bf16). Llama-2-7B has 32 layers, 32 KV heads and head dimension 128, so each token takes 524,288 bytes (512 KiB), and 4 million tokens come to about 1,953 GiB, which does not fit anywhere.
  2. Models fail beyond their training length. A model has only seen sequences up to its pre-training window (4K for Llama-2), and position encodings extrapolate worse on longer ones. Methods that extend the window (see the YaRN explainer) only raise the ceiling; they do not remove it.

The obvious fix is to keep only the last LL tokens’ KV, known as window attention (the Longformer-style approach). Figure 1 of the paper compares four schemes, with perplexity measured on Llama-2-13B over the first book of PG-19 (65K tokens):

SchemeWhat it doesCostPerplexity
Dense attentionCache all KVTotal time O(T2)O(T^2), cache keeps growing5641
Window attentionCache only the last LL KVO(TL)O(TL)5158
Sliding window with re-computationRebuild the KV from the last LL tokens for every new tokenO(TL2)O(TL^2)5.43
StreamingLLM4 initial tokens plus the last L−4L-4 KVO(TL)O(TL)5.40

The third row is the quality ceiling but slow; the second row is fast but broken. StreamingLLM wants the quality of the third row at the speed of the second.

The core idea: attention sinks

The first observation is when the collapse happens. Figure 3 of the paper plots perplexity on 20K-token texts: window attention blows up exactly when the text length passes the cache size, which is the moment the first tokens are evicted. The authors conclude that these tokens matter for stability no matter how far they are from the position being predicted.

The second observation is where attention goes. Figure 2 plots Llama-2-7B’s average attention over 256 sentences of 16 tokens: apart from the bottom two layers, which attend locally, almost every head in every other layer puts a lot of weight on the first token. In the quantitative analysis of Appendix F, the 4096th token’s attention weight on the first token is often above one half in every layer except the bottom two. That is the “attention sink”.

The explanation comes from softmax. The attention weights are

αj=esj∑iesi,sj=q⋅kjd,\alpha_j = \frac{e^{s_j}}{\sum_i e^{s_i}}, \qquad s_j = \frac{q\cdot k_j}{\sqrt{d}},

and they must sum to 1. If the current query has no strong match anywhere in the context, the weight still has to go somewhere. The first token is visible to every later token, while any other token is visible only to the tokens after it, so the first tokens are the easiest to train into this “outlet”. If the sink holds weight aa and is evicted, the remaining weights are renormalized and all scale up by 1/(1−a)1/(1-a):

αj′=αj1−a,j≥1.\alpha'_j = \frac{\alpha_j}{1-a}, \qquad j \ge 1 .

With a=0.5a=0.5 every remaining weight doubles. If the sink’s Value vector was close to zero (it is only an outlet and contributes no content), the half of the weight it used to absorb now has to be spread over other tokens, every head’s output is rewritten, and the next layer sees a distribution it never saw in training.

The sink depends on position, not content. In Table 1 of the paper the first 4 tokens are replaced with line breaks \n: 4 line breaks plus the last 1020 tokens give perplexity 5.60, close to 5.40 with the 4 real initial tokens, while window attention gives 5158.07. The authors conclude that “absolute position rather than semantics” matters. Read that with care: it shows the content does not matter, but it does not separate “position” from “being first and visible to every later token”.

Method: the cache is sinks plus a rolling window

The StreamingLLM cache has two parts:

Which keys each query can see: dense, window and StreamingLLM Three 12 by 12 causal mask matrices, rows are query positions and columns are key positions. Dense attention: every query sees all earlier tokens and the cache keeps growing. Window attention: every query sees only the last 6 tokens, and the model collapses once the first tokens are evicted. StreamingLLM: every query sees the first 2 tokens as attention sinks plus the last 4 tokens, 6 in total. The diagram is scaled down; the paper keeps 4 sinks. Dense attention caches every KV, grows with length perplexity 5641 (paper Fig. 1) Window attention caches only the last 6 KV perplexity 5158 (paper Fig. 1) StreamingLLM 2 sinks + the last 4 KV perplexity 5.40 (paper Fig. 1) sink (initial tokens) recent tokens evicted the query itself Rows are query positions, columns are key positions; grey cells are evicted past tokens, blank cells are future tokens.
Figure: which keys each query can see under three cache policies (the picture is scaled down to 12 tokens and a cache of 6; StreamingLLM draws 2 sinks, while the paper keeps 4). The perplexities under each panel come from Figure 1 of the paper: Llama-2-13B on the first PG-19 book (65K tokens).
  1. Sinks: the KV of the first SS tokens of the sequence, with S=4S=4 in the paper, never evicted.
  2. Rolling window: the KV of the last L−SL-S tokens; each decoding step evicts the oldest one.

Positions are assigned inside the cache, not in the original text. The paper’s example: the cache holds original tokens 0, 1, 2, 3, 6, 7, 8 and is decoding token 9; they get positions 0 to 7 rather than the original 0, 1, 2, 3, 6, 7, 8, 9. For RoPE, the cache stores Keys from before the rotation and rotates them at every step according to their position in the cache; for ALiBi, it switches to contiguous linear biases instead of “jumping” ones. The paper says this step is key to StreamingLLM working beyond the pre-training window. The design applies to any autoregressive model with a relative position encoding (RoPE, ALiBi) and needs no fine-tuning.

Sections 3.3 and 4.2: put a sink into pre-training. If the model uses “whatever token happens to come first” as its sink, why not provide a dedicated one? The paper trains three models of 160 million parameters with the Pythia-160M recipe (8 A6000 GPUs, the deduplicated Pile, batch size reduced to 256, 143,000 steps):

ModelWhat it does0+10241+10232+10224+1020
VanillaStandard softmax27.8718.4918.0518.05
Zero SinkSoftMax1, equivalent to a leading token whose key and value are all zero2921419.9018.2718.01
Learnable SinkA learnable token at the start of every training sample123518.0118.0118.02

(Table 3, perplexity on the first sample; “x+y” means x initial tokens plus y recent tokens in the cache.) SoftMax1 is SoftMax1(x)i=exi/(1+∑jexj)\mathrm{SoftMax}_1(x)_i = e^{x_i}/(1+\sum_j e^{x_j}); the extra 1 in the denominator acts like an “empty token” with score 0. How to read the table: Zero Sink only eases the problem and still needs other initial tokens; Learnable Sink needs just that one token, and without it perplexity jumps to 1235, which shows the model really uses it as the sink. The extra token does not hurt convergence: on 7 zero-shot benchmarks the two models differ by at most 1 point (Table 4), and a second sink token brings no further benefit (Appendix I).

Experiments and conclusions

The paper’s conclusions, the evidence, and what to watch for:

ConclusionEvidenceWhat to watch for
Window attention collapses when the first tokens are evicted; keeping 4 initial tokens restores itFigures 1 and 3, Table 1What is restored is language-modeling perplexity, not use of long-range information
Llama-2-7/13/70B, Falcon-7/40B, Pythia-2.8/6.9/12B and MPT-7/30B stay stable beyond 4 million tokensFigure 5, concatenated PG-19 test set (100 books)Cache of 2048 for Llama-2 and 1024 for the others; perplexity wobbles at book boundaries
Perplexity is almost the same as the per-step-recompute ceiling, with up to 22.2x lower per-token latencyFigures 3 and 10, A6000, Hugging Face TransformersThe opponent is the recompute baseline in the same implementation; memory is similar to that baseline
4 initial tokens are enoughTable 2Only the Llama-2-7B row supports “1 is not enough”; see the hands-on section
A bigger cache is not always betterTable 6The authors read it as the model not fully using the context
Streaming QA matches the recompute baselineTable 5, ARC, Llama-2-Chat 7/13/70BDense attention runs out of memory; window attention is almost always wrong (3.58 and 1.39 at 7B)
With a sink token in pre-training, keeping only it is enoughTables 3 and 4Only tried at 160 million parameters

Table 5 numbers: on Llama-2-7B-Chat, the one-shot, question-by-question baseline scores 71.25 on ARC-Easy and 53.16 on ARC-Challenge, StreamingLLM scores 71.34 and 55.03, window attention 3.58 and 1.39; at 70B the three are 91.29 and 78.50, 91.37 and 80.20, and 0.12 and 0.32. StreamEval is the paper’s own benchmark (Figure 8): it asks a question after every 10 lines of new information and the answer is always 20 lines back, because in real streaming settings questions mostly concern recent information; in Figure 9, StreamingLLM keeps reasonable accuracy as the input approaches 120K tokens, while dense and window attention fail at the pre-training length and at the cache size respectively.

Hands-on check: window collapse, sinks, the recompute ceiling and memory distance

StreamingLLM’s mechanism does not need a large model, so it can be checked directly on a small one. The script below has 11 parts on Qwen2.5-0.5B, numbered 0 to 10 as in the == N. lines of the output: 0 checks that my implementation is equivalent to dense attention and to the official algorithm written token by token; 1 plots the perplexity of window attention, StreamingLLM and dense attention by position; 2 compares with the paper’s “ceiling”, sliding window with re-computation; 3 zooms in on the moment token 0 is evicted; 4 varies the number of initial tokens and compares with Table 2 of the paper; 5 varies the cache size and compares with Table 6; 6 asks whether the sink needs a position or a content; 7 measures where attention goes and how small the sink’s Value is; 8 stretches the text to 40,960 tokens, beyond the model’s native 32,768 window; 9 builds a mini StreamEval to see how far back the model can remember; 10 does the arithmetic of cache memory and re-computation cost.

Environment: Apple M2 Max (MPS backend, CPU for part 8), Python 3.14.3, PyTorch 2.10.0, transformers 5.3.0. The model is Qwen2.5-0.5B (Apache-2.0, 24 layers, 14 query heads, 2 KV heads, native context 32,768), and the mini StreamEval in part 9 uses Qwen2.5-1.5B-Instruct (Apache-2.0). The text is a passage of Middlemarch from Project Gutenberg (public domain), 12,288 tokens, with cache C=1024C=1024 (the initial tokens plus the most recent ones, 1024 in total, not counting the token being predicted). Everything is deterministic except part 9, which uses one fixed random seed (7); on another machine the last digit of a few numbers may differ. Apart from the re-computation baseline in part 2 and a few cross-checks that call the model’s own forward pass, the attention is computed by hand, layer by layer, in blocks of 256 tokens, and each policy is a boolean mask: query tt may see key jj if and only if j≤tj\le t and (t≤Ct\le C, or j<Sj<S, or j≥t−(C−S)j\ge t-(C-S)). Positions are assigned inside the cache: the query gets position min⁡(t,C)\min(t, C), and only the sink columns’ scores are affected (the keys in the recent window keep the same relative distance to the query), so the code only recomputes those columns. A full run takes about 20 minutes, most of it in the CPU dense attention of part 8 and the re-computation baseline of part 2.

# StreamingLLM on Qwen2.5-0.5B: window attention, attention sinks, recompute
import math
import os
import random
import urllib.request

import torch
import torch.nn.functional as F
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer
from transformers.utils import logging as hf_logging

hf_logging.set_verbosity_error()  # no loading progress or length warnings
hf_logging.disable_progress_bar()
dev = "mps"
NAME = "Qwen/Qwen2.5-0.5B"  # Apache-2.0, native context 32,768
tok = AutoTokenizer.from_pretrained(NAME)
model = AutoModelForCausalLM.from_pretrained(NAME, dtype=torch.float32)
model = model.to(dev).eval()
cfg, M = model.config, model.model
H, HKV = cfg.num_attention_heads, cfg.num_key_value_heads
D = cfg.hidden_size // H
G = H // HKV

# Long text: Middlemarch (Project Gutenberg), from the middle, 12,288 tokens
URL = "https://www.gutenberg.org/cache/epub/145/pg145.txt"
PATH = "/tmp/pg145.txt"
if not os.path.exists(PATH):
    urllib.request.urlretrieve(URL, PATH)
raw = open(PATH, encoding="utf-8").read()
a = raw.index("*** START OF THE PROJECT GUTENBERG EBOOK")
b = raw.index("*** END OF THE PROJECT GUTENBERG EBOOK")
text = raw[a:b].split("\n", 1)[1][300000:]
text = text[text.index("\n\n") + 2:]
ids_all = tok(text, add_special_tokens=False, return_tensors="pt").input_ids[0]
N, C = 12288, 1024  # stream length; cache size (sinks + most recent tokens)
ids = ids_all[:N].to(dev)


def rope(x, cos, sin):
    h = x.shape[-1] // 2
    return x * cos + torch.cat((-x[..., h:], x[..., :h]), -1) * sin


@torch.no_grad()
def hidden(ids, S, C, blk=256, shift=True, probe=None):
    """Each query sees only the cache: S initial tokens + C-S recent tokens
    + itself. C=None is dense attention. shift: sinks use in-cache positions."""
    n = ids.numel()
    h = M.embed_tokens(ids)[None]
    pos = torch.arange(n, device=dev)
    cos, sin = [x[0] for x in M.rotary_emb(h, pos[None])]
    if C is not None:  # query position in the cache: min(t, C)
        cq, sq = [x[0] for x in M.rotary_emb(h, pos.clamp(max=C)[None])]
    R = None if C is None else C - S
    stats = []
    for L in M.layers:
        at = L.self_attn
        x = L.input_layernorm(h)
        q = at.q_proj(x)[0].view(n, H, D).transpose(0, 1)
        k = at.k_proj(x)[0].view(n, HKV, D).transpose(0, 1)
        v = at.v_proj(x)[0].view(n, HKV, D).transpose(0, 1)
        qr, kr = rope(q, cos, sin), rope(k, cos, sin)
        qa = rope(q, cq, sq) if C is not None and S and shift else None
        out, acc = torch.empty_like(q), torch.zeros(4, device=dev)
        for a0 in range(0, n, blk):
            a1 = min(n, a0 + blk)
            t = pos[a0:a1]
            lo = 0 if C is None else max(0, a0 - R)
            keys = pos[lo:a1]
            if S and lo > 0:  # initial tokens before the block
                keys = torch.cat([pos[:min(S, lo)], keys])
            ok = keys[None] <= t[:, None]
            if C is not None:
                ok &= ((t[:, None] <= C) | (keys[None] < S)
                       | (keys[None] >= t[:, None] - R))
            kb = kr[:, keys][:, None].transpose(-1, -2)
            s = qr[:, a0:a1].reshape(HKV, G, -1, D) @ kb
            if qa is not None:  # sink columns: in-cache positions
                sc = keys < S
                qs = qa[:, a0:a1].reshape(HKV, G, -1, D)
                s[..., sc] = qs @ kr[:, keys[sc]][:, None].transpose(-1, -2)
            w = torch.softmax((s * at.scaling).masked_fill(~ok, -math.inf), -1)
            if probe is not None:  # oldest 1, oldest 4, newest 4
                m = t >= probe
                up = ok.cumsum(-1)
                down = ok.flip(-1).cumsum(-1).flip(-1)
                for i, sel in enumerate([ok & (up == 1), ok & (up <= 4),
                                         ok & (down <= 4)]):
                    acc[i] += (w * sel).sum(-1)[..., m].sum()
                acc[3] += H * m.sum()
            o = w @ v[:, keys][:, None]
            out[:, a0:a1] = o.reshape(H, a1 - a0, D)
        h = h + at.o_proj(out.transpose(0, 1).reshape(1, n, H * D))
        h = h + L.mlp(L.post_attention_layernorm(h))
        stats.append(acc[:3] / acc[3].clamp(min=1))
    return M.norm(h)[0], torch.stack(stats)


@torch.no_grad()
def nll(ids, S, C, **kw):
    """Per-token NLL (nats): r[t] = -log p(ids[t+1] | cache)."""
    hs = hidden(ids, S, C, **kw)[0]
    out = []
    for i in range(0, ids.numel() - 1, 512):
        tgt = ids[i + 1:i + 513]
        lg = model.lm_head(hs[i:i + 512])[:tgt.numel()]
        out.append(F.cross_entropy(lg, tgt, reduction="none"))
    return torch.cat(out)


def ppl(r, lo=0, hi=None):
    return math.exp(r[lo:hi].mean().item())


# ===== 0. First prove the implementation is right
print("== 0. checks of the implementation")
x = ids[:300]
with torch.no_grad():
    lg = model(x[None]).logits[0, :-1]
ref = F.cross_entropy(lg, x[1:], reduction="none")
d0 = (nll(x, None, None) - ref).abs().max()
d1 = (nll(x, 4, 400) - ref).abs().max()
print(f"dense vs HF forward: max |dNLL| = {d0:.1e}")
print(f"C >= n vs HF forward: max |dNLL| = {d1:.1e}")


# Zero Sink of the paper: SoftMax1 = a leading token with all-zero key/value
torch.manual_seed(0)
z = torch.randn(10)
sm1 = torch.exp(z) / (1 + torch.exp(z).sum())
zero = torch.softmax(torch.cat([torch.zeros(1), z]), 0)[1:]
dz = (sm1 - zero).abs().max()
print(f"SoftMax1 vs softmax with a zero logit: max diff {dz:.1e}")


@torch.no_grad()
def naive(ids, S, C):
    """The official algorithm token by token: cache unrotated K/V, evict after
    every step, rotate queries and keys by their in-cache positions."""
    cache, out = [None] * len(M.layers), []
    for t in range(ids.numel() - 1):
        h = M.embed_tokens(ids[t:t + 1])[None]
        for i, L in enumerate(M.layers):
            at = L.self_attn
            x = L.input_layernorm(h)
            q = at.q_proj(x)[0].view(1, H, D).transpose(0, 1)
            k = at.k_proj(x)[0].view(1, HKV, D).transpose(0, 1)
            v = at.v_proj(x)[0].view(1, HKV, D).transpose(0, 1)
            if cache[i] is not None:
                k = torch.cat([cache[i][0], k], 1)
                v = torch.cat([cache[i][1], v], 1)
            cache[i] = (k, v)
            m = k.shape[1]
            p = torch.arange(m, device=dev)
            c_, s_ = [z[0] for z in M.rotary_emb(h, p[None])]
            kk = rope(k, c_, s_).repeat_interleave(G, 0)
            vv = v.repeat_interleave(G, 0)
            s = (rope(q, c_[-1:], s_[-1:]) @ kk.transpose(-1, -2)) * at.scaling
            o = torch.softmax(s, -1) @ vv
            h = h + at.o_proj(o.transpose(0, 1).reshape(1, 1, H * D))
            h = h + L.mlp(L.post_attention_layernorm(h))
        if cache[0][0].shape[1] > C:
            cache = [(torch.cat([k[:, :S], k[:, k.shape[1] - (C - S):]], 1),
                      torch.cat([v[:, :S], v[:, v.shape[1] - (C - S):]], 1))
                     for k, v in cache]
        lg = model.lm_head(M.norm(h))[0]
        out.append(F.cross_entropy(lg, ids[t + 1:t + 2], reduction="none"))
    return torch.cat(out)


x = ids[:260]
for S in (0, 4):
    d = (naive(x, S, 64) - nll(x, S, 64, blk=64)).abs().max()
    print(f"token-by-token cache (S={S}, C=64) vs mask version: {d:.1e}")


# ===== 1. Perplexity by position: dense, window, StreamingLLM
r_dense = nll(ids, None, None)
r_win = nll(ids, 0, C)
r_str = nll(ids, 4, C)
print(f"== 1. perplexity by position (n={N}, cache={C})")
print("positions      dense   window   stream")
for lo in range(0, N - 1, 1024):
    hi = min(lo + 1024, N - 1)
    print(f"{lo:5d}-{hi - 1:5d}  {ppl(r_dense, lo, hi):7.1f}  "
          f"{ppl(r_win, lo, hi):7.1f}  {ppl(r_str, lo, hi):7.1f}")
print("all positions t>=2048: dense {:.2f}  window {:.2f}  stream {:.2f}"
      .format(ppl(r_dense, 2048), ppl(r_win, 2048), ppl(r_str, 2048)))
dd = (r_str - r_dense)[2048:]
print(f"stream - dense: {dd.mean():.3f} nats/token "
      f"(standard error {dd.std() / dd.numel() ** 0.5:.3f})")


# ===== 2. The paper's upper bound: sliding window with re-computation
@torch.no_grad()
def recompute(ids, C, stride=16, bs=16):
    """Every `stride` positions, recompute the last C+1 tokens from scratch."""
    ts = list(range(C, ids.numel() - 1, stride))
    out = []
    for i in range(0, len(ts), bs):
        tt = ts[i:i + bs]
        x = torch.stack([ids[t - C:t + 1] for t in tt])
        lg = model(x, logits_to_keep=1).logits[:, -1]
        out.append(F.cross_entropy(lg, ids[[t + 1 for t in tt]],
                                   reduction="none"))
    return torch.tensor(ts), torch.cat(out)


ts, r_rec = recompute(ids, C)
keep = ts >= 2048
sel, r_rec = ts[keep].to(dev), r_rec[keep.to(dev)]
print("== 2. sliding window with re-computation (every 16th position, t>=2048)")
print("dense {:.2f}  window {:.2f}  stream {:.2f}  recompute {:.2f}".format(
    ppl(r_dense[sel]), ppl(r_win[sel]), ppl(r_str[sel]), ppl(r_rec)))
dd = r_str[sel] - r_rec
print(f"stream - recompute: {dd.mean():.3f} nats/token "
      f"(standard error {dd.std() / dd.numel() ** 0.5:.3f}, n={dd.numel()})")

# ===== 3. Zoom in on the moment of eviction
d = (r_win - r_dense).abs()
t0 = int((d > 1e-3).nonzero()[0])
print(f"== 3. first position where window differs from dense: t={t0} "
      f"(cache {C}: token 0 evicted)")
print("t range        dense   window   stream   (mean NLL, nats)")
edges = [992, 1025, 1029, 1033, 1041, 1057, 1089, 1153, 1281, 1537, 2048]
for lo, hi in zip(edges[:-1], edges[1:]):
    print(f"{lo:5d}-{hi - 1:5d}  {r_dense[lo:hi].mean():7.2f}  "
          f"{r_win[lo:hi].mean():7.2f}  {r_str[lo:hi].mean():7.2f}")

# ===== 4. How many initial tokens to keep (paper Table 2)
PAPER_T2 = {  # perplexities of paper Table 2; cache size in brackets
    "Falcon-7B (2048)": [17.90, 12.12, 12.12, 12.12, 12.12],
    "MPT-7B (2048)": [460.29, 14.99, 15.00, 14.99, 14.98],
    "Pythia-12B (2048)": [21.62, 11.95, 12.09, 12.09, 12.02],
    "Llama-2-7B (4096)": [3359.95, 11.88, 10.51, 9.59, 9.54],
}
SINKS = [0, 1, 2, 4, 8]
mine = [ppl(nll(ids, S, C), 2048) for S in SINKS]
print("== 4. number of initial tokens kept (perplexity)")
print("initial tokens kept          " + "".join(f"{s:9d}" for s in SINKS))
for name, v in PAPER_T2.items():
    print(f"paper {name:22s}" + "".join(f"{x:9.2f}" for x in v))
print(f"here  Qwen2.5-0.5B ({C})".ljust(29)
      + "".join(f"{x:9.2f}" for x in mine))
print("change from 1 to 4 initial tokens:")
for name, v in {**PAPER_T2, f"Qwen2.5-0.5B ({C})": mine}.items():
    ch = round((v[3] / v[1] - 1) * 100, 1) + 0.0  # + 0.0 turns -0.0 into 0.0
    print(f"  {name:20s}{ch:+7.1f}%")

# ===== 5. Cache size (paper Table 6)
# all from t=8192 on, past the transient right after the eviction
print("== 5. cache size (perplexity, positions t>=8192)")
print("cache   window(0+c)   stream(4+c-4)")
for c in [128, 256, 512, 1024, 2048, 4096]:
    print(f"{c:5d}  {ppl(nll(ids, 0, c), 8192):11.2f}  "
          f"{ppl(nll(ids, 4, c), 8192):13.2f}")
print(f"dense  {ppl(r_dense, 8192):11.2f}")

# ===== 6. What the sink tokens need: position or content
r_ns = nll(ids, 4, C, shift=False)
ids_nl = ids.clone()
ids_nl[:4] = tok("\n", add_special_tokens=False).input_ids[0]
r_nl = nll(ids_nl, 4, C)
print("== 6. what the sink tokens need (perplexity, positions t>=2048)")
print(f"4+{C - 4}, positions inside the cache:   {ppl(r_str, 2048):.2f}")
print(f"4+{C - 4}, original text positions:      {ppl(r_ns, 2048):.2f}")
print(f"4+{C - 4}, first 4 tokens -> newline:    {ppl(r_nl, 2048):.2f}")

# ===== 7. Where the attention goes
st = {k: hidden(ids, S_, C_, probe=2048)[1]
      for k, S_, C_ in [("dense", None, None), ("window", 0, C),
                        ("stream", 4, C)]}
print("== 7. attention mass (mean over heads and queries t>=2048): oldest "
      "entry, oldest 4, newest 4")
print("layer  dense:old  new4  window:old  new4  stream:old  old4  new4")
for l in range(len(M.layers)):
    d, w, s_ = st["dense"][l], st["window"][l], st["stream"][l]
    print(f"{l:5d}  {d[0]:9.3f} {d[2]:5.3f}  {w[0]:10.3f} {w[2]:5.3f}  "
          f"{s_[0]:10.3f} {s_[1]:5.3f} {s_[2]:5.3f}")
m = {k: v.mean(0) for k, v in st.items()}
print(f" mean  {m['dense'][0]:9.3f} {m['dense'][2]:5.3f}  "
      f"{m['window'][0]:10.3f} {m['window'][2]:5.3f}  "
      f"{m['stream'][0]:10.3f} {m['stream'][1]:5.3f} {m['stream'][2]:5.3f}")
big = int((st["dense"][:, 0] > 0.3).sum())
uni = (1 / (torch.arange(2048, N) + 1.0)).mean()
print(f"layers where dense attention puts >30% on token 0: {big} of "
      f"{len(M.layers)}; a uniform share would be {uni:.5f}")


@torch.no_grad()
def v_ratio(ids):
    """Value norm of token 0 / mean over the other tokens, per layer."""
    out, hooks = [], []
    for L in M.layers:
        hooks.append(L.self_attn.v_proj.register_forward_hook(
            lambda m, i, o: out.append(o[0].view(-1, HKV, D).norm(dim=-1))))
    model(ids[None])
    for h in hooks:
        h.remove()
    return torch.stack([v[0].mean() / v[1:].mean() for v in out])


vr = v_ratio(ids[:2048])
print("value norm of token 0 / mean over the other tokens:")
for lo in (0, 12):
    row = " ".join(f"{x:.2f}" for x in vr[lo:lo + 12].tolist())
    print(f"layers {lo:2d}-{lo + 11}: {row}")
sink = st["dense"][:, 0] > 0.3
print(f"the {int(sink.sum())} layers with a sink: {vr[sink].mean():.2f}; "
      f"the other {int((~sink).sum())} layers: {vr[~sink].mean():.2f}")

# ===== 8. Beyond the native window: 40,960 tokens
# The native window of Qwen2.5 is 32,768. On MPS, attention over more than
# 32,768 keys returns wrong numbers (first NaN, then plausible but bad values
# with smaller blocks), so this part runs on the CPU
dev, model = "cpu", model.to("cpu")
N2 = 40960
ids2 = ids_all[:N2]
r2 = {"dense": nll(ids2, None, None),
      "stream": nll(ids2, 4, C),
      "orig-pos": nll(ids2, 4, C, shift=False)}
dev, model = "mps", model.to("mps")
print(f"== 8. beyond the native window (n={N2}, native window 32,768)")
print("positions      dense   stream  orig-pos")
for lo in range(0, N2 - 1, 4096):
    hi = min(lo + 4096, N2 - 1)
    print(f"{lo:5d}-{hi - 1:5d}  {ppl(r2['dense'], lo, hi):7.1f}  "
          f"{ppl(r2['stream'], lo, hi):7.1f}  "
          f"{ppl(r2['orig-pos'], lo, hi):8.1f}")
for k, r in r2.items():
    print(f"{k:8s} t<32768: {ppl(r, 0, 32768):6.2f}   "
          f"t>=32768: {ppl(r, 32768):6.2f}")

# ===== 9. How far back can it remember: a mini StreamEval
# 0.5B dense attention mostly fails beyond ~10 lines; use the 1.5B Instruct
NAME = "Qwen/Qwen2.5-1.5B-Instruct"  # Apache-2.0
tok = AutoTokenizer.from_pretrained(NAME)
model = AutoModelForCausalLM.from_pretrained(NAME, dtype=torch.float32)
model = model.to(dev).eval()
cfg, M = model.config, model.model
H, HKV = cfg.num_attention_heads, cfg.num_key_value_heads
D = cfg.hidden_size // H
G = H // HKV
rng = random.Random(7)  # independent seed for the numbers
LINES, DIST = 900, [4, 12, 24, 36, 60, 100]
nums = [rng.randrange(10000, 100000) for _ in range(LINES)]


def enc(s):
    return tok(s, add_special_tokens=False).input_ids


stream, tasks, where = [], [], []
for i in range(LINES):
    head = f"The REGISTER_CONTENT in line {i:04d} is <"
    where.append(len(stream) + len(enc(head)))
    stream += enc(f"{head}{nums[i]}>\n")
    if i >= 120 and i % 5 == 4:  # query every 5 lines, about the line DIST back
        d = DIST[(i // 5) % len(DIST)]
        stream += enc(f"Query: The REGISTER_CONTENT in line {i - d:04d} is <")
        tasks.append((len(stream), d, i - d))
        stream += enc(f"{nums[i - d]}>\n")
sid = torch.tensor(stream, device=dev)
print(f"== 9. mini StreamEval: {len(stream)} tokens, {len(tasks)} queries, "
      f"{len(stream) / (LINES + len(tasks)):.1f} tokens per line")
hit = {}
for name, S_, C_ in [("dense", None, None), ("window", 0, C), ("stream", 4, C)]:
    hs = hidden(sid, S_, C_)[0]
    for p, d, j in tasks:
        gold = enc(str(nums[j]))
        pred = model.lm_head(hs[p - 1:p + 4]).argmax(-1).tolist()
        hit.setdefault((name, d), []).append(pred == gold)
print("distance back (mean tokens)     dense   window   stream  (5 digits)")
for d in DIST:
    dist = [p - where[j] for p, dd, j in tasks if dd == d]
    row = [sum(hit[(n, d)]) for n in ("dense", "window", "stream")]
    k = len(hit[("dense", d)])
    print(f"{d:6d} ({d:3d} lines, {sum(dist) / len(dist):6.0f} tokens)  "
          + "  ".join(f"{x:3d}/{k}" for x in row))


# ===== 10. Arithmetic: cache memory and the cost of re-computation
def kv_bytes(layers, kv_heads, head_dim):
    return 2 * layers * kv_heads * head_dim * 2  # K and V, bf16, per token


q5 = AutoConfig.from_pretrained("Qwen/Qwen2.5-0.5B")
per = {"Qwen2.5-0.5B": kv_bytes(q5.num_hidden_layers, q5.num_key_value_heads,
                                q5.hidden_size // q5.num_attention_heads),
       "Llama-2-7B": kv_bytes(32, 32, 128)}  # 32 layers, 32 KV heads
print("== 10. arithmetic")
for k, b in per.items():
    print(f"{k:13s} KV per token {b:7,d} B, 4M tokens dense: "
          f"{b * 4e6 / 2**30:7.1f} GiB")
    print(" " * 14 + f"cache 1024: {b * 1024 / 2**20:6.1f} MiB, "
          f"cache 4096: {b * 4096 / 2**20:7.1f} MiB")
PAPER_MS = {  # paper Fig. 10 latency per token (ms): re-compute / StreamingLLM
    "Llama-2-7B": [(63, 31), (103, 31), (223, 35), (523, 45), (1411, 65)],
    "Llama-2-13B": [(99, 48), (169, 52), (361, 60), (860, 75), (2355, 106)],
}
print("paper Fig. 10 speedup of StreamingLLM over re-computation, "
      "cache 256/512/1024/2048/4096:")
for k, v in PAPER_MS.items():
    print(f"  {k:12s}" + "".join(f"{a / b:7.1f}x" for a, b in v))
print("linear-layer FLOP ratio, re-computation / StreamingLLM = cache+1: "
      + ", ".join(f"{c + 1}" for c in [256, 512, 1024, 2048, 4096]))

The output:

== 0. checks of the implementation
dense vs HF forward: max |dNLL| = 0.0e+00
C >= n vs HF forward: max |dNLL| = 4.3e-05
SoftMax1 vs softmax with a zero logit: max diff 1.5e-08
token-by-token cache (S=0, C=64) vs mask version: 1.7e-04
token-by-token cache (S=4, C=64) vs mask version: 4.1e-05
== 1. perplexity by position (n=12288, cache=1024)
positions      dense   window   stream
    0- 1023     34.1     34.1     34.1
 1024- 2047     28.4    737.3     29.0
 2048- 3071     30.6     78.4     31.5
 3072- 4095     26.7     75.5     27.2
 4096- 5119     23.2     66.6     23.9
 5120- 6143     25.0     61.9     25.3
 6144- 7167     19.5     48.6     20.0
 7168- 8191     25.8     63.7     26.5
 8192- 9215     25.1     75.7     26.9
 9216-10239     20.5     53.4     21.7
10240-11263     33.9     96.6     36.0
11264-12286     25.9     76.4     27.4
all positions t>=2048: dense 25.31  window 68.44  stream 26.29
stream - dense: 0.038 nats/token (standard error 0.004)
== 2. sliding window with re-computation (every 16th position, t>=2048)
dense 28.01  window 76.35  stream 28.96  recompute 28.85
stream - recompute: 0.004 nats/token (standard error 0.005, n=640)
== 3. first position where window differs from dense: t=1025 (cache 1024: token 0 evicted)
t range        dense   window   stream   (mean NLL, nats)
  992- 1024     3.38     3.38     3.38
 1025- 1028     3.29     4.84     3.29
 1029- 1032     1.71     2.46     1.71
 1033- 1040     2.04     2.18     2.04
 1041- 1056     2.81     6.14     2.81
 1057- 1088     3.78     7.40     3.78
 1089- 1152     2.91     6.79     2.91
 1153- 1280     3.34     7.60     3.37
 1281- 1536     3.06     7.65     3.07
 1537- 2047     3.56     5.88     3.59
== 4. number of initial tokens kept (perplexity)
initial tokens kept                  0        1        2        4        8
paper Falcon-7B (2048)          17.90    12.12    12.12    12.12    12.12
paper MPT-7B (2048)            460.29    14.99    15.00    14.99    14.98
paper Pythia-12B (2048)         21.62    11.95    12.09    12.09    12.02
paper Llama-2-7B (4096)       3359.95    11.88    10.51     9.59     9.54
here  Qwen2.5-0.5B (1024)        68.44    26.29    26.29    26.29    26.28
change from 1 to 4 initial tokens:
  Falcon-7B (2048)       +0.0%
  MPT-7B (2048)          +0.0%
  Pythia-12B (2048)      +1.2%
  Llama-2-7B (4096)     -19.3%
  Qwen2.5-0.5B (1024)    +0.0%
== 5. cache size (perplexity, positions t>=8192)
cache   window(0+c)   stream(4+c-4)
  128       152.26          32.44
  256       106.89          29.77
  512        85.80          28.46
 1024        73.93          27.54
 2048        68.22          26.87
 4096        64.11          26.42
dense        25.92
== 6. what the sink tokens need (perplexity, positions t>=2048)
4+1020, positions inside the cache:   26.29
4+1020, original text positions:      26.36
4+1020, first 4 tokens -> newline:    27.00
== 7. attention mass (mean over heads and queries t>=2048): oldest entry, oldest 4, newest 4
layer  dense:old  new4  window:old  new4  stream:old  old4  new4
    0      0.000 0.300       0.000 0.306       0.000 0.000 0.306
    1      0.000 0.314       0.000 0.330       0.001 0.002 0.330
    2      0.000 0.382       0.000 0.400       0.000 0.000 0.400
    3      0.252 0.220       0.000 0.346       0.382 0.383 0.224
    4      0.235 0.253       0.000 0.416       0.266 0.266 0.257
    5      0.321 0.171       0.000 0.275       0.360 0.362 0.175
    6      0.228 0.243       0.000 0.348       0.259 0.259 0.247
    7      0.494 0.243       0.000 0.553       0.520 0.521 0.246
    8      0.144 0.467       0.000 0.681       0.180 0.180 0.466
    9      0.538 0.136       0.000 0.343       0.579 0.579 0.138
   10      0.230 0.259       0.000 0.437       0.258 0.258 0.263
   11      0.529 0.042       0.000 0.166       0.581 0.582 0.043
   12      0.181 0.268       0.000 0.354       0.206 0.206 0.270
   13      0.298 0.172       0.000 0.308       0.380 0.381 0.175
   14      0.236 0.276       0.000 0.361       0.245 0.246 0.277
   15      0.222 0.261       0.000 0.372       0.259 0.259 0.268
   16      0.557 0.042       0.000 0.172       0.702 0.702 0.044
   17      0.375 0.098       0.000 0.247       0.437 0.438 0.103
   18      0.411 0.241       0.000 0.475       0.448 0.449 0.242
   19      0.333 0.346       0.000 0.577       0.362 0.362 0.348
   20      0.400 0.066       0.000 0.178       0.461 0.462 0.068
   21      0.403 0.076       0.000 0.139       0.523 0.525 0.079
   22      0.000 0.021       0.000 0.052       0.001 0.011 0.031
   23      0.000 0.167       0.000 0.206       0.000 0.013 0.176
 mean      0.266 0.211       0.000 0.335       0.309 0.310 0.216
layers where dense attention puts >30% on token 0: 10 of 24; a uniform share would be 0.00017
value norm of token 0 / mean over the other tokens:
layers  0-11: 1.00 1.01 0.83 0.16 0.26 0.23 0.37 0.22 0.28 0.21 0.39 0.28
layers 12-23: 0.23 0.27 0.25 0.28 0.03 0.28 0.14 0.19 0.37 0.31 0.50 0.98
the 10 layers with a sink: 0.23; the other 14 layers: 0.49
== 8. beyond the native window (n=40960, native window 32,768)
positions      dense   stream  orig-pos
    0- 4095     29.8     30.3      30.4
 4096- 8191     23.3     23.8      23.8
 8192-12287     25.9     27.5      27.7
12288-16383     22.3     23.2      23.7
16384-20479     23.7     25.7      28.3
20480-24575     21.3     22.5      23.6
24576-28671     31.5     32.7      33.1
28672-32767     21.9     23.3      23.5
32768-36863     23.0     24.1      24.4
36864-40958     21.4     21.8      22.1
dense    t<32768:  24.73   t>=32768:  22.19
stream   t<32768:  25.91   t>=32768:  22.90
orig-pos t<32768:  26.54   t>=32768:  23.20
== 9. mini StreamEval: 19320 tokens, 156 queries, 18.3 tokens per line
distance back (mean tokens)     dense   window   stream  (5 digits)
     4 (  4 lines,     92 tokens)   26/26    2/26   26/26
    12 ( 12 lines,    275 tokens)   20/26    0/26   25/26
    24 ( 24 lines,    530 tokens)   16/26    0/26   14/26
    36 ( 36 lines,    805 tokens)   12/26    0/26   14/26
    60 ( 60 lines,   1332 tokens)   15/26    0/26    0/26
   100 (100 lines,   2199 tokens)   18/26    0/26    0/26
== 10. arithmetic
Qwen2.5-0.5B  KV per token  12,288 B, 4M tokens dense:    45.8 GiB
              cache 1024:   12.0 MiB, cache 4096:    48.0 MiB
Llama-2-7B    KV per token 524,288 B, 4M tokens dense:  1953.1 GiB
              cache 1024:  512.0 MiB, cache 4096:  2048.0 MiB
paper Fig. 10 speedup of StreamingLLM over re-computation, cache 256/512/1024/2048/4096:
  Llama-2-7B      2.0x    3.3x    6.4x   11.6x   21.7x
  Llama-2-13B     2.1x    3.2x    6.0x   11.5x   22.2x
linear-layer FLOP ratio, re-computation / StreamingLLM = cache+1: 257, 513, 1025, 2049, 4097

The implementation is right: it matches dense attention and the token-by-token official algorithm

  • It matches the Hugging Face forward pass. The NLL of dense attention is bit-for-bit the model’s own forward pass (maximum difference 0.0e+00); when the cache is longer than the sequence (C≥nC\ge n) the StreamingLLM mask blocks nothing and the maximum difference is 4.3e-05, which is float32 rounding. SoftMax1 and “put a key with score 0 in front” differ by only 1.5e-08, confirming the Zero Sink equivalence the paper states.
  • It matches the token-by-token form of the official algorithm. naive follows the official logic one token at a time: cache the unrotated K and V, evict after each step, rotate queries and keys by their position in the cache. Against my mask version, with C=64C=64 and 260 tokens, the maximum NLL difference is 1.7e-04 for S=0S=0 and 4.1e-05 for S=4S=4, both within float32 error. The point of this step is that every number below is a result of the StreamingLLM algorithm itself, not a by-product of my mask implementation.

Perplexity: window attention collapses after position 1024, StreamingLLM nearly coincides with dense

Perplexity by position: dense attention, window attention and StreamingLLM Perplexity of Qwen2.5-0.5B on 12,288 tokens of a novel, per 256 tokens, on a logarithmic axis. Dense attention and StreamingLLM almost coincide, between 14 and 72 after position 1024. Window attention jumps right after position 1024, where the cache is full and token 0 is evicted, and peaks at 2133 for positions 1280 to 1535; it then falls back to about 33 to 171 after position 2048, which is 2 to 4 times dense attention. 10 30 100 300 1,000 3,000 10,000 0 2,048 4,096 6,144 8,192 10,240 cache full, token 0 evicted 2,133 dense attention window attention (cache 1024) StreamingLLM (4 + 1020) position t (tokens) perplexity (log scale)
Figure: perplexity of Qwen2.5-0.5B on 12,288 tokens of novel text, per 256 tokens (log scale). The curves come from the same function as part 1 of the script; window attention and StreamingLLM both have a cache of 1024, StreamingLLM being 4 initial tokens plus the most recent 1020.
  • The collapse happens the moment the cache fills. Positions 0 to 1023 are identical for all three (34.1); from 1024, window attention has perplexity 737.3, dense 28.4 and StreamingLLM 29.0. Beyond position 2048 the overall perplexity is 25.31 for dense, 68.44 for window and 26.29 for StreamingLLM. StreamingLLM costs 0.038 nats per token over dense (standard error 0.004), about 4%, the price of dropping the middle tokens.
  • Not exactly like the paper: window attention recovers. In Figure 1 of the paper, Llama-2-13B with window attention scores 5158 over the whole 65K-token text, so it does not recover; this model’s window attention falls back after the spike (737.3) to between 48.6 and 96.6, roughly 2 to 3 times dense, and does not stay collapsed. I did not test why. One guess is that Qwen2.5’s long pre-training window leaves it more tolerant of inputs with no sink at the front; it is only a guess.
  • StreamingLLM agrees with the paper’s “ceiling”. Part 2 re-computes, at every 16th position, the last 1025 tokens from scratch (sliding window with re-computation, the paper’s quality ceiling); over the 640 sampled points after position 2048, dense is 28.01, window 76.35, StreamingLLM 28.96 and re-computation 28.85. The paired difference between StreamingLLM and re-computation is 0.004 nats (standard error 0.005), no visible difference. One explanation, which I did not test directly: in re-computation the first token of each window is a real “first token”, which the model saw in training, so the sink comes for free, while StreamingLLM gets the same effect by keeping the real initial tokens. Sampling every 16th position saves time and is not what the paper does.

Zooming in on the eviction

  • The first difference appears at position 1025. At position 1024 window attention can still see token 0 (a cache of 1024 plus itself); from 1025 token 0 is evicted and window and dense start to differ. For the first 4 positions after the eviction (1025 to 1028) the mean NLL of window attention is 4.84 against 3.29 for dense; for 1057 to 1088 it is 7.40 against 3.78; for 1281 to 1536 it is 7.65 against 3.06. The damage builds up within a few dozen tokens and then stays high: the mean NLL of 7.65 for 1281 to 1536 is a perplexity of about 2,100, much worse than dense at 3.06.
  • StreamingLLM barely notices at the same moment. From position 1025 the evicted tokens are ordinary ones, with index 4, 5, and so on; StreamingLLM’s mean NLL agrees with dense to two decimals up to 1152 (for 1057 to 1088 both are 3.78) and is only 0.01 to 0.03 higher afterwards (3.37 against 3.34 for 1153 to 1280). Evicting ordinary tokens hardly changes the prediction; evicting the sink breaks the whole model.

How many initial tokens to keep? Comparison with Table 2

  • This model needs only 1. Keeping 0 gives 68.44; 1, 2 and 4 tokens all give 26.29; 8 gives 26.28. In Table 2 of the paper, Falcon-7B (12.12 against 12.12), MPT-7B (14.99 against 14.99) and Pythia-12B (11.95 against 12.09) also need just 1; only Llama-2-7B drops from 11.88 with 1 token to 10.51 with 2 and 9.59 with 4, so keeping 4 is 19.3% lower than keeping 1.
  • So the paper’s text and its own table do not fully agree. Section 3.1 says models are “typically trained to use multiple initial tokens as attention sinks rather than just one”, and the caption of Table 2 says that one or two initial tokens do not fully restore perplexity; but in the table only Llama-2-7B supports that sentence. The reason the paper gives (Llama-2 pre-training samples have no uniform starting token) is a hypothesis that I did not test. For this model, “4 tokens” is Llama-2’s rule of thumb, not a general law.

Cache size: bigger is better here, unlike Table 6

  • A bigger cache helps both window attention and StreamingLLM. After position 8192: with a cache of 128, window attention is at 152.26 and StreamingLLM at 32.44; with 1024, 73.93 and 27.54; with 4096, 64.11 and 26.42; dense is 25.92. StreamingLLM with only 128 positions is already close to dense (about 25% above it), and with a cache of 4096 only about 2% above.
  • Table 6 of the paper does not look like this. There Falcon-7B and Pythia-12B are best at 4+1020, MPT-7B is best at the smallest cache, and Llama-2-7B at 4+2044; a bigger cache is worse. My largest cache is 4096, far below this model’s native window of 32,768, so that situation does not arise; the paper’s caches are of the same order as the models’ training length. That is my guess and I did not run a control.

What the sink needs: a position or a content

  • Cache-relative or original positions make little difference. With a 4+1020 cache, cache-relative positions give 26.29 and original positions 26.36. The paper says assigning positions inside the cache is crucial, and that is about text beyond the pre-training window; this text is only 12,288 tokens, inside this model’s native window of 32,768, so it cannot show the difference here; part 8 stretches the text beyond the window.
  • Replacing the initial tokens with line breaks costs little. Replacing the first 4 tokens with line breaks gives 27.00 against 26.29 for the originals and 68.44 for window attention. This agrees with Table 1 of the paper (4 line breaks 5.60, original 5.40, window 5158.07): the content of the sink does not matter.

Where attention goes: the sink absorbs weight but writes almost nothing

  • In dense attention, 10 of 24 layers give more than 30% of their weight to token 0. In each layer the “oldest key” (token 0 when dense) takes a mean weight of 0.266, with the maximum in layer 16 at 0.557 and layers 9 and 11 both above 0.5; a uniform split would give each key 0.00017. Layers 0 to 2 and layers 22 and 23 barely use the sink (the newest 4 tokens get 0.300 to 0.382 in layers 0 to 2, which is local attention, and the paper also says the bottom two layers do that).
  • In window attention the new “oldest token” does not become a sink. After the eviction, the oldest key in the cache gets weight 0.000 in every layer, and the weight that used to go to token 0 is pushed to the most recent tokens: the mean weight of the newest 4 tokens rises from 0.211 to 0.335. The model cannot “rebuild” a sink at the left edge of the window.
  • StreamingLLM puts the weight back on token 0. The oldest key takes 0.309 on average and the oldest 4 keys together 0.310, so the sink is almost entirely token 0, tokens 1 to 3 together take about 0.001; the newest 4 tokens get 0.216, almost the same as dense (0.211).
  • The sink’s Value is small. The norm of token 0’s Value vector divided by the mean norm of the other tokens is 0.23 on average in the 10 layers with a sink and 0.49 in the other 14 layers; in layer 16 it is 0.03 (that layer’s sink weight is 0.557); in layers 0 and 1 it is about 1.00, and those two layers do not use a sink at all. The sink soaks up a lot of attention weight and writes almost nothing into the residual stream, like an “empty” outlet, which agrees with the paper’s account (the sink has no semantics) and with the idea behind SoftMax1 (allow the head to attend to nothing). This is a measurement on one model and one text, not a proof.

Beyond the native window: 40,960 tokens

  • This part runs on the CPU. On MPS, attention over more than 32,768 keys gives wrong numbers: NaN at first, and after shrinking the block size, plausible-looking bad values (on MPS the last two blocks of dense attention came out at perplexity 59.7 and 345.3, on the CPU at 23.0 and 21.4); up to 32,768 keys MPS agrees with the CPU. I did not look for the cause; this is what I saw with PyTorch 2.10.0 and I do not know whether other versions behave the same. The lesson: check any dense computation over more than 32,768 keys on the CPU.
  • Dense attention does not hit a wall on this model. In the two blocks beyond the native window of 32,768 (32768 to 36863 and 36864 to 40958) dense perplexity is 23.0 and 21.4, inside the range of the blocks within the window (21.3 to 31.5); overall it is 24.73 for t < 32768 and 22.19 for t ≥ 32768. So this text cannot show “the model fails beyond its pre-training window” (that is what Llama-2 does past 4K): Qwen2.5-0.5B has RoPE base 10⁶ and a 32,768 window, and 8K more tokens show no degradation.
  • StreamingLLM works as usual beyond the window. For t ≥ 32768 StreamingLLM with cache-relative positions scores 22.90 against 22.19 for dense, and 25.91 against 24.73 for t < 32768. The cache holds only 1024 tokens, yet it reads all 40,960.
  • Cache-relative or original positions: the same direction, but small. The original-position version is never better than the cache-relative one in any block: 23.20 against 22.90 for t ≥ 32768 and 26.54 against 25.91 for t < 32768; the largest gap is the block 16384 to 20479 (28.3 against 25.7), and I did not look into why. The paper says cache-relative positions are crucial beyond the pre-training window; here the text is only 8K tokens longer than the window and I do not see that difference. Testing the claim needs a text much longer than the window, which I did not do.

How far back can it remember: a mini StreamEval

  • Setup. 900 records of the form The REGISTER_CONTENT in line 0123 is <48213> (a five-digit random number; line numbers zero-padded to four digits), with a question every 5 lines from line 120, asking for the record 4, 12, 24, 36, 60 or 100 lines back: 156 questions, 26 per distance, about 18.3 tokens per line and 19,320 tokens in the stream. Grading is an exact match of the five digits, with no free-form generation. The paper’s StreamEval asks every 10 lines with the answer always 20 lines back; I made the distance variable so that I could see where the cliff is.
  • A first try with 0.5B. With the same code and Qwen2.5-0.5B (the base model), dense attention answered only 23, 10, 11, 7, 4 and 5 of 26 at 4, 12, 24, 36, 60 and 100 lines back, which is too weak, so I switched to the 1.5B Instruct model. The first version did not zero-pad the line numbers and “line 20” and “line 120” are easy to confuse; after padding to four digits, dense attention’s accuracy still does not fall monotonically with distance. There are only 26 samples per row, one question is nearly 4 percentage points, and I did not dig into the non-monotonicity.
  • Result: the cliff is at the cache size. StreamingLLM answers 26 of the records 92 tokens back, 25 at 275 tokens, 14 each at 530 and 805 tokens, and 0 at 1,332 and at 2,199 tokens back; the cache is 1024, so beyond roughly 1,000 tokens the information has been evicted and no answer is possible. This agrees with Table 7 in Appendix C of the paper (Llama-2-7B-32K-Instruct: accuracy falls to 0 beyond the cache). Dense attention has no such cliff and still gets 15 and 18 right at 1,332 and 2,199 tokens back.
  • Window attention cannot even answer about the most recent records. At 4 lines (92 tokens) back it gets only 2 right and every other distance is 0: once the cache is full and token 0 is evicted the model has collapsed and cannot repeat what it just read. StreamingLLM scores higher than dense at 12 and 36 lines, by a few questions each, which is within noise and should not be interpreted.

The arithmetic: cache memory and the cost of re-computation

  • KV cache per token. Qwen2.5-0.5B has only 2 KV heads (grouped-query attention, see the GQA explainer), so each token takes 12,288 bytes and a dense cache for 4 million tokens is 45.8 GiB; Llama-2-7B has 32 layers and 32 KV heads, so each token takes 524,288 bytes, 4 million tokens need 1953.1 GiB, a 1024-token cache is 512.0 MiB and a 4096-token one is 2048.0 MiB; the StreamingLLM cache size does not depend on the length of the stream.
  • The speedups in Figure 10 of the paper. From the per-token latencies in the figure (Llama-2-7B: re-computation 63, 103, 223, 523 and 1411 ms against 31, 31, 35, 45 and 65 ms for StreamingLLM; 13B: 99, 169, 361, 860 and 2355 ms against 48, 52, 60, 75 and 106 ms) I get the speedups for caches of 256, 512, 1024, 2048 and 4096: 2.0, 3.3, 6.4, 11.6 and 21.7 times for 7B and 2.1, 3.2, 6.0, 11.5 and 22.2 times for 13B; 22.2 times is the paper’s headline. The latencies are numbers printed on the figure and I did not re-measure them.
  • Why re-computation is so slow. At every step it pushes C+1C+1 tokens through the whole network, so its linear-layer cost is C+1C+1 times that of StreamingLLM, which computes one new token per step: 257, 513, 1025, 2049 and 4097 times, and the attention part inside the window is still quadratic. The paper’s speedup is far smaller than that ratio. My explanation: decoding a single token is limited mainly by the memory bandwidth for reading the weights, and re-computation processes many tokens in one forward pass and reads the weights only once, so its cost does not grow C+1C+1 times; this is my inference and the paper does not analyze it.

Limitations and follow-ups

  • It neither extends the context nor strengthens memory. Appendix A says it is not suited to long-document QA or summarization. Table 7 in Appendix C: Llama-2-7B-32K-Instruct with a 4+2044 cache scores 85.80% at a token distance of 460 and 0.00 at 2300; with caches 4+4092, 4+8188 and 4+16380 accuracy likewise falls to 0 beyond the cache. On LongBench (Llama-2-7B-Chat, Appendix D), a 4+3496 cache scores 11.6 on NarrativeQA, below the truncation baseline (first 1750 plus last 1750 tokens) at 18.7; raising the sinks to 1750 brings it back to 18.2. The effect depends on what is in the cache.
  • A bigger cache is not always better. In Table 6 (400K tokens of PG-19), Falcon-7B and Pythia-12B are best at 4+1020, MPT-7B at the smallest 4+252, and Llama-2-7B at 4+2044 (9.08), then back to 9.59 at 4+4092. The paper reads this as the model not fully using its context, which agrees with the finding of Lost in the Middle.
  • “4” is not a law. Section 3.1 says models are “typically trained to use multiple initial tokens as attention sinks rather than just one”, but the paper’s own Table 2 supports that only for Llama-2-7B; see the hands-on section.
  • The cause of sinks is a hypothesis. “The first tokens are visible to all later tokens so they are the easiest to train into sinks” and “Llama-2 lacks a uniform starting token so it uses several” are supported only indirectly, by visualizations and the pre-training experiment, and not tested directly.
  • The pre-training part is small. Only 160 million parameters and one recipe; the paper recommends that future models include a sink token but gives no larger-scale validation.

What to take from this paper

  1. When window attention collapses, what collapses is softmax’s “outlet”, not the “context”. The evicted tokens carry almost no content yet play the role of normalization.
  2. The cache must keep both the “outlet” and the “recent information”. 4 initial tokens plus a rolling window is the smallest change; positions must be assigned inside the cache.
  3. An infinite stream is not infinite memory. It decouples “pre-training length” from “length of text that can be processed”, but information outside the window is still invisible.
  4. Check the paper’s rules of thumb yourself. “4 sinks” and “bigger caches are better” vary by model; with a different model the conclusion may differ.
  5. Sinks are a class of phenomena, not just a trick. They show up in decoders, encoders and vision models, and they inspired designs that reserve room in softmax for “attend to nothing”.

Further reading

FAQ

What is StreamingLLM and what problem does it solve?
StreamingLLM is a KV-cache policy that needs no fine-tuning: the cache always keeps the first few tokens (the paper uses 4 and calls them attention sinks), adds a sliding window of the most recent tokens, and evicts the rest. It targets settings where the text has no length limit, such as long-running chat or streaming input: a dense cache grows without bound, and plain window attention blows up in perplexity as soon as the cache fills and the first tokens are evicted. The paper reports that it keeps Llama-2, MPT, Falcon and Pythia stable on texts of more than 4 million tokens.
What is an attention sink, and why does deleting it break the model?
In most layers an autoregressive language model puts a large share of its attention weight on the very first tokens of the sequence, whatever those tokens are. That is the attention sink. The paper's explanation is that softmax forces the weights to sum to 1: when a query has no strong match in the context, the surplus weight has to go somewhere, and the first tokens, which every later token can see, are the easiest place for training to put it. Evicting them changes the softmax denominator and the attention distribution drifts away from what the model saw in training, so the output degrades. This is the paper's explanation, supported by attention maps and by ablations on which tokens to keep, not a proof.
Does StreamingLLM give a model an infinite context?
No. It lets the model keep reading without breaking, but each step can only see what is in the cache. In Appendix C, Llama-2-7B-32K-Instruct on StreamEval drops to 0 accuracy once the question-answer distance exceeds the cache size; in Appendix D, on LongBench, a 4+3496 cache scores 11.6 on NarrativeQA against 18.7 for a truncation baseline. The paper itself says it is not suited to long-document QA or summarization and fits multi-turn dialogue that needs only short-term memory. Longer memory needs a longer context window or retrieval.
Why keep 4 initial tokens rather than 1?
Four is the paper's empirical choice and it varies by model. In the paper's Table 2, Llama-2-7B goes from 11.88 perplexity with 1 kept token to 9.59 with 4; but in the same table Falcon-7B, MPT-7B and Pythia-12B with 1 kept token are about as good as with 4 (Falcon 12.12 vs 12.12, MPT 14.99 vs 14.99, Pythia 11.95 vs 12.09). The paper's explanation is that Llama-2 pre-training samples have no uniform starting token, so the model treats several initial positions as sinks; if every pre-training sample starts with one dedicated sink token, keeping that single token is enough.
How much faster is StreamingLLM than sliding window with re-computation?
In Figure 10, measured on one A6000 with Hugging Face Transformers, at a cache of 4096 the per-token decoding latency drops from 1411 ms to 65 ms for Llama-2-7B (21.7x) and from 2355 ms to 106 ms for Llama-2-13B (22.2x, the paper's headline speedup); at a cache of 256 the gain is only about 2x. The gap comes from the baseline recomputing the KV of the whole window for every new token: its linear-layer cost is the cache size plus one times that of StreamingLLM, and its attention part is still quadratic.