Introduction
Modern serving engines make long prompts cheap by reusing past computations. More specifically, the engine saves the intermediate computed KV tensors for every token in a memory bank called the KV cache. When a future request begins with those exact same tokens, the engine simply grabs the saved cache and skips the heavy initial processing (“prefill”) for that part. A system prompt shared by many requests is a typical example. Both vLLM’s prefix caching and SGLang’s RadixAttention use this idea to accelerate inference.
However, the condition for a cache hit is strict. Under causal attention, a token’s KV can be reused only if its entire prefix is identical to the saved one, in both content and order. The reason is that the keys and values of a token depend on every token before it:
Here k_i and v_i are the key and value of token i in any layer after the first, and x_1, …, x_i are all tokens up to i. Change any earlier token, and the KV of token i changes too.
Agentic tasks are now common, and their multi-turn tool use brings a new problem. Consider this agent serving case:
In an agentic search case, let’s suppose agents receive multi-turn requests from different users, and all of them need to read Document 17. They retrieve the same text, yet each agent builds its own KV cache for Document 17, because each has a different history (prefix). In practice, documents are long and noisy, and only a small part of each one matters for the current request. In that case, do we still need a separate KV cache for every agent? Is it possible that compute the KV cache for Document 17 once, and let every other agent load it and use it directly? Ideally, that gives us a “cache of KV caches”.
Before we show how, let’s check that this kind of reuse is common in agent workloads.
How often do agents read the same content?
We measure this on real agent trajectories. We match tool results by exact text and count tokens. A token is a repeat if the tool result it belongs to appeared before. We split the repeats by where the earlier copy comes from:
- Within a trace: the same agent read it earlier in its own trajectory.
- Across attempts, same question: another attempt at the same question read it. RL training and test-time sampling run many attempts per question.
- Across questions: an agent working on a different question read it.
For coding, we also split by repository: across tasks in the same repository, and across repositories.
Repeats are common in all three workloads (Figure 1). In our search training data, 68.1% of retrieved document tokens are repeats. Most come from other attempts at the same question (50.9%), and many from other questions (15.4%). On BrowseComp-Plus, a long-horizon research benchmark, repeats reach 92.0%, and half of all document tokens (46.5%) repeat inside the agent’s own trace. Coding agents show the same pattern: 48.1% of tool-result tokens repeat. However, current serving engines still compute the KV of every copy from scratch.
Experimental setup
- Search: 297,720 correct Qwen3-32B trajectories on 104,159 NQ and HotpotQA questions (our mid-training data), and 3,320 Qwen3.5-9B trajectories on BrowseComp-Plus (830 questions × 4 attempts).
- Coding: 4,000 Qwen3.5-9B attempts on 1,000 SWE-smith Python tasks from 50 repositories, all outcomes kept.
- Matching: exact text match for documents, exact prefix match for coding tool results.
Localized attention
Causal attention
These repeated tool results suggest a simple idea. Remove each tool result’s dependency on its prefix, and let it attend only to itself.
The figure below shows our one-step change: a mask around each tool result. We call it localized attention. Each tool result attends only to itself, while every token the agent writes still attends to everything before it. The KV of a tool result then depends only on its own tokens, so it can be computed once, stored, and loaded into any agent’s context at any position. The condition for reuse moves from the same prefix to the same text. By contrast, in full causal attention, every token of the tool result attends to the whole context before it.
One detail is RoPE, and it is easy to handle: we rotate each key from its old position to its new one. In production, we cache the KV before RoPE and apply RoPE at load time.
Here k̃_i is the key of the i-th tool-result token before RoPE. R_s, R_i and R_{s+i} are the RoPE rotations for positions s, i and s+i. A key cached before RoPE gets R_{s+i}. A key cached with RoPE at position i gets R_s. Values carry no position, so they are copied as they are.
Linear-attention
Hybrid models add a new kind of layer. For example, Qwen3.5-9B has 32 layers, and 24 of them are Gated DeltaNet layers, which carry a recurrent state instead of attending. There is no mask to edit, so we make a tool result local in a different way (Figure 3). The trajectory’s state simply skips each tool result. Take documents as an example: the first token after a document continues from the state of the last token before it. The document itself runs its own short recurrence, starting from a zero state, and that state is dropped when the document ends.
Documents and think tokens exchange information only through the attention layers. In the first three DeltaNet layers, the tokens after a document have not seen it at all. Think tokens first read the document at layer 4, by attending to its keys and values. From then on, they carry the document’s information.
Note: this is a first try. Better methods likely exist, and we will try others, such as averaging states.
Related Work
KV eviction and selection methods also try to make inference more efficient. Sparse attention methods such as Quest, NSA, MoBA and DeepSeek Sparse Attention let each query read a small part of the context. Eviction methods such as H2O, StreamingLLM, SnapKV and R-KV keep only the highest-scoring tokens and stay accurate. One recent paper, Random Attention, goes further. It keeps the prompt and drops the other tokens at random in each head. Even with no scoring rule, it matches the best scoring method at about 4× compression, with 32–43% higher throughput in vLLM. This further shows that causal attention makes tokens highly redundant. Each token’s information is also stored in every token after it.
The closest work is Block-Attention. It uses the same idea as ours: each document attends only to itself. It targets retrieval-augmented generation (RAG), where the documents sit at the front of the prompt and the model answers one question in one turn. Agents are harder. Tool results arrive in the middle of the trajectory, turn after turn. KVLink also reuses a document’s KV outside its prefix. It adds trainable special tokens that let the documents attend to each other again. We only change the attention mask and train the model with it.
In this post we focus on one agent setting: search. Here the tool results are retrieved documents. We plan to extend this to other agent settings, such as coding and more general tasks.
Can a model use localized attention without training?
We hope a model can work with localized attention out of the box. To test this, we take models trained with full attention and switch them to localized attention at inference time. We evaluate them on 1,200 search questions (HotpotQA, NQ and 2WikiMultihopQA), 3 samples each. Accuracy drops sharply (Figure 5): Qwen3-1.7B falls from 0.345 to 0.082, Qwen3-4B from 0.460 to 0.336, and Qwen3.5-9B from 0.487 to 0.175.
We then test whether in-domain training helps. We train the off-the-shelf models on the search task with full attention: mid-training first, then RL with the Search-R1 recipe. The trained models are much stronger in domain, but their accuracy drops sharply once we switch them to localized attention (Figure 5, right). So the model has to learn how to read localized KV.
Experimental setup
- Models: Qwen3-1.7B, Qwen3-4B and Qwen3.5-9B as released, and the same models after in domain training (mid-training, then RL with the Search-R1 recipe).
- Task: a search agent for multi-hop questions. It searches wiki-18 with an e5-base-v2 retriever, gets 5 documents per search, and searches at most 10 times, in a 16,384-token context.
- Train set: mid-training uses 297,720 correct Qwen3-32B search trajectories on 104,159 NQ and HotpotQA questions. RL uses 32,000 other questions from the same pool.
- Test set: 1,200 in-distribution questions (HotpotQA, NQ and 2WikiMultihopQA), 3 samples each, run on SGLang.
- Localized attention at inference: each retrieved document attends only to itself, and every other token attends to everything before it.
- Accuracy: Qwen3.5-9B judges each final answer against the gold answers.
Training
Setup
We train in two stages: mid-training, then RL. The mid-training corpus comes from a teacher, Qwen3-32B in thinking mode. It answers 128,875 NQ and HotpotQA questions four times each, searching wiki-18 with an e5 retriever. We keep the 297,720 trajectories that search at least once and reach a correct answer. Mid-training runs one epoch over this corpus. RL then follows the Search-R1 recipe with GRPO. It runs 300 steps on 32,000 other questions from the same pool. Each step samples 16 rollouts for each of 56 questions, and the reward is 1 when the judge marks the final answer correct.
We first train two runs from the same base model, one with full attention and one with localized attention, and evaluate every checkpoint in both full attention and localized attention modes.
Localized attention adds no training cost. In training it is one FlexAttention block mask: each packed trajectory and each document sees only itself. On Qwen3-1.7B with 8 H200s, the median step takes 0.967 s with localized attention and 0.993 s with full attention, and peak memory is 116.4 GiB for both. RL rollouts and evaluation run on SGLang, with the mask in prefill and FA3 in decode.
Training details
| Parameter | Value |
|---|---|
| Mid-training teacher | Qwen3-32B, thinking mode |
| Mid-training trajectories | 297,720 |
| Mid-training questions (NQ and HotpotQA) | 104,159 |
| Mid-training tokens, Qwen3 tokenizer | 684.86M |
| Mid-training tokens, Qwen3.5 tokenizer | 725.73M |
| Mid-training epochs | 1 |
| Mid-training steps, Qwen3-1.7B and Qwen3-4B | 4,763 |
| Mid-training steps, Qwen3.5-9B | 5,064 |
| Mid-training batch (packed sequences per step) | 8 |
| Packed sequence length (tokens) | 18,432 |
| Mid-training optimizer | Muon (decoder matrices) and AdamW (the rest) |
| Mid-training learning rate | 2e-5, cosine |
| RL algorithm | GRPO, Search-R1 recipe |
| RL questions (NQ and HotpotQA, not in mid-training) | 32,000 |
| RL steps | 300 |
| Prompts per RL step | 56 |
| Samples per prompt | 16 |
| RL learning rate | 1e-6 |
| RL reward | 1 if the judge marks the final answer correct, else 0 |
| Search corpus and retriever | wiki-18, e5-base-v2 |
| Documents per search | 5 |
| Searches per question, at most | 10 |
| Context length (tokens) | 16,384 |
| Step | Content |
|---|---|
| Question | Who was president of the United States in the year that Citibank was founded? |
| Search 1 | Citibank founding year |
| Documents | 5 documents, each encoded on its own: Citibank was founded in 1812 … |
| Search 2 | President of the United States in 1812 |
| Documents | 5 documents: … James Madison, the incumbent President … |
| Answer | James Madison |
A shortened rollout example of the training data.
The test sets are 1,200 in-distribution questions (HotpotQA, NQ and 2WikiMultihopQA, 3 samples each), 1,025 out-of-distribution questions (Bamboogle, FEVER, MuSiQue and PopQA, 1 sample each), and GSM8K and MATH-500 without tools. Qwen3.5-9B judges each final answer against the gold answers.
Results
We find that training with the mask recovers most of the accuracy. Most of this happens in mid-training. After it, the model has largely learned to reason with localized attention, and RL mainly raises performance further (Figure 6). At 1.7B a gap to the baseline remains after RL. At 4B the gap nearly closes, both in and out of distribution, so within Qwen3 the gap shrinks as the model grows. Interestingly, the localized model also keeps working with full attention. In Figure 6 the dashed red line is our deployed setting, and the solid red line is the same model evaluated with full attention. The two stay close, so one checkpoint serves both modes.
Math checks general ability. It has no documents, so the mask never applies. For smaller models, training on search data costs some math accuracy compared with the base model. Compared with full-attention training, localized training keeps math accuracy about the same (Figure 7).
Qwen3.5-9B
We show the training curves of Qwen3.5-9B on their own (Figure 8). In our setting, accuracy keeps rising with training, through both mid-training and RL. One point worth noting is that for the Qwen3.5-9B model trained with full attention, the gap between full and localized attention is large, and it grows during RL. Its accuracy in localized mode falls from 0.456 to 0.337, while its full-attention accuracy keeps rising.
After RL, the gap between our setting and the baseline is a little larger at 9B than at 4B. We see two possible reasons. First, our rule for the linear-attention layers (Figure 3) may not be the best one. Second, our training data may not be enough for a 9B model.
Analysis: what training changes
Which part of the model does training change? To find out, we take three Qwen3-1.7B checkpoints: the base model, the model mid-trained with full attention (Full-Mid), and the model mid-trained with localized attention (Localized-Mid). We score each model by its localized-KV penalty:
NLL is the model’s loss, in nats per token, on the first 256 reasoning tokens after each retrieval. We compute it twice, once with the documents localized and once with them fully encoded, on the same 200 questions for every model. A penalty of 0 means the model reads localized documents as well as full ones.
In each matrix of Figure 9, the diagonal is a checkpoint in its own setting. Every other cell replaces one part of the row’s model with the same part from the column’s checkpoint: the reader’s MLPs in the left matrix, and the encoder that writes the document KV in the right one.
Take the Base row on the left as an example. The base model’s own penalty is 0.290. With the MLPs from Full-Mid, it rises to 0.381. With the MLPs from Localized-Mid, it falls to 0.073. So localized training makes the MLPs better suited to localized attention, and swapping in these weights alone helps the base model adapt to it.
The right matrix gives a second example. Take the Base row again: the base model’s own penalty is 0.290. When it reads document KV written by Full-Mid, the penalty drops to 0.029. When it reads document KV written by Localized-Mid, the penalty rises to 0.304. So the KV a model writes depends on how it was trained. Full-Mid writes KV that the base model can use, while Localized-Mid writes KV suited to a reader trained with localized attention.
Together, the two matrices show that localized training changes mostly the reader. Its MLPs learn to work with localized documents, and the trained reader can use document KV from any of the three encoders. Our hypothesis is that with full attention, every document token sees the question, so the question is already mixed into the document KV. With localized attention it is not, so the reader’s MLPs learn to do this mixing more heavily during reasoning.
Efficiency: copy the KV instead of computing it
Once a document, or any tool result, is localized, its KV no longer depends on the conversation. So an agent can get the KV in two ways (Figure 10). It can compute the KV in place with localized prefill, where each document attends only to itself. Or it can retrieve a stored KV that was computed once: rotate the keys to the agent’s positions, then write keys and values into its KV cache.
Setup
We measure both ways. To compute, we prefill the documents on SGLang with localized attention and compare it with full attention on FlashAttention-3 as the baseline. We also include full attention on FlexAttention as an unoptimized baseline. To copy, we load stored KV from GPU memory, CPU memory, a network file system or a local disk, and write it into each agent’s KV cache.
Benchmark details
- One H200 GPU, SGLang 0.5.23 with radix (prefix) caching.
- N agents run at once, with N from 1 to 512. Each agent already has a 4,096-token context in cache.
- Each agent takes in one search result: 5 documents, 830 tokens on average.
- We time how long it takes until the documents’ KV sits in GPU memory for all N agents (TTFT). We report the median of 3 runs.
- The copy runs in plain PyTorch, outside the serving engine.
Copying is 8–15× faster than prefill
Copying is much faster than prefill (Figure 11). With 512 agents, copying from GPU memory is 8–15× faster than full-attention prefill and comes close to SGLang’s floor, the time to serve the same requests when every token is already cached. Even copying from CPU memory is several times faster. The larger model gains more, because its prefill compute grows faster than its KV size.
Where to keep the KV
Stored KV is large. By our estimation, saving all of wiki-18 documents as KV cache would need about 500 TB on Qwen3-4B. Instead, we propose keeping a hot set of document KV with an LRU policy. On a hit, the agent retrieves the stored KV. On a miss, it computes the KV in place and adds it to the hot set, so that later requests can retrieve it.
What’s next
We will keep applying localized attention to more tasks, including search, coding and open-ended agent tasks. We will also train on more data, move to harder tasks with longer contexts and more turns, and measure efficiency on more serving systems.
Citation
@misc{localizedattention2026,
title = {Accelerating KV Cache Reuse through Localized Attention},
author = {Xiaochuan Li},
year = {2026},
note = {Blog post}
}