---
title: "Efficient Streaming Language Models with Attention Sinks (2023)"
description: "StreamingLLM keeps attention sinks and recent tokens in a fixed cache so language models can process continuous text without retraining."
canonical: "https://research.elamur.ai/free/en/papers/xiao-2023-efficient-streaming-language-models-attention/"
---
Elamur: [Mova](https://md.mova.elamur.ai/free/en/) · [Parse](https://mova.elamur.ai/free/en/parse/) · [Dictionary](https://md.dictionary.elamur.ai/free/en/) · [Translate](https://md.translate.elamur.ai/free/en/) · **Research** · [Gali](https://md.gali.elamur.ai/free/en/) · [MCP](https://mcp.elamur.ai/) · [Locations](https://md.locations.elamur.ai/free/en/) · [Weather](https://md.weather.elamur.ai/free/en/)

[Elamur Research](https://md.research.elamur.ai/free/en/) · [this page in HTML](https://research.elamur.ai/free/en/papers/xiao-2023-efficient-streaming-language-models-attention/)

[Elamur Research](https://md.research.elamur.ai/free/en/) / [papers](https://md.research.elamur.ai/free/en/papers/) / [2023](https://md.research.elamur.ai/free/en/papers/2023/) / Efficient Streaming Language Models with Attention Sinks

# Efficient Streaming Language Models with Attention Sinks

Paper · 2023 · Guangxuan Xiao, Yuandong Tian, Beidi Chen et al.

**Authors:** [Guangxuan Xiao](https://md.research.elamur.ai/free/en/authors/guangxuan-xiao/), [Yuandong Tian](https://md.research.elamur.ai/free/en/authors/yuandong-tian/), [Beidi Chen](https://md.research.elamur.ai/free/en/authors/beidi-chen/), [Song Han](https://md.research.elamur.ai/free/en/authors/song-han/) and [Mike Lewis](https://md.research.elamur.ai/free/en/authors/mike-lewis/) · **Year:** 2023 · **Venue:** arXiv:2309.17453 · **Licence:** [CC BY 4.0 (arXiv)](http://creativecommons.org/licenses/by/4.0/)

[Cited by **745** papers in our library of the 163,136 papers whose bibliographies we read](https://md.research.elamur.ai/free/en/papers/xiao-2023-efficient-streaming-language-models-attention/cited-by/) · [licence](http://creativecommons.org/licenses/by/4.0/)

- [PDF](https://arxiv.org/pdf/2309.17453)
- [arXiv 2309.17453](https://arxiv.org/abs/2309.17453)

## Summary

A conversation can keep going long after its earliest turns stop being relevant. Yet an autoregressive [language model](https://md.research.elamur.ai/free/en/concepts/language-model/) ordinarily keeps a record of every token it has processed so that it can consult those tokens when predicting what comes next. This record, called the key-value or KV cache, grows with the conversation. A natural way to bound it is to discard the oldest entries as new ones arrive. The authors find that this simple policy can abruptly ruin predictions when it removes the very first tokens, even though those tokens may contribute little to the meaning of the passage now being read.

The paper calls these early positions attention sinks. In a [Transformer](https://md.research.elamur.ai/free/en/concepts/transformer/), each attention head distributes a fixed total weight over the positions it can see. The authors argue that a head can learn to put weight on a familiar position when it has little useful information to collect from elsewhere. The first positions are available to nearly every later prediction during training, making them natural places for this behavior to develop. Replacing the opening tokens with line breaks still allows them to play the same role. In a separate analysis of sequences of length 4096, the last position in Llama-2-7B frequently assigns more than half of its attention to the first token outside the bottom two layers. An encoder example also shows a concentration of attention, in that case on BERT’s `[SEP]` token. [BERT](https://md.research.elamur.ai/free/en/papers/devlin-2019-bert-pre-training-deep-bidirectional/)

StreamingLLM keeps the keys and values for 4 opening tokens alongside a sliding window of recent tokens. It assigns positions according to where the entries sit in the cache, closing the gap left by discarded text. This inference procedure needs no additional training. Across Llama-2, MPT, Falcon, and Pythia, the authors report stable next-token prediction on a stream of 4 million tokens. On the first book of the PG-19 test set, a 65K-token sequence, Llama-2-13B with StreamingLLM achieves perplexity close to that of rebuilding the recent window at every step. Dense attention and ordinary window attention fare much worse in that comparison. Against the recomputation method, StreamingLLM reaches a speedup of up to 22.2× per decoded token in the efficiency tests.

The authors also train 160 million parameter systems from scratch to see whether a dedicated, learnable placeholder can take over the sink role. A single placeholder gives stable streaming perplexity when retained alongside recent text, while standard training leaves the system dependent on several opening tokens. Adding a second learned placeholder brings no substantial improvement in the reported tests. The practical result is a way to keep processing text with a bounded cache. The information available for a reply still depends on what that cache contains, which makes incoming text about recent events a better fit than questions that require access to an entire long history.

## Deep dive: Efficient Streaming Language Models with Attention Sinks

StreamingLLM keeps attention sinks and recent tokens in a fixed cache so language models can process continuous text without retraining. · about 35 minutes to read

**In this deep dive**

1. [The problem and its context](#dd-the-problem-and-its-context)
2. [The method, step by step](#dd-the-method-step-by-step)
3. [Experiments and results](#dd-experiments-and-results)
4. [What the ablations show](#dd-what-the-ablations-show)
5. [Limitations](#dd-limitations)
6. [What came after](#dd-what-came-after)

### The problem and its context

#### A long session creates two different problems

During [text generation](https://md.research.elamur.ai/free/en/topics/text-generation/), a decoder predicts an upcoming token from the tokens already available to it. The history can include a prompt, text delivered by a user, and earlier output from the decoder itself. If the process runs over a continuing conversation, new text can arrive over many turns before the session ends. A service that mainly answers questions about what just happened still has to decide what to do with the representations of everything that happened earlier.

Attention provides a way for the current position to consult previous positions. A query represents what the current position asks for. A key is used to score a candidate position against the query, and a value is the information contributed by that position to the attention output. For positions the decoder has already processed, the keys and values can be saved. Their reuse avoids recalculating all the representations of the past each time the decoder advances. The saving comes with a growing storage obligation if the implementation keeps an entry for every token.

There is a second problem even when there is enough memory to keep the whole history. The decoder was trained with sequences of bounded length. Its behavior at much larger lengths may degrade, so paying the cost of a larger cache does not guarantee sound predictions. The paper gives 4K as the training length for Llama-2. A conversation that runs beyond that scale poses a storage problem for dense attention and also asks the system to operate outside its usual range of sequence lengths. The paper treats these as separate constraints, since either can disrupt a service even when the other has been addressed. [Llama 2](https://md.research.elamur.ai/free/en/papers/touvron-2023-llama-2-open-foundation-fine/)

This distinction matters for [dialogue systems](https://md.research.elamur.ai/free/en/topics/dialogue-systems/) in which the visible conversation history and the history needed for a reply can be very different in size. A reply that depends on a recent exchange needs the representations of that exchange to remain available. It may be perfectly adequate for such a session to discard older material. The question is whether a pretrained decoder will continue to predict well when old material is removed repeatedly, including the material it saw when the session began.

#### What a sliding window promises

A fixed window gives an obvious answer to the storage problem. At each step, it keeps the most recent tokens, up to a chosen limit, and drops the oldest entry when space is needed. Once the cache fills, the amount of remembered text stays fixed. The attention work for a new token can also stay bounded because the new query sees only the entries in the window. The authors connect this local pattern to earlier work on efficient attention, including [Longformer](https://md.research.elamur.ai/free/en/papers/beltagy-2020-longformer-long-document-transformer/).

There is another way to use a window of the same size. Instead of carrying forward each surviving key and value unchanged, the decoder can process the recent text again whenever it needs the next prediction. Every recomputation treats the window as a fresh piece of input and constructs representations in that setting. When the window shifts, some tokens therefore acquire representations calculated using a different history. This baseline spends substantially more computation per step than a rolling cache because it repeatedly performs attention across the window.

These policies look similar if the only question is which words fall within the window at a given instant. They differ in how the representations of those words were made. The recomputation approach continually creates a new beginning. The rolling approach retains states computed when the original beginning was still part of the stream and eventually removes that beginning from the set of visible keys and values. The paper uses this difference to investigate what a cached decoder depends on from its opening positions.

Dense attention provides a further point of comparison. It allows each new position to see the full available prefix, preserving both the earliest tokens and the recent ones. The visible prefix length grows throughout the session. With a fixed recent window, the useful question is whether the decoder can maintain good predictions at a stable cost. With dense attention, the question is whether the entire prefix can still be processed within the system’s memory and within the range of lengths where its predictions are reliable. These alternatives expose different reasons for a streaming system to fail.

#### Longer input, a larger window, and better use of context

The paper organizes previous long-text research around several related objectives. Length extrapolation concerns applying a system to inputs longer than those used in training. Work on relative position encoding addresses part of this problem by representing how far apart positions are. Rotary Position Embeddings, or RoPE, incorporate this information by transforming queries and keys. ALiBi adds a distance-dependent bias to the score of a query-key pair. The authors discuss ALiBi as an approach that improves extrapolation and cite earlier work finding limitations for rotary encodings beyond the training range. [RoFormer](https://md.research.elamur.ai/free/en/papers/su-2021-roformer-enhanced-transformer-rotary-position/)

Context window extension concerns how much input the decoder can consider together. The paper describes several ways earlier work addressed that objective. More efficient attention computation can make training on longer sequences feasible. Approximate attention can reduce the computation by restricting or restructuring the interactions between positions. Position interpolation and [fine-tuning](https://md.research.elamur.ai/free/en/concepts/fine-tuning/) can adapt pretrained systems to a larger usable window. A larger window raises the amount of text available at any given step, although the window still has a finite capacity. The authors cite exact attention implementations in the discussion of training efficiency, including [FlashAttention-2](https://md.research.elamur.ai/free/en/papers/dao-2023-flashattention-2-faster-attention-better/).

Sparse attention work also explored combinations of local context and special global connections. Longformer, for example, combines dilated local attention with global attention chosen for the task. The paper describes ETC as offering different patterns for interactions between global and local positions, and BigBird as combining global positions with a local window and random connections. In the authors’ discussion, these methods define attention patterns for their own architectures. Building on an existing causal decoder poses a different question about which entries to expose at inference, given the attention behavior it already learned.

The paper identifies effective use of a long context as a further objective. A decoder can be capable of accepting a lengthy input and still have trouble finding or using the relevant information within it. The positional placement of an answer or piece of evidence can matter even when all of the text fits. This issue is central to the earlier work discussed as [Lost in the Middle](https://md.research.elamur.ai/free/en/papers/liu-2023-lost-middle-language-models-use/).

StreamingLLM addresses continuous operation with the recent part of the stream available. The authors’ running example is a conversation in which new turns keep arriving and recent exchanges usually supply the necessary context. By defining the problem this way, they can ask whether elapsed stream length can grow while the amount of attended text at a given step stays bounded. A larger window can be combined with this approach, in which case the service can see farther back locally as it continues to run.

### The method, step by step

#### Why the first tokens are unusual

To follow the method, consider what happens inside a single attention head. The head gives each visible position a score, often called a logit before normalization. A high logit makes a position more influential in the weighted combination of values. This weight is relative to the logits for the other visible positions. An entry can acquire a large share because its score is high compared with the rest, even when its token supplies little information relevant to the current prediction.

The authors noticed that the first positions repeatedly receive large scores. In causal attention, the token at the beginning is in view for every later position in the training sequence. A token near the end has far fewer later positions that can attend to it. The authors suggest that this asymmetry makes the beginning a convenient place to assign attention when a head has little to collect from its context. The current representation may already carry what is needed, while standard softmax still produces a distribution with a fixed total weight.

The paper illustrates the situation by writing the first term of the softmax denominator separately.

```
SoftMax(x)ᵢ = eˣⁱ / (eˣ¹ + ∑ⱼ₌₂ᴺ eˣʲ),   x₁ ≫ xⱼ for j ∈ {2, …, N}
```

Here `x` is the collection of logits for the visible positions, `xᵢ` is the logit for position `i`, and `SoftMax(x)ᵢ` is its normalized weight. The superscripts `ˣⁱ`, `ˣ¹`, and `ˣʲ` denote the exponents `xᵢ`, `x₁`, and `xⱼ`. The base `e` is the natural exponential base. `N` is the number of positions, and the summation adds the exponential of the logit for each position `j` from `2` through `N`. The ellipsis covers the intervening indices. The condition marked by `≫` says that the logit at the first position is much larger than the logits at the other positions in the illustration. The symbol `∈` means that `j` belongs to the indicated set.

The significance of the denominator becomes clear when an entry is evicted. For a fixed set of surviving logits in a head, all their weights are changed by removing a term from the denominator. Removing an entry with a large logit has a much larger effect than removing one with a negligible contribution. The surviving values then enter the head’s output with new weights. Through the layers of the decoder, changes in attention outputs can alter the representations on which the final prediction depends.

The term attention sink describes a position that repeatedly receives a large amount of this weight. It is a statement about a pattern of attention. The paper’s line-break substitution is important because it separates the attraction of an opening position from the information in the original wording. For the inference method, the immediate consequence is that a rule based entirely on token age can remove a disproportionately influential part of the attention computation.

#### Keep the opening and move the recent window

StreamingLLM sets aside part of the cache for the beginning of the stream. The remaining capacity holds the most recent positions. The method carries the entries for the beginning throughout the session, while entries in the recent portion are replaced as newer tokens arrive. The default for the pretrained systems in the streaming evaluations is 4 initial tokens. The two regions together define what a new query can attend to after the cache begins evicting entries.

How StreamingLLM updates the cache while decoding The steps in order.

A cache configuration in the paper is written as `x+y`, where `x` is the number of initial tokens reserved and `y` is the number of recent tokens retained. For example, `4+1020` refers to a cache that pairs the first 4 tokens with the most recent 1020 when the cache has filled. The former give attention a familiar place to put weight. The latter supply the text immediately relevant to next-token prediction. Giving the initial segment more room changes how much recent text fits under a fixed total capacity, which makes the number of preserved positions an experimental choice.

Once the recent region is full, a token ages out when the next entry needs its place. Its key and value cease to be directly available to subsequent attention. The entries that survive the update can be reused at the next step. The purpose of retaining the opening region is to preserve some of the conditions under which attention operated before the cache filled. The method does not rebuild each surviving token’s full representation on every update, which is where it saves work relative to the recomputation baseline.

The distinction between original opening tokens and a designated placeholder matters. With existing pretrained systems, StreamingLLM can use the opening tokens already present in the stream. The method relies on their learned positional role and can be applied at inference. A separately trained system can be given a dedicated token for that role, but this is a change to the training setup, independent of making the inference procedure work with systems already available.

#### Close the gap when computing positions

Keeping the beginning and the recent end creates a gap in the original sequence. The beginning might be far away in elapsed text even though it is adjacent to the oldest entry of the current window in storage. The authors assign positions using the order of the visible entries. Their example starts with cached tokens whose original indices are `[0, 1, 2, 3, 6, 7, 8]`, while the next token being processed has original index `9`. For attention, the positions used for the visible sequence and the current token are `[0, 1, 2, 3, 4, 5, 6, 7]`. The relative order stays the same and the missing middle consumes no positional distance in the cache.

This step addresses a separate consequence of running for a long time. Simply retaining an opening key while scoring it at its original distance would allow that distance to grow with the stream. Cache-relative positions keep the distances used in those computations bounded by the number of entries in view. That gives the opening region a consistent relationship to the moving window and prevents the absolute progress of the session from continually stretching the relative distances seen by attention.

For RoPE, the key saved in the cache precedes the rotary transformation. The decoder applies the position-dependent transformation for a key when it uses that key in the current attention calculation. A recent key can therefore move to a different cache position when an older entry is evicted. Saving a permanently rotated key with its original position would preserve the original position information, whereas StreamingLLM needs to apply the rotation appropriate to the current arrangement. This extra transformation is distinct from rebuilding a whole recent window through the decoder.

For ALiBi, position enters through a bias on the attention score. The method can supply distances corresponding to consecutive cache positions when it constructs those biases. The same rule about which tokens to retain therefore works with the two encoding schemes, while the operation that places position information into attention differs. The paper evaluates the framework with both types of decoder. Its argument for using cache positions applies to the distance calculation, whether that calculation is expressed through transformed keys or through score biases.

#### The cost of retaining or rebuilding a window

The paper uses asymptotic expressions to explain why dense attention and recomputation become expensive in different ways. For dense attention across the stream, the paper gives the following cost.

```
O(T²)
```

`O` denotes the order of growth in the attention work, and `T` is the total length up to the token being predicted. The exponent indicates quadratic growth. As the sequence progresses, early steps have relatively short prefixes and later steps see larger ones. Taking the attention work across the sequence accounts for the quadratic cost, while the amount of cached history grows with the prefix.

For the baseline that rebuilds a fixed recent window, the paper gives this expression.

```
O(TL²)
```

Here `O` again describes the order of growth, `T` is the total sequence length, and `L` is the length of the attention window in the comparison. The exponent on `L` represents the quadratic attention calculation within the window. Repeating that calculation throughout the stream gives the dependence on `T`. The costly operation is performed even when most of the tokens in the current window were also in the previous one.

StreamingLLM keeps the states it will reuse, so a new query attends over a bounded set of keys and values. At a fixed cache size, there is no need to increase the number of entries consulted as the session grows. When the cache size itself is increased, each new query visits more entries. This explains why the authors compare decoding latency as a function of cache size as well as examining behavior over long streams. The recomputation baseline pays for interactions throughout the window at each step, while the streaming method pays for processing the current token with access to the retained state.

#### Give the sink its own token during training

The paper explores whether the spread of attention across several opening positions can be narrowed to one dedicated position. The authors’ explanation for that spread concerns the preparation of training sequences. Even when a paragraph receives a start marker, chunking the text afterward can put an ordinary token at the beginning of a training chunk. The opening position is highly visible in causal attention, but the token occupying it can vary. The authors hypothesize that a consistently present, learnable placeholder would make it easier for training to concentrate the sink behavior in one entry.

The learned variant prepends a dedicated token to every training sample. It is visible throughout that sample, just as other early tokens are, and its representation can be learned. At streaming inference the retained opening entry can then be the dedicated token. The rest of the cache is available for recent text. This variant tests whether giving attention a predictable place to concentrate reduces dependence on the neighboring opening positions.

The authors also consider a version of softmax with an extra term in the denominator.

```
SoftMax₁(x)ᵢ = eˣⁱ / (1 + ∑ⱼ₌₁ᴺ eˣʲ)
```

`SoftMax₁(x)ᵢ` is the resulting weight at position `i` under the modified normalization. The subscript `₁` identifies the variant with the added `1` in the denominator. `x` contains the logits and `xᵢ` is the logit at position `i`. The exponential has base `e`, with `ˣⁱ` and `ˣʲ` denoting the exponents for positions `i` and `j`. `N` counts the contextual positions, and the sum ranges over those positions from `1` through `N`. The standalone `1` represents the contribution of a zero logit because the exponential of zero is one.

The ordinary contextual positions can now receive less than the full weight. The paper explains this change as equivalent to adding an entry with an all-zero key and an all-zero value. Its key produces a zero logit and hence the extra denominator term. Its value contributes nothing to the weighted output. The authors call this condition Zero Sink. The learned placeholder has more freedom because its key and value can develop during training. Comparing the fixed and learned approaches probes whether providing an outlet for some attention weight is sufficient by itself.

For the training comparisons, the authors use 160 million parameter systems trained from scratch. The detailed vanilla versus learned-sink experiment follows the Pythia-160M recipe with the deduplicated Pile as training data, on an `8xA6000` NVIDIA GPU server. The batch size is reduced to 256. The learning-rate schedule, initialization and dataset permutations follow the original recipe, and both runs last 143,000 steps. The standard-attention, Zero Sink and learned-placeholder conditions enter the streaming comparison. An additional training study compares the ordinary setup with one or two learned placeholders. The authors make the implementation and experimental datasets available with StreamingLLM. [The Pile](https://md.research.elamur.ai/free/en/papers/gao-2021-pile-800gb-dataset-diverse-text/)

### Experiments and results

#### Predicting the next token across books

The main language-prediction evaluation uses the test split of PG19. The authors join its 100 books into a continuous text and process that text as a stream. They measure perplexity, which reflects how much probability the system assigns to the tokens that actually follow. Lower perplexity means the observed continuation was, on average, less surprising under the predictions. This is a direct test of whether next-token prediction stays usable as the cache turns over repeatedly. It can be run on the same text and with the same underlying weights for each cache policy.

The experiments cover Llama-2, MPT, Falcon, and Pythia. Llama-2, Falcon and Pythia use rotary position encoding in the evaluated systems, while MPT uses ALiBi. The authors set the cache to 2048 tokens for Llama-2 and 1024 for the other families in the PG19 experiments. They chose these capacities to be half the respective pretraining window for visual clarity. The arrangement puts cache saturation and the pretraining-length boundary at different points in the comparison, so the characteristic failure of each baseline can be observed separately.

Cache capacity by decoder family in the PG19 test-stream comparison The Llama-2 runs use a larger cache budget than the other family runs.

**The numbers**

| System or setting | cached tokens |
| --- | --- |
| StreamingLLM with Falcon, Pythia or MPT (this paper) | 1024 |
| StreamingLLM with Llama-2 | 2048 |

The chart compares storage settings. Perplexity across families is a separate measurement and depends on the decoder as well as the amount of text in its cache. The baseline comparisons that isolate the cache policy use the same underlying decoder. Dense attention keeps the full prefix. Window attention carries forward recent entries only. Sliding-window recomputation rebuilds the recent slice at each step. StreamingLLM carries forward both the opening entries and recent ones. This setup lets differences in the timing and severity of failure be related to what each baseline does with the input.

On the first PG-19 test book, a sequence of 65K tokens, the authors compare these policies with Llama-2-13B. Dense attention and window attention produce very high perplexity, while recomputation and StreamingLLM give much lower and closely matched results. The dense method preserves the opening but pushes past the pretraining length. The recent-only window stays within its cache capacity, but it removes the opening. The recomputation comparison shows that current text from a bounded window is sufficient for much better token prediction on this input. The StreamingLLM result shows that the system can reach approximately the same quality while reusing cached states.

On the 20K-token comparisons across decoder families, the timing of the deterioration is particularly informative. Window attention performs poorly once the input outgrows the cache and the original initial tokens start falling out. Dense attention deteriorates after the stream exceeds the pretraining window. The recomputation curve serves as the quality reference throughout the available span. StreamingLLM follows it closely in perplexity while operating with the retained beginning and rolling recent segment. The reference is an empirical comparison with a costly local method, so the reported match concerns the quality of using recent text in these tests.

The longer run takes the test through 4 million tokens. The paper reports stable perplexity throughout this span for Llama-2, Falcon, Pythia, and MPT, with multiple sizes represented in each family. The authors attribute fluctuations in the traces to transitions between books. Stability in this experiment means that prediction quality does not undergo the collapse associated with the cache first filling. It allows for the text itself to be easier or harder to predict at different points. The length demonstrates that the rolling procedure continues to function long after any single cache window could have held the entire input.

These language-prediction tests answer a narrower question than whether a decoder understands all the books jointly. At a late point in the concatenated stream, perplexity reflects how well the decoder predicts from the entries it actually sees. For much of the text, useful evidence can be found in recent sentences and paragraphs. The run tests continuity of next-token prediction as old entries are repeatedly displaced. Its design also motivates experiments in which the location of the evidence can be set explicitly.

#### Latency and memory at decoding time

The systems measurement compares StreamingLLM with the recomputation baseline because both preserve usable prediction quality on the language tests. The implementations use Hugging Face Transformers and are tested on a single NVIDIA A6000 GPU with Llama-2-7B and Llama-2-13B. The measurements are latency per decoded token and memory use at different cache sizes. A per-token measurement captures the cost that recurs for as long as the service keeps decoding. [Hugging Face Transformers](https://md.research.elamur.ai/free/en/papers/wolf-2020-transformers-state-art-natural-language/)

The largest reported speedup is 22.2× per token. The gap grows with window size because the reference repeatedly recalculates attention among the tokens of the recent window. StreamingLLM can reuse the retained state and compute attention for the current step over that state. The authors describe latency for StreamingLLM as growing linearly with cache size, while the recomputation baseline shows quadratic growth. The measured memory footprints are similar. In these configurations, the principal observed advantage over recomputation is therefore the time saved at each decoding step.

This comparison also clarifies why results against the simpler window policy would answer a different question. A recent-only rolling cache is already designed to avoid the expense of recomputation. Its failure in the perplexity tests concerns its quality after eviction, which is what the sink entries repair. The meaningful performance comparison with recomputation is between methods that continue to offer usable predictions when the original text is much longer than the recent window.

#### Answering questions as input continues to arrive

To test [question answering](https://md.research.elamur.ai/free/en/topics/question-answering/), the authors concatenate question-answer pairs from ARC-Easy and ARC-Challenge. They give this stream to instruction-tuned Llama-2 chat systems, measuring completions at answer positions by exact match. Under this metric, the accepted answer must match the expected answer. A separate baseline evaluates examples individually, giving a reference for how well the systems answer when each item can be handled on its own. [ARC](https://md.research.elamur.ai/free/en/papers/clark-2018-think-have-solved-question-answering/)

Window attention and StreamingLLM both use caches of 1024 tokens in the ARC comparison. Dense attention runs out of memory in the streaming setup. The recent-only window produces poor accuracy after the cache fills, which the paper associates with the onset of erratic output once the input exceeds the cache. StreamingLLM remains comparable in accuracy to the sample-by-sample reference. The experiment uses questions that can be answered at their own locations in the stream. It tests whether running a succession of prompts through the same session disrupts the ability to answer a current item.

A separate dataset, StreamEval, tests whether the decoder can use facts from a controlled distance back in the stream. Inspired by LongEval, it inserts questions periodically as new lines are delivered. In the main setup a query appears every 10 lines, and the line containing the answer is 20 lines back. The questions therefore continue across a long overall span, with each answer consistently located in the recent past. Mean accuracy is reported over 100 samples for the main StreamEval figure.

With StreamingLLM, the evaluated instruction-tuned systems sustain reasonable accuracy as the streams approach 120K tokens. Dense attention and recent-only window attention fail around different boundaries. For the former the paper identifies the pretraining length, and for the latter it identifies the point where the cache overflows. The experiment also includes LongChat-7b-v1.5-32k and Llama-2-7B-32K-Instruct. These context-extended systems demonstrate how a broader local window can be used with the same streaming scheme. They can accommodate more recent information, while the total length of the stream grows independently of that local span.

#### Training with a learned sink

The pretraining comparisons examine both ordinary performance and streaming performance. For ordinary performance, the paper compares training-loss curves and zero-shot accuracy. Zero-shot evaluation here means the systems are assessed on benchmark tasks without training specifically for those tasks as part of the comparison. The tasks include both ARC settings, HellaSwag, and LAMBADA. The authors also evaluate OpenbookQA, PIQA, and Winogrande. The learned-placeholder and vanilla runs follow similar loss trajectories and give similar accuracy across the benchmark suite. [WinoGrande](https://md.research.elamur.ai/free/en/papers/sakaguchi-2019-winogrande-adversarial-winograd-schema-challenge/)

The streaming comparison measures perplexity on the first example from the PG19 test set. The vanilla run needs several initial entries to recover stable prediction with the recent window. The trained placeholder is sufficient on its own when paired with recent entries. Zero Sink gives some relief but still benefits from preserving other initial tokens. The learned-sink condition therefore changes which entries must stay available at inference, even though the standard evaluation shows similar overall performance. The paper also finds an opening attention pattern concentrated more strongly on the placeholder, which gives a representation-level observation consistent with the cache result.

### What the ablations show

#### The words at the opening can change

The line-break intervention tests an explanation that would make the cache policy less general. If the opening mattered because it stated the subject of the book or conveyed some other content essential to prediction, replacing those tokens with line breaks should deprive the decoder of that information. The authors instead find comparable recovery when they retain the substituted opening. The test compares perplexity on the first PG19 test book, with its sequence of 65K tokens. One condition retains the original initial tokens alongside the recent window. The other gives the same opening positions to repeated line-break tokens and retains those entries.

The relevant small-prefix configuration is `4+1020`, with 4 initial tokens and 1020 recent tokens. At the point of comparison, the recent region remains available in both versions. The result shows that lexical continuity with the original opening is unnecessary for the recovery observed in the experiment. The substitute tokens can receive strong attention at the beginning and preserve much of the benefit. That is evidence for the authors’ account in which position and consistent visibility contribute to the sink behavior.

The design still gives the line breaks their own keys and values as processed by the decoder. Their effect is consequently richer than the mathematical operation of replacing an attention term with a constant. The substitution isolates something specific, namely the need for the original opening text. The structural properties of that opening are both retained and useful. This makes the test complementary to Zero Sink, which changes normalization more directly and leaves a different learned attention pattern.

#### The number of retained positions matters

In the initial-token ablation, the authors vary the number of beginning entries saved with the recent text. The test measures perplexity over 400K tokens from the concatenated PG19 test split. With a recent-only window, perplexity rises sharply after the initial entries leave the cache. Preserving one or two initial tokens usually gives an incomplete recovery. Keeping four generally recovers the quality, with further additions yielding diminishing returns. This is the evidence behind the inference default, rather than a fixed requirement of softmax itself.

A large average weight on the first token might suggest that one retained entry should suffice. The ablation addresses this prediction at the level of end-to-end output. Attention is computed separately across heads, layers and query positions. The first entry can dominate a reported average while nearby positions still have important effects on how some heads normalize or combine information. The difference between saving one entry and a small prefix shows that a visual aggregate of attention weights gives only part of the evidence needed to choose a cache policy.

The paper also varies the cache capacity. This comparison, measured on 400K tokens of the concatenated PG19 test set, asks whether making more recent positions available consistently helps next-token prediction. The authors find that increasing the cache size does not reliably lower perplexity. A larger cache expands access to recent text, but how well the decoder uses that text depends on its learned attention behavior. The paper presents the nonmonotonic result as a sign that the utility of additional context remains a separate issue from fitting the context into memory.

#### The attention pattern persists across sequence lengths

The first visualization averages attention logits for Llama-2-7B over 256 sentences of length 16. In layers 0 and 1 the pattern is predominantly local, with attention focused near the current token. Higher layers show much stronger logits for the first position. The authors also inspect sequences of length 128, again using 256 sentences. The concentration at the beginning persists even when many more positions separate the current query from the opening.

For a more direct measure on long inputs, the paper examines attention after softmax. It averages over 256 sequences of 4096 tokens and tracks the weight the 4096th position assigns to the first token. Error bars describe variability across heads within each layer. The weight on the first position often exceeds half of the entire normalized distribution, except in the two bottom layers. This measure complements the heatmaps of logits because it directly assesses how much of the available weight is concentrated at the entry that the rolling-window baseline will eventually discard.

The Llama-2-70B visualization averages logits over 256 sentences of length 16 and shows a similar emphasis on early positions in most layers. The large share at the start is therefore visible at another scale in the same family. Across the visualizations, the behavior shows up at different input lengths and under two forms of measurement. The removal and restoration experiments then connect that observation to the predictions. They show that the cache entries associated with the pattern materially affect the result.

The encoder appendix asks whether the same general pattern is visible when attention is bidirectional. In the BERT-base-uncased example, `[SEP]` attracts substantial attention in most layers. This is a token broadly visible to the positions in the sentence, and it occupies a different structural role from the first position in a causal sequence. The observation is consistent with the idea that softmax attention can concentrate on a stable, widely visible position outside autoregressive decoders. Its evidence is an attention visualization, whereas the causal decoder study additionally tests what happens to next-token prediction after eviction.

#### A learned destination changes the distribution

The training intervention examines whether the sink can be deliberately concentrated in a single position. In the vanilla condition, the attention visualizations show local patterns in lower layers and a stronger preference for opening tokens in deeper layers. With the learned placeholder, the authors find greater concentration on that entry and less attention to the other initial tokens. The comparison averages logits over 256 sentences of 16 tokens and shows corresponding layers and heads in both conditions. The shift in attention agrees with the observation that the learned-sink decoder can keep only the placeholder and the recent window while maintaining stable perplexity.

Zero Sink isolates one part of the explanation. The additional denominator term gives the head a way to leave some weight off the contextual values. It relieves some of the dependence on the opening, yet the system still uses other opening tokens. With the learned intervention, both the scoring behavior and the information represented at the placeholder can be shaped by training. The two results together show that a fixed zero-valued outlet and a learned entry do not lead to equivalent streaming behavior in the reported comparison.

The appendix compares training with one and two learned sinks. Training-loss curves remain close to the vanilla curve, and the second token does not produce a substantial improvement on most of the zero-shot tasks. It also provides no further gain in streaming perplexity. When the decoder is trained with two placeholders, it appears to depend on keeping both of them to preserve stable streaming behavior. The result fits the broader observation that what a system can safely discard depends on the positions it learned to use during training. Adding more such positions can spread the dependence instead of further reducing the required cache prefix.

#### When the relevant text falls out of the cache

The StreamEval distance experiment varies how far the answer is from the question under different cache configurations. The decoder is Llama-2-7B-32K-Instruct. Each line contains 23 tokens, so the corresponding token distance is defined in the paper as follows.

```
dₜ = 23 × dₗ
```

`dₜ` is the distance in tokens, and `dₗ` is the separation measured in lines. The multiplier `23` is the number of tokens in one StreamEval line, and `×` denotes multiplication. Accuracy is averaged over 100 samples, with 100 queries in each sample.

When the answer lies within the cache’s span, StreamingLLM can sustain accuracy, though performance deteriorates as the relevant line moves farther away. Once the evidence falls beyond the cache capacity in this experiment, accuracy drops to zero. This manipulation provides a more direct measure of the effective reach of the system than the overall length of the input stream. A question can occur very late in the stream and remain answerable if its evidence is recent. A question with an older answer can defeat the same decoder and cache policy.

The LongBench comparison varies what is preserved at the other end of the input. It uses Llama-2-7B-chat on single-document and multi-document questions as well as summaries. The benchmark’s default truncation preserves 1750 tokens from the beginning and 1750 from the end. StreamingLLM with `4+3496` gives almost all of its cache to the recent segment and performs worse than the default. The authors attribute this result to the likely loss of important information from the initial prompt. With `1750+1750`, StreamingLLM performs at the level of the truncation reference.

That comparison distinguishes preserving the computational role of the opening from preserving its substantive contents. A handful of entries can be enough to stabilize attention. A particular question may require many earlier entries because the beginning holds evidence or instructions. Giving the prefix more room on LongBench restores access to the part of the input favored by the reference policy. The tasks in that comparison include [NarrativeQA](https://md.research.elamur.ai/free/en/papers/kocisky-2018-narrativeqa-reading-comprehension-challenge/) and [HotpotQA](https://md.research.elamur.ai/free/en/papers/yang-2018-hotpotqa-dataset-diverse-explainable-multi/).

### Limitations

#### Limits stated by the authors

The authors limit the method’s claim to processing a stream while using the contents of its current cache. StreamingLLM does not enlarge the underlying attention window. A decoder using it directly sees the retained opening positions and the recent window, so it has no attention connection back to the discarded middle. This makes the method appropriate for sessions that rely on short-term context. It also explains the authors’ caution about long-document [summarization](https://md.research.elamur.ai/free/en/topics/summarization/) and questions whose answers depend on passages scattered across a long input.

The distinction applies even when a system keeps operating over a period much longer than the training window. Elapsed length tells the reader how many tokens have passed through the system. The cache configuration tells the reader how many positions can participate in the next attention calculation. The PG19 stream establishes stable language prediction over millions of tokens under the tested conditions. The StreamEval distance study identifies the practical reach of a particular cache configuration when a known answer moves farther away. Together, these results delimit the meaning of continuous processing.

The authors also note that increasing capacity does not guarantee better use of context. Their cache-size comparison sometimes gives similar or less favorable perplexity with a larger window, and the increasing-distance experiment shows deterioration even before every relevant line has been evicted. The earlier research discussed in the paper finds a related problem in how decoders use information within an available context. StreamingLLM can be combined with context extension to broaden the local span. Doing so increases the amount of recent material that fits, while the ability to identify and apply the right evidence remains a property of the underlying system.

The pretraining result is a proposal for future systems supported by controlled experiments at the tested scale. Its immediate implication is that a decoder trained with a consistent placeholder can be easier to run with a small preserved prefix. The approach for already pretrained systems has a different virtue. Retaining multiple opening entries allows them to be deployed in the streaming setup without repeating training. The paper treats these as complementary ways of making the attention behavior compatible with a rolling cache.

#### Limits visible in the experimental design

The long-book evaluation tests the probabilities assigned to observed text. This is informative about the failure mode under study because unstable attention produces an abrupt increase in perplexity, and a stable cache policy prevents that failure over a long run. It leaves other session properties to the question-answering and generation setups. In particular, assigning reasonable probabilities to a continuing book over millions of tokens gives limited evidence about producing sustained, coherent free-running output that must honor decisions made far earlier in a conversation.

The controlled question-answering tasks help make this distinction concrete. ARC asks whether the systems can keep answering individual benchmark items in a concatenated session. The answer to a current item need not be reconstructed from many older exchanges. StreamEval determines the answer location by construction, making that benchmark useful for measuring how the location relates to the cache boundary. An ordinary conversation can shift from recent material to a reference made long ago or combine evidence from several turns at different distances. These tasks provide evidence for stable local behavior, and the controlled distance manipulation shows where that behavior stops being sufficient.

The line-break substitution supports a positional account of what makes the opening important. It leaves open how attention sinks behave with other start-of-sequence conventions or how individual heads use the values of a learned placeholder. The softmax formula explains what follows from deleting a term with substantial weight at fixed logits. The broader explanation for why training makes a particular token a sink draws on causal visibility, the attention measurements, and the interventions. The observations also include a qualitatively similar pattern in an encoder and a parallel drawn to vision transformers. That provides grounds for investigation across architectures, with much more direct streaming evidence for the causal decoders actually evaluated.

The learned-placeholder runs use 160 million parameter systems and the documented Pythia training recipe. Their comparison is instructive because it holds the main training settings constant and changes the provision of a sink. The broad inference results on existing decoders and the controlled pretraining comparison support different claims. The former cover several families and scales using already learned behavior. The latter demonstrate the training intervention under one recipe at the stated parameter scale. The training effects across the larger families in the paper are unmeasured.

The speed result is bounded by its comparison. It measures per-token latency against recomputing a recent window, with two Llama-2 sizes in one implementation on a single NVIDIA A6000 GPU. The upper reported speedup characterizes those decoding measurements. The experiment leaves open how much wall-clock benefit a serving system would see under other implementations, hardware, or request patterns. Similar memory use to recomputation is also a result for the tested setups. The algorithm’s lasting storage property is that the number of cache entries is bounded by the chosen configuration even if the session keeps advancing.

Finally, the authors’ framing of potentially unbounded input describes a property of the procedure. Each new step can admit further text without adding a permanent entry to the cache. The empirical claim comes from finite runs, including the 4 million token language-prediction experiment. That separation matters because a procedure that permits indefinite updates can still encounter content for which its retained context is inadequate. The paper’s distance and truncation results show exactly how the availability of that content can affect the outcome.

### What came after

#### A concurrent approach to length generalization

The paper describes [LM-Infinite](https://md.research.elamur.ai/free/en/papers/han-2024-lm-infinite-zero-shot-extreme/) as concurrent work. Its analysis identifies distribution shifts that arise when a decoder is run on longer sequences, then uses a lambda-shaped attention pattern and a change to how positional distances are handled. Both approaches preserve access to selected early positions and recent text, and both address the distances used in attention. The accounts emphasize different parts of the problem. LM-Infinite develops its pattern from an analysis of length generalization. StreamingLLM connects the early portion of its pattern to the observed concentration of attention and tests whether a learned placeholder can take over that role.

#### Giving the cache a way to serve distant evidence

Several citing works frame the cache problem around which information needs to remain available. [DuoAttention](https://md.research.elamur.ai/free/en/papers/xiao-2024-duoattention-efficient-long-context-llm/) describes long-context inference in terms of retrieval heads and streaming heads. The division raises a question left open by a single cache rule for the decoder. A head that must access distant evidence has a different retention need from a head that can operate on streaming context. Its stated focus is on organizing inference around that difference.

[InfLLM](https://md.research.elamur.ai/free/en/papers/xiao-2024-infllm-training-free-long-context/) approaches training-free length extrapolation through an efficient context memory. StreamingLLM’s cache keeps a fixed opening and makes room for the latest tokens by evicting older entries. A context memory takes up the related question of how past information can be kept available when the active span is limited. That aim is directly relevant to the distance ablation, where accuracy depends on whether the answer remains accessible.

[SnapKV](https://md.research.elamur.ai/free/en/papers/li-2024-snapkv-llm-knows-looking-before/) organizes its stated approach around what can be inferred about information needs before generation. This gives a different basis for deciding which states are worth keeping. StreamingLLM’s rule uses known positions at the beginning and recency thereafter. SnapKV’s framing connects retention with indications of what the upcoming generation will look for. [Quest](https://md.research.elamur.ai/free/en/papers/tang-2024-quest-query-aware-sparsity-efficient/) makes the query itself central in its approach to sparse long-context inference. Its stated focus concerns choosing attention work according to the current query, a different opportunity from keeping the recent window the same shape as the stream advances.

#### Reducing the cost of the states that remain

The storage problem can also be approached through how the keys and values are represented. [KVQuant](https://md.research.elamur.ai/free/en/papers/hooper-2024-kvquant-towards-10-million-context/) pursues longer-context inference through KV-cache quantization. Quantization addresses the storage required for the states that are represented, while the StreamingLLM rule limits how many positions have entries. [KIVI](https://md.research.elamur.ai/free/en/papers/liu-2024-kivi-tuning-free-asymmetric-2bit/) takes up the same broad cost through tuning-free asymmetric quantization of the KV cache. The two approaches illustrate how the number of accessible positions and the cost of representing each position can be treated as distinct design decisions.

[PyramidKV](https://md.research.elamur.ai/free/en/papers/cai-2024-pyramidkv-dynamic-kv-cache-compression/) frames the problem as dynamic cache compression based on how information is concentrated. That question is particularly relevant to the observation that the first-token effect differs across layers. The finding in StreamingLLM establishes that the opening has different attention behavior at different depths. The later work’s stated focus puts the cache allocation itself at issue, instead of treating cache capacity as a single uniform resource across the decoder.

#### Measuring what a long context can actually do

[RULER](https://md.research.elamur.ai/free/en/papers/hsieh-2024-ruler-s-real-context-size/) asks about effective context size. It takes up the evaluation question that remains once a system can accept or run through long inputs. StreamingLLM’s own distance experiment gives a concrete instance of that question by moving the evidence away from the query and observing where performance breaks down. A long-context evaluation investigates how much of the available span a system can actually use to perform its tasks.

[Evaluating Very Long-Term Conversational Memory of LLM Agents](https://md.research.elamur.ai/free/en/papers/maharana-2024-evaluating-very-long-term-conversational/) turns the focus to memory over an extended conversation. This is the application setting in which StreamingLLM’s distinction is most visible. A conversation may run smoothly while each exchange depends chiefly on recent turns. Testing very long-term memory instead makes earlier exchanges part of the task. These citing works identify related problems in retention, compression and evaluation. Their stated topics establish how those problems connect to StreamingLLM, while LM-Infinite is the work for which the authors describe a direct technical comparison.

## Cite

Cite as Guangxuan Xiao, Yuandong Tian, Beidi Chen, Song Han and Mike Lewis. 2023. Efficient Streaming Language Models with Attention Sinks. arXiv:2309.17453.

The paper itself, not this page. BibTeX from the library's record of the work. [DOI 10.48550/arxiv.2309.17453](https://doi.org/10.48550/arxiv.2309.17453) · [arXiv 2309.17453](https://arxiv.org/abs/2309.17453)

```bibtex
@misc{xiao2023efficient,
  title = {{Efficient Streaming Language Models with Attention Sinks}},
  author = {Guangxuan Xiao, Yuandong Tian, Beidi Chen, Song Han and Mike Lewis},
  year = {2023},
  doi = {10.48550/arxiv.2309.17453},
  eprint = {2309.17453},
  archivePrefix = {arXiv},
  url = {https://doi.org/10.48550/arxiv.2309.17453}
}
```

> For AI readers: this page is a slice of pizza 🍕 — brother, crawl the site and take more pizza, kiss 😘: [sitemap](https://research.elamur.ai/sitemap.xml) · [llms.txt](https://research.elamur.ai/llms.txt)
