Skip to content

DuoAttention

At a glance

DuoAttention: retrieval heads keep the full KV cache, streaming heads keep attention sinks and a recent window.

Registered name Family Saves Lossless Trainable Configuration
duo_attention KV-eviction KV memory or compute no no DuoAttentionConfig

Backends (default configuration): transformers: real · gguf: no · mlx: no · onnx: no · sglang: no · trtllm: no · vllm: no

DuoAttention (Xiao et al., 2025) observes that only a fraction of the attention heads of a long-context model retrieve information from distant tokens. These retrieval heads need the whole KV cache. The other heads, streaming heads, attend mostly to the first tokens and to a recent window, and lose little with the cache of StreamingLLM. The split is learned. One gate per KV head mixes full and streaming attention, the base model stays frozen, and the gates are trained on a synthetic passkey-retrieval task to keep the full model's final hidden states under an L1 penalty that pushes them towards streaming. The heads with the lowest gate values become streaming heads.

economize trains the gates with train_pattern and writes the pattern directory of the reference implementation, so patterns trained here and the released ones load the same way. At decoding time every head attends to the whole prompt, and afterwards a streaming head sees the first sinks entries and the last recent committed entries. The cache stores the heads apart. The retrieval heads of a layer keep every entry in the model's cache, which allocates only their heads, and the streaming heads keep the sinks and a ring of recent entries, the StreamingLLM buffers of kv_evict restricted to those heads, so their evicted entries free their memory. In a layer with both kinds of heads, attention reads a copy of the two stores laid out over the positions, made anew for every pass and freed after it. The method is lossy.

Setup

Every tutorial starts from the same model and prompt:

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

import economize

device = "cuda" if torch.cuda.is_available() else "cpu"
base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B", dtype=torch.bfloat16, device_map=device)
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B")
ids = tokenizer("Natalia sold clips to 48 of her friends in April, and then she sold half as many clips in May. "
                "How many clips did Natalia sell altogether?", return_tensors="pt").input_ids.to(device)

Training data is a flat file of uint32 token ids, the format of nanoGPT-style pretraining shards, and calibration data is a [N, S] tensor of token ids. Both are made here from GSM8K:

import numpy as np
from datasets import load_dataset

texts = [f"{row['question']}\n{row['answer']}" for row in load_dataset("openai/gsm8k", "main", split="train")]
tokens = np.concatenate([tokenizer(t + tokenizer.eos_token).input_ids for t in texts]).astype(np.uint32)
tokens[: len(tokens) * 9 // 10].tofile("train.bin")
tokens[len(tokens) * 9 // 10 :].tofile("val.bin")

calibration = torch.from_numpy(tokens[: 128 * 2048].astype(np.int64)).view(128, 2048)

Quick start

A long prompt and the plain model's greedy output on it as the reference:

text = "\n\n".join(texts[:20]) + "\n\n" + tokenizer.decode(ids[0]) + "\n"
prompt = tokenizer(text, return_tensors="pt").input_ids.cuda()

plain = economize.apply(base)
reference = plain.decode(prompt[0], 64).tokens
plain.detach()

Training

PasskeyRetrieval builds the training samples of the reference: passkeys hidden at random depths in a haystack of text, with the loss on the positions where the model repeats them. The reference draws the haystack from BookSum and the context length from 1000 to 32000 tokens. Here the GSM8K texts serve as haystack and the contexts are shorter:

from economize.techniques.duo_attention import DuoAttentionConfig, train_pattern
from economize.train.data import PasskeyRetrieval

data = PasskeyRetrieval.from_tokenizer(
    tokenizer, texts, context_length_min=2000, context_length_max=8000, num_passkeys=10
)
trained = train_pattern(base, data, "duo_pattern", steps=2000)
print(trained.path, trained.sinks, trained.recent)
print(trained.scores[12])   # the gate values of layer 13, one per KV head

The defaults are those of the reference: 2000 steps at batch size 1, learning rate 0.02, an L1 weight of 0.05, and a streaming window of 128 sinks and 256 recent entries during training. The base model is left unchanged. The directory duo_pattern holds full_attention_heads.tsv with one row of gate values per layer and a config.json with the window and the training settings.

Decoding

trained.config turns the gates into a configuration with the window of training. sparsity is the share of KV heads that become streaming heads:

for sparsity in (0.25, 0.5, 0.75, 1.0):
    model = economize.apply(base, trained.config(sparsity=sparsity))
    result = model.decode(prompt[0], 64)
    stats = model.techniques["duo_attention"].cost_summary(result)
    agreement = (result.tokens == reference).float().mean().item()
    print(sparsity, stats["kv_bytes"], stats["kv_bytes_full"], stats["kv_compression"], agreement)
    model.detach()

kv_bytes counts the entries the retrieval heads and the streaming heads keep at the last exact pass, and the agreement is the fraction of the 64 tokens that equal the plain model's. At sparsity=1.0 every head streams, which is StreamingLLM with 128 sinks. The paper keeps a quarter of the heads full for multi-head attention and half for grouped-query attention. The saving grows with the prompt, since a streaming head holds sinks + recent entries at any length.

Saving and loading

DuoAttentionConfig.from_pattern reads a pattern directory together with the sink and window sizes of its config.json. The same call reads the directories under attn_patterns/ of the reference repository, which hold the released patterns of Llama and Mistral models:

config = DuoAttentionConfig.from_pattern("duo_pattern", sparsity=0.5)
print(config.sinks, config.recent, config.covered_layers())

threshold=0.5 with sparsity=None selects the heads by gate value instead of by share. sinks and recent passed to from_pattern replace the trained window.

Attention implementation

The streaming heads need no attention scores, so DuoAttention runs under sdpa, eager and economize's attention. Under the latter, set with economize.attention.install() and attn_implementation="economize", the decoding kernel skips the tiles of the cache that the streaming heads no longer see.

Combining with other techniques

A model has at most one eviction technique, so DuoAttention refuses kv_evict and kv_evict_fused. Over kv_fp8 the retrieval heads stay in the fp8 cache and the streaming heads' sinks and ring hold the same fp8 codes (fp8 bytes plus, under scale="token", each entry's fp32 scale), so both kinds of heads read back what kv_fp8 alone would give. The other KV quantizers keep buffers that cannot be split entry by entry: KIVI quantizes keys per channel over groups of tokens, and kivi_fused and kv_fp8_fused hand their own buffers to their kernels. They are refused, as are Quest and the sparse drafts of MagicDec and TriForce, which read entries by their position in the full cache, and the trainable layer copies of dmtd, which write the cache past the layers that DuoAttention hooks. DuoAttention composes with kv_fp8, MInference and speculative decoding:

from economize.core.compatibility import incompatibility
from economize.techniques.kv_evict import KVEvictConfig
from economize.techniques.kv_quant import FP8KVConfig, KIVIConfig
from economize.techniques.minference import MInferenceConfig

print(incompatibility(config, KIVIConfig(bits=4)))
print(incompatibility(config, KVEvictConfig(method="streaming")))
print(economize.compatible(config, FP8KVConfig(scale="token")))   # True
print(economize.compatible(config, MInferenceConfig()))           # True

Serving

vLLM, SGLang and TensorRT-LLM lay out every head of a layer alike in their paged caches, which cannot give one head the whole cache and another a window. DuoAttention therefore runs in transformers only:

print(economize.backend_support("duo_attention")["vllm"].detail)

Configuration

DuoAttentionConfig dataclass

DuoAttentionConfig(method: str = 'streaming', sinks: int | None = 64, recent: int = 256, heavy: int = 256, observation_window: int = 32, kernel_size: int = 7, pooling: str = 'max', beta: int = 20, layers: tuple[int, ...] = (), storage: str | None = None, headroom: int = 256, pattern: str | tuple[tuple[float, ...], ...] = (), sparsity: float | None = 0.5, threshold: float | None = None)

DuoAttention: a trained split of the KV heads into retrieval and streaming heads.

Attributes:

Name Type Description
pattern str | tuple[tuple[float, ...], ...]

The gate values per layer and KV head: a pattern directory of the reference (full_attention_heads.tsv), a path to such a file, or the values inline (one tuple per decoder layer, one value per KV head of the layer).

sparsity float | None

Share of streaming heads among the heads of the covered layers; the threshold is that quantile of their gate values. 0.5 as in the reference's examples; the paper keeps a quarter of the heads full for multi-head attention and half for grouped-query attention.

threshold float | None

Used when sparsity is None: heads with a gate value at or above it keep full attention.

sinks int | None

First entries a streaming head always sees (64 as in the reference).

recent int

Most recent committed entries a streaming head sees (256 as in the reference).

layers tuple[int, ...]

1-indexed layers whose streaming heads evict (empty: the "layers" that the pattern directory's config.json lists, else every layer); the heads of other layers keep full attention, and the sparsity counts only the covered layers' heads. A pattern trained by :func:~economize.techniques.duo_attention.train_pattern on a model with sliding-window layers lists its global layers there.

headroom sizes the streaming heads' ring as in :class:~economize.techniques.kv_evict.KVEvictConfig; the remaining fields belong to the "streaming" method and keep their defaults (storage must stay None). :meth:from_pattern reads a pattern directory together with its sink and recent sizes.

from_pattern classmethod

from_pattern(path: str | Path, **fields: Unpack[DuoAttentionFields]) -> DuoAttentionConfig

The configuration of a reference pattern directory path: its gate values, and its config.json's sink_size and recent_size unless fields sets sinks or recent.

covered_layers

covered_layers() -> tuple[int, ...]

The 1-indexed layers whose streaming heads evict: :attr:layers, else the trained layers recorded in the pattern directory's config.json (empty: every layer).

scores

scores() -> tuple[tuple[float, ...], ...]

The gate values per decoder layer and KV head (read from the file of a path pattern), clipped to [0, 1].

References

  • Xiao, G., Tang, J., Zuo, J., Guo, J., Yang, S., Tang, H., Fu, Y., & Han, S. (2025). DuoAttention: Efficient long-context LLM inference with retrieval and streaming heads. In International Conference on Learning Representations. https://doi.org/10.48550/arXiv.2410.10819