SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2309.17453 · ICLR · 2024

Efficient Streaming Language Models with Attention Sinks

Song Han, Mike Lewis, Beidi Chen, Yuandong Tian, Guangxuan Xiao

arXiv · PDF · Open in the Atlas

Code that ran

8 of 11 samples (functions and classes) lifted from this paper's linked repositories executed on a synthesized input in Syntology's jail (4 of them constructed an object rather than computing a result; 0 honoured the contract we drafted, 0 violated it and 4 have no contract verdict; 4 failures of our instrument; 3 no recorded run), measured 2026-11-23; repository links from the Papers with Code archive attributed under CC BY-SA, no affiliation; bodies inline only under a permissive licence as GitHub detects it. Not a reproduction of the paper's results.

"Ran" means the function executed on a synthesized input and returned a value. It is not a reproduction of the paper's results. This record, dated, as JSON: /api/ran/2309.17453.json · badge: /api/ran/2309.17453.svg

Each repository's role is a label: a classifier's output recorded on the link, or, where no role is recorded, what the Papers with Code archive marked. The line under it names its basis. Neither says who wrote the code.

RepositoryRoleRan
mit-han-lab/streaming-llm canonical (classifier label)
classifier basis: classifier_2025
5 ran · 0 no recorded run
squeezeailab/kvquant community
Papers with Code archive
1 ran · 1 no recorded run
tomaarsen/attention_sinks community
Papers with Code archive
1 ran · 0 no recorded run
intel/intel-extension-for-transformers application (classifier label)
classifier basis: classifier_2025
1 ran · 0 no recorded run
answerdotai/cold-compress community
Papers with Code archive
0 ran · 2 no recorded run
FunctionStatusWhere it lives
AttentionSinkKVCache Ran
ran on a synthesized input · constructed an object; no result was computed
tomaarsen/attention_sinks/attention_sinks/attention_sink_kv_cache.py
code served (permissive licence) · get_code("221a10d8ed175d74")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned an instance of its own class, AttentionSinkKVCache: the run constructed the object and did not call it, so no result was computed. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
from dataclasses import dataclass

torch.manual_seed(0)

# Create sample past_key_values structure
# past_key_values is a list of [k, v] pairs where k and v are tensors
# Based on the code, k and v have shape [batch, seq_len, ...] with seq_dim controlling which dimension is seq_len
batch_size = 2
seq_len = 1500
head_dim = 4
num_heads = 3

# Create tensors with seq_len at dimension 2 (k_seq_dim and v_seq_dim default to 2)
k_tensor = torch.randn(batch_size, num_heads, seq_len, head_dim)
v_tensor = torch.randn(batch_size, num_heads, seq_len, head_dim)

past_key_values = [[k_tensor, v_tensor], [k_tensor, v_tensor]]

ARGS = {
    "attention_sink_size": 4,
    "attention_sink_window_size": 1020,
    "k_seq_dim": 2,
    "v_seq_dim": 2,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type AttentionSinkKVCache — the run constructed an instance of its own class and did not call it; no shape is stated — the instrument coerces any output to an array; for a AttentionSinkKVCache output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
H2OKVCache Ran
ran on a synthesized input · constructed an object; no result was computed
intel/intel-extension-for-transformers/intel_extension_for_transformers/transformers/kv_cache_compression/prune/h2o.py
code served (permissive licence) · get_code("c2fd5f6408017e25")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned an instance of its own class, H2OKVCache: the run constructed the object and did not call it, so no result was computed. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch

torch.manual_seed(0)

# Create small tensors for testing
batch_size = 2
num_heads = 2
seq_len = 10
head_dim = 4

# attn_score: shape (batch, num_heads, seq_len, seq_len) or similar
attn_score = torch.randn(batch_size, num_heads, seq_len, seq_len)

# key_states: shape (batch, num_heads, seq_len, head_dim)
key_states = torch.randn(batch_size, num_heads, seq_len, head_dim)

# value_states: shape (batch, num_heads, seq_len, head_dim)
value_states = torch.randn(batch_size, num_heads, seq_len, head_dim)

# Create H2OKVCache instance with test arguments
cache = torch.nn.Module()  # placeholder to avoid instantiation issues

# Define ARGS for H2OKVCache.__init__
ARGS = {
    "heavy_ratio": 0.2,
    "recent_ratio": 0.2,
    "heavy_budget": None,
    "recent_budget": None,
    "min_seqlen": -1,
    "mean": False,
}

# For __call__, we would pass:
# cache(attn_score, key_states, value_states)
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type H2OKVCache — the run constructed an instance of its own class and did not call it; no shape is stated — the instrument coerces any output to an array; for a H2OKVCache output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
SinkCache Ran
ran on a synthesized input · constructed an object; no result was computed
squeezeailab/kvquant/gradients/src/transformers/cache_utils.py
pointer only (licence: NONE) · get_code("a71a6943a9cf9d4b")
How it ran

The body of this sample is withheld: GitHub detected no licence in this paper's repository, squeezeailab/kvquant when it was checked. The setup block that called it is withheld with it, because it is written against that body. source_path and origin say where the code lives, to read under the repository's own terms. A run is recorded.

StartRecentKVCache Ran
ran on a synthesized input · constructed an object; no result was computed
mit-han-lab/streaming-llm/streaming_llm/kv_cache.py
code served (permissive licence) · get_code("465929486ee1650b")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned an instance of its own class, StartRecentKVCache: the run constructed the object and did not call it, so no result was computed. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch

torch.manual_seed(0)

ARGS = {
    "start_size": 4,
    "recent_size": 512,
    "k_seq_dim": 2,
    "v_seq_dim": 2,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type StartRecentKVCache — the run constructed an instance of its own class and did not call it; no shape is stated — the instrument coerces any output to an array; for a StartRecentKVCache output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
greedy_generate Ran
ran; our contract draft was wrong, not the code
mit-han-lab/streaming-llm/examples/run_streaming_llama.py
code served (permissive licence) · get_code("0a11ee057df336ca")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1) and returned list, ndim 6, dtype family float; no output shape is stated. The image it ran in was not recorded. If your copy returns the same type and ndim on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn as nn

torch.manual_seed(0)

# Build a minimal model that satisfies the function's usage
class MinimalLM(nn.Module):
    def __init__(self, vocab_size=100, hidden_dim=4, num_layers=2):
        super().__init__()
        self.embedding = nn.Embedding(vocab_size, hidden_dim)
        self.lm_head = nn.Linear(hidden_dim, vocab_size)
        self.num_layers = num_layers
        
    def forward(self, input_ids, past_key_values=None, use_cache=False):
        # input_ids shape: (batch_size, seq_len)
        x = self.embedding(input_ids)  # (batch_size, seq_len, hidden_dim)
        
        # Simulate transformer output
        x = x.mean(dim=1, keepdim=True)  # (batch_size, 1, hidden_dim)
        logits = self.lm_head(x)  # (batch_size, 1, vocab_size)
        
        # Create mock past_key_values (list of tuples for each layer)
        if use_cache:
            past_key_values = [
                (torch.randn(2, 4, 4, 4), torch.randn(2, 4, 4, 4))
                for _ in range(self.num_layers)
            ]
        
        class Output:
            pass
        
        output = Output()
        output.logits = logits
        output.past_key_values = past_key_values
        return output

# Build a minimal tokenizer
class MinimalTokenizer:
    def __init__(self):
        self.eos_token_id = 2
        self.vocab = {i: f"token_{i}" for i in range(100)}
        self.vocab[2] = "</s>"
    
    def decode(self, token_ids, skip_special_tokens=False, clean_up_tokenization_spaces=False, spaces_between_special_tokens=False):
        words = []
        for tid in token_ids:
            if tid == 2 and skip_special_tokens:
                continue
            words.append(self.vocab.get(tid, f"unk_{tid}"))
        return " ".join(words)

# Create instances
model = MinimalLM(vocab_size=100, hidden_dim=4, num_layers=2)
tokenizer = MinimalTokenizer()
input_ids = torch.tensor([[5, 10, 15]], dtype=torch.long)  # (batch_size=1, seq_len=3)
past_key_values = None
max_gen_len = 5

ARGS = {
    "model": model,
    "tokenizer": tokenizer,
    "input_ids": input_ids,
    "past_key_values": past_key_values,
    "max_gen_len": max_gen_len,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type list, ndim 6, dtype family float — a list output has no array shape of its own; none is stated
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
slice1d Ran
ran; our contract draft was wrong, not the code
mit-han-lab/streaming-llm/streaming_llm/kv_cache.py
code served (permissive licence) · get_code("2564045c0e65006b")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned Tensor, ndim 3, dtype family float, shape (2, 2, 3) as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn as nn

torch.manual_seed(0)

# The function slices a tensor along dimension 1
# x is indexed with [:, start:end, ...] so it should be a tensor
# start and end are integers for slicing

x = torch.randn(2, 4, 3)  # batch=2, dim1=4, dim2=3
start = 1
end = 3

ARGS = {
    "x": x,
    "start": start,
    "end": end,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Tensor, ndim 3, dtype family float, shape (2, 2, 3) — shape (2, 2, 3) as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
slice2d Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
mit-han-lab/streaming-llm/streaming_llm/kv_cache.py
code served (permissive licence) · get_code("19c86edfcb34276c")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned Tensor, ndim 4, dtype family float, shape (2, 4, 4, 6) as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch

torch.manual_seed(0)

# Create a 4D tensor: (batch=2, channels=4, height=8, width=6)
x = torch.randn(2, 4, 8, 6)

# Define start and end indices for slicing along dimension 2 (height)
start = 2
end = 6

ARGS = {
    "x": x,
    "start": start,
    "end": end,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Tensor, ndim 4, dtype family float, shape (2, 4, 4, 6) — shape (2, 4, 4, 6) as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
slice3d Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
mit-han-lab/streaming-llm/streaming_llm/kv_cache.py
code served (permissive licence) · get_code("8884022644d5af82")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned Tensor, ndim 5, dtype family float, shape (2, 4, 3, 3, 6) as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn as nn

torch.manual_seed(0)

# The function slices a tensor along dimension 3 (the 4th dimension)
# It expects x to be a multi-dimensional tensor
# start and end are integer indices for slicing

# Create a 5D tensor (batch, channels, depth, height, width)
# Using distinct sizes: batch=2, channels=4, depth=3, height=5, width=6
x = torch.randn(2, 4, 3, 5, 6)

# Define start and end indices for slicing dimension 3
start = 1
end = 4

ARGS = {
    "x": x,
    "start": start,
    "end": end
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Tensor, ndim 5, dtype family float, shape (2, 4, 3, 3, 6) — shape (2, 4, 3, 3, 6) as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
Cache Not yet run
unverified (harvested, no recorded run)
squeezeailab/kvquant/gradients/src/transformers/cache_utils.py
pointer only (licence: NONE) · get_code("1b72723f50079a16")
How it ran

The body of this sample is withheld: GitHub detected no licence in this paper's repository, squeezeailab/kvquant when it was checked. The setup block that called it is withheld with it, because it is written against that body. source_path and origin say where the code lives, to read under the repository's own terms. No invocation recorded.

KVCacheHeadConstant Not yet run
unverified (harvested, no recorded run)
answerdotai/cold-compress/cache.py
code served (permissive licence) · get_code("ae661478c5529ea2")
How it ran

no invocation recorded.

KVCacheRecentGlobal Not yet run
unverified (harvested, no recorded run)
answerdotai/cold-compress/cache.py
code served (permissive licence) · get_code("87d089c843ae1768")
How it ran

no invocation recorded.

Also present in other papers' code

Of 11 samples lifted from this paper's linked repositories, 11 carry a function identity and 0 do not. Of the 11 distinct functions with an identity, 5 are also present in other papers whose code we hold (0 with at least one paper dated earlier, 4 the same month, 4 later) and 6 are only here among the 52,977 papers whose code Syntology holds (as of 2026-09-26).

Only here means: among the 52,977 papers whose code Syntology holds (51,887 with lifted samples, 1,090 through their assemblies only), as of 2026-09-26, no other paper's lifted samples or current assembly bricks contain an identical function body after normalisation.

FunctionAlso present inEarliest-datedOthers named
slice1d
brick of this paper's assembly: helper
4 other papers
1 the same month, 3 later · 1 only as an assembly brick
2309.14717 (2023-09)
QA-LoRA: Quantization-Aware Low-Rank Adaptation of Large Language Models
2407.18121 (2024-07)
Efficient Inference of Vision Instruction-Following Models with Elastic Cache
2412.03409 (2024-12)
PrefixKV: Adaptive Prefix KV Cache is What Vision Instruction-Following Models Need for Efficient Generation
and 1 more not named here
slice2d
brick of this paper's assembly: helper
4 other papers
1 the same month, 3 later · 1 only as an assembly brick
2309.14717 (2023-09)
QA-LoRA: Quantization-Aware Low-Rank Adaptation of Large Language Models
2407.18121 (2024-07)
Efficient Inference of Vision Instruction-Following Models with Elastic Cache
2412.03409 (2024-12)
PrefixKV: Adaptive Prefix KV Cache is What Vision Instruction-Following Models Need for Efficient Generation
and 1 more not named here
slice3d
brick of this paper's assembly: helper
4 other papers
1 the same month, 3 later · 1 only as an assembly brick
2309.14717 (2023-09)
QA-LoRA: Quantization-Aware Low-Rank Adaptation of Large Language Models
2407.18121 (2024-07)
Efficient Inference of Vision Instruction-Following Models with Elastic Cache
2412.03409 (2024-12)
PrefixKV: Adaptive Prefix KV Cache is What Vision Instruction-Following Models Need for Efficient Generation
and 1 more not named here
Cache
brick of this paper's assembly: helper
1 other paper
1 later
2412.00876 (2024-12)
Dynamic-LLaVA: Efficient Multimodal Large Language Models via Dynamic Vision-language Context Sparsification
greedy_generate 1 other paper
1 the same month
2309.12307 (2023-09)
LongLoRA: Efficient Fine-tuning of Long-Context Large Language Models

Presence, not direction: an identical function body in two papers' repositories does not say who wrote it, which came from which, or that either paper's method rests on it. Matching is exact after normalisation, so a renamed or edited function is not matched. Dates are when papers appeared, not when code was written. Only .py files the harvester lifted are covered; notebooks are not read. A new-style arXiv id YYMM.NNNN dates a paper to the month 20YY-MM; otherwise Paper.year dates it to the year; otherwise it is undated. Dates are when the paper appeared, not when the code was written. Read 2026-11-23.

Repositories linked to this paper

Some links come from the archived Papers with Code dataset (CC BY-SA 4.0): attribution and licence.

Abstract

Deploying Large Language Models (LLMs) in streaming applications such as multi-round dialogue, where long interactions are expected, is urgently needed but poses two major challenges. Firstly, during the decoding stage, caching previous tokens' Key and Value states (KV) consumes extensive memory. Secondly, popular LLMs cannot generalize to longer texts than the training sequence length. Window attention, where only the most recent KVs are cached, is a natural approach -but we show that it fails when the text length surpasses the cache size. We observe an interesting phenomenon, namely attention sink, that keeping the KV of initial tokens will largely recover the performance of window attention. In this paper, we first demonstrate that the emergence of attention sink is due to the strong attention scores towards initial tokens as a "sink" even if they are not semantically important. Based on the above analysis, we introduce StreamingLLM, an efficient framework that enables LLMs trained with a finite length attention window to generalize to infinite sequence length without any fine-tuning. We show that StreamingLLM can enable Llama-2, MPT, Falcon, and Pythia to perform stable and efficient language modeling with up to 4 million tokens and more. In addition, we discover that adding a placeholder token as a dedicated attention sink during pre-training can further improve streaming deployment. In streaming settings, StreamingLLM outperforms the sliding window recomputation baseline by up to 22.2× speedup. Code and datasets are provided in the link.

For agents

The same record, over MCP at https://syntology.ai/mcp:

get_harvested_code_for_paper("2309.17453")
get_code_for_paper("2309.17453")
have("2309.17453")

The run record, dated, one paper per request, free:

curl https://syntology.ai/api/ran/2309.17453.json

A badge for a README (the split and the date, never a ratio):

[![Syntology run record](https://syntology.ai/api/ran/2309.17453.svg)](https://syntology.ai/paper/2309.17453)

Connect an agent — have() is free.