Learning how to Forget: Fine-tuning for Long-Context Sparse Attention
Summary
This paper presents a novel method for fine-tuning transformer language models with sparse attention to enable efficient long-context inference, often outperforming models trained with exact attention, and introduces an efficient implementation and a new open-source library.
View Cached Full Text
Cached at: 08/21/26, 10:14 AM
# Learning how to Forget: Fine-tuning for Long-Context Sparse Attention
Source: [https://arxiv.org/html/2608.19920](https://arxiv.org/html/2608.19920)
Matthias SeegerNote:Correspondence tomseeger@gmail\.comAffiliation:Amazon Web ServicesEmail:[mseeger@gmail\.com](mailto:)Vihang PatilAffiliation:AmazonEmail:[pvihang@amazon\.de](mailto:)Konstantinos BenidisAffiliation:Amazon Web ServicesEmail:[kbenidis@amazon\.de](mailto:)Sebastian SchelterAffiliation:Technical University BerlinEmail:[schelter@tu\-berlin\.de](mailto:)
###### Abstract
A lot of prior work addressed key\-value \(KV\) cache selection and compression by sparse attention to enable long\-context inference for transformer language models without excessive hardware budgets\. We provide a new method for fine\-tuning models with sparse attention\. It works for any KV cache policy, runs on a moderate hardware budget \(e\.g\., a single Nvidia A100 GPU with 40 GB RAM\), and allows the model to co\-adapt with the policy, often outperforming models trained with exact attention \(sequence parallelism\)\. We also provide an efficient implementation of H2O sparse attention \(the leading policy in our experiments\) with dedicated scaled dot product attention kernel support\.[πΊππ’ππ°πππ
πππππ\\mathtt\{KeysAndValues\}](https://github.com/awslabs/keys_values), a new open source library for long\-context inference and fine\-tuning, provides easy\-to\-use and performant code for all methods discussed here\.
## 1Introduction
Modern large language models need to process very long contexts \(i\.e\., number of tokens\) for calling many tools with sizable outputs\([51](https://arxiv.org/html/2608.19920#bib.bib43);[17](https://arxiv.org/html/2608.19920#bib.bib15)\), running chain of thought reasoning\([66](https://arxiv.org/html/2608.19920#bib.bib57)\), or sustaining multi\-turn conversations\. While naive transformer implementations scale quadratically in compute and linearly in memory with context width, a lot of progress has been made on approximations with essentially linear time and constant memory scaling\. A particularly fruitful direction issparse attention, where key\-value \(KV\) information is stored in a fixed\-size KV cache, slots of which are evicted once it is full, and many different eviction policies have been proposed\.
In this paper, we address the problem of how topost\-traina transformer language model with sparse attention on a moderate hardware budget \(our experiments are run computing gradients for a 4B weights model on a single111We use 4 GPUs with distributed data parallel training to attain a larger batch size\.Nvidia A100 GPU with 40 GB RAM\)\. Our novel method works for any KV cache policy and requires no further approximations beyond sparse attention\. As we demonstrate in experiments on a range of long\-context benchmarks, our training algorithm allows the model to co\-adapt with the KV cache policy, often outperforming models trained with exact attention \(sequence parallelism\)\. Moreover, our fine\-tuning method runs on resources comparable to sparse attention inference\. It can be combined with orthogonal KV cache compression strategies such as grouped query attention\([1](https://arxiv.org/html/2608.19920#bib.bib1)\)or quantization\([28](https://arxiv.org/html/2608.19920#bib.bib25);[44](https://arxiv.org/html/2608.19920#bib.bib37)\)\.
The heavy\-hitter oracle \(H2O\)\([76](https://arxiv.org/html/2608.19920#bib.bib69)\)is one of the most prominent sparse attention policies\. We demonstrate several improvements to H2O, leading to a much more efficient implementation with dedicated scaled dot product attention \(SDPA\) kernel support\. Variants of H2O outperform other KV cache policies in our experiments, and our fast implementation takes a big step towards latencies competitive with SotA inference libraries such as vLLM\([33](https://arxiv.org/html/2608.19920#bib.bib28)\), which use context or sequence parallelism almost exclusively\. In summary, our contributions are:
- β’New method for fine\-tuning transformer language models with sparse attention and arbitrary KV cache policy in place\. This method runs on resources comparable to sparse attention inference\. It combines nested activation checkpointing and CPU offloading with exploiting a linear KV cache buffer recurrence by way of autograd saved tensors packing\. Our method can process sequences of arbitrary length with constant resources\.
- β’Methodological and implementation improvements of heavy\-hitter oracle \(H2O\) cache policy\([76](https://arxiv.org/html/2608.19920#bib.bib69)\)\. In particular, we provideTritoncode to return summed attention weights alongside a FlashInfer SDPA kernel\([72](https://arxiv.org/html/2608.19920#bib.bib63)\)\.
- β’A comprehensive evaluation on a range of long\-context benchmarks\. Our training algorithm often outperforms models trained with sequence parallelism\([36](https://arxiv.org/html/2608.19920#bib.bib30)\)when sparse attention inference is used\.
- β’πΊππ’ππ°πππ
πππππ\\mathtt\{KeysAndValues\}, a novel open source library for long\-context inference and fine\-tuning \([https://github\.com/awslabs/keys\_values](https://github.com/awslabs/keys_values)\)\.
## 2Related Work
There is a large body of work on long\-context inference by way of KV cache compression\. A simple idea is to group heads, so that less key and value vectors need to be stored\([54](https://arxiv.org/html/2608.19920#bib.bib46);[1](https://arxiv.org/html/2608.19920#bib.bib1);[7](https://arxiv.org/html/2608.19920#bib.bib5)\), or to impose a low\-rank structure in the query\-by\-key matrix\([15](https://arxiv.org/html/2608.19920#bib.bib10)\)\. These are modifications to be used during pre\-training already\. Cache buffers can be quantized to 8 or 4 bits, or even below\([28](https://arxiv.org/html/2608.19920#bib.bib25);[44](https://arxiv.org/html/2608.19920#bib.bib37);[79](https://arxiv.org/html/2608.19920#bib.bib71);[39](https://arxiv.org/html/2608.19920#bib.bib32);[56](https://arxiv.org/html/2608.19920#bib.bib48);[34](https://arxiv.org/html/2608.19920#bib.bib29);[58](https://arxiv.org/html/2608.19920#bib.bib49);[78](https://arxiv.org/html/2608.19920#bib.bib68)\)\. Sparse attention is a powerful general idea \(discussed in Section[3\.1](https://arxiv.org/html/2608.19920#S3.SS1)\) with many instantiations\. Big Bird\([77](https://arxiv.org/html/2608.19920#bib.bib67)\)prescribes fixed attention sparsity patterns\. The heavy\-hitter oracle \(H2O\)\([76](https://arxiv.org/html/2608.19920#bib.bib69)\)is discussed in Section[3\.1\.1](https://arxiv.org/html/2608.19920#S3.SS1.SSS1)\. Q\-Hitter\([81](https://arxiv.org/html/2608.19920#bib.bib70)\)combines H2O with quantization, steering decisions by quantizability as well\. SnapKV\([40](https://arxiv.org/html/2608.19920#bib.bib31)\)uses summed attention weights like H2O, but makes decisions only at one point during generation\. Expected Attention\([12](https://arxiv.org/html/2608.19920#bib.bib12)\)tries to estimate future relevance of KV cache information \(under some strong assumptions\)\. FlexGen\([55](https://arxiv.org/html/2608.19920#bib.bib47)\)shows how to maximize throughput by using a cache hierarchy\. FastGen\([21](https://arxiv.org/html/2608.19920#bib.bib18)\)provides a meta\-strategy voting between a number of different cache policies\. CAKE\([49](https://arxiv.org/html/2608.19920#bib.bib42)\)runs sparse inference with a H2O\-related score, but also distributes an overall memory budget between layers\. Other sparse attention techniques include\([24](https://arxiv.org/html/2608.19920#bib.bib21);[69](https://arxiv.org/html/2608.19920#bib.bib59);[63](https://arxiv.org/html/2608.19920#bib.bib53);[8](https://arxiv.org/html/2608.19920#bib.bib6);[68](https://arxiv.org/html/2608.19920#bib.bib60);[62](https://arxiv.org/html/2608.19920#bib.bib54);[18](https://arxiv.org/html/2608.19920#bib.bib16);[71](https://arxiv.org/html/2608.19920#bib.bib62);[65](https://arxiv.org/html/2608.19920#bib.bib56)\)\. KVPop\([25](https://arxiv.org/html/2608.19920#bib.bib22)\)learns a cache policy against a future\-attention target, computed efficiently using FlexAttention\([14](https://arxiv.org/html/2608.19920#bib.bib14)\)\. Policies are parameterized as small xLSTMs[4](https://arxiv.org/html/2608.19920#bib.bib4)\. qTTT\([3](https://arxiv.org/html/2608.19920#bib.bib3)\)uses a few gradient updates at test time in order to improve inference results\. MInference\([30](https://arxiv.org/html/2608.19920#bib.bib27)\)and KVPress \([https://github\.com/NVIDIA/kvpress](https://github.com/NVIDIA/kvpress)\) are open source libraries providing several sparse attention methods\. ShadowKV\([60](https://arxiv.org/html/2608.19920#bib.bib52)\)is a high\-throughput long\-context inference system including KV cache selection\. SCBench\([41](https://arxiv.org/html/2608.19920#bib.bib33)\)provides a comprehensive empirical analysis of long\-context inference methods\.
Optimized scaled dot product attention \(SDPA\) kernels are essential for fast inference and training, pioneered by FlashAttention\([10](https://arxiv.org/html/2608.19920#bib.bib8);[52](https://arxiv.org/html/2608.19920#bib.bib44)\)\. FlashInfer\([72](https://arxiv.org/html/2608.19920#bib.bib63)\)is optimized for the inference case1βͺNqβͺNk1\\ll N\_\{q\}\\ll N\_\{k\}\(notation from Section[3\.1](https://arxiv.org/html/2608.19920#S3.SS1)\)\. FlexAttention\([14](https://arxiv.org/html/2608.19920#bib.bib14)\)allows to specify mask and score modification code, usingπππππ\.πππππππ\\mathtt\{torch\.compile\}under the hood\.
Our main contribution is on long\-contextfine\-tuning\. Prior work can be ordered into two groups\. Proposals in the first group modify multi\-head attention in ways which remedy the difficulties detailed in Section[3\.2](https://arxiv.org/html/2608.19920#S3.SS2)\. LongLoRA\([9](https://arxiv.org/html/2608.19920#bib.bib7)\)uses permutation and reshaping of keys and values, essentially trading\(B,N\)\(B,N\)for\(Bβ‘\(N/NC\),NC\)\(B\(N/N\_\{C\}\),N\_\{C\}\), whereBBis batch size,NNis sequence length,NCN\_\{C\}is cache length\. This speeds up MHA, but does not reduce KV memory, and works only ifN/NCN/N\_\{C\}is small\. Native sparse attention \(NSA\)\([74](https://arxiv.org/html/2608.19920#bib.bib65)\)bakes a mixture of some sparse attention kernels with different fixed policies into the model architecture\. DeepSeek sparse attention \(DSA\)\([16](https://arxiv.org/html/2608.19920#bib.bib11)\)is a refined variant of this idea\. Different toselectivesparse attention, this needs to be used during pre\-training already, whose cost is significantly increased\. IndexCache\([2](https://arxiv.org/html/2608.19920#bib.bib2)\)speeds up DSA somewhat by sharing the indexer \(i\.e\., the cache logic\) between several layers\. Also, by fixing the selection policy as part of the model choice, DSA offers considerable less flexibility during post\-training\. Finally, LSA and DSA still require storing the complete KV cache \(even though each attention call uses only a part of it\)\. LongGen\([20](https://arxiv.org/html/2608.19920#bib.bib19)\)uses static sparsity patterns for the top and bottom third of layers and full attention for the middle third, which speeds up training a bit, but does not reduce its memory requirements\. DMC\([46](https://arxiv.org/html/2608.19920#bib.bib40)\)uses a form of KV cache compression where new information is either appended or accumulated with the last recent slot\. They propose heuristics to train a model with this mechanism in place\. This approach seems restricted to KV cache updates during generation, it is not clear what is done when a large prompt needs to be processed\. Starting from Mamba\([23](https://arxiv.org/html/2608.19920#bib.bib20)\), there have been several attempts to resurrect LSTMs\([27](https://arxiv.org/html/2608.19920#bib.bib24)\), e\.g\.\([11](https://arxiv.org/html/2608.19920#bib.bib9);[4](https://arxiv.org/html/2608.19920#bib.bib4)\)\. When compared against the long\-context transformer SotA, none of them have been competitive enough in order to warrant costly pre\-training efforts\. YOCO\([61](https://arxiv.org/html/2608.19920#bib.bib51)\)proposes an architecture different to the transformer, where a single KV cache block serves all layers\. Note that KV buffer scaling with layers is not a major problem in practice, since at any time, all but one can be offloaded to CPU \(see Section[A\.4\.1](https://arxiv.org/html/2608.19920#A1.SS4.SSS1)\)\.
In the second group, KV cache buffers are not compressed, but both storage and computation are distributed across several devices\. This can be done with RingAttention\([42](https://arxiv.org/html/2608.19920#bib.bib36)\)or more recent variants\([43](https://arxiv.org/html/2608.19920#bib.bib38)\), in what is called context parallelism \(CP\), or with sequence parallelism \(SP\)\([36](https://arxiv.org/html/2608.19920#bib.bib30)\)\. While[38](https://arxiv.org/html/2608.19920#bib.bib34)observe that long sequences can be split into chunks, and that the computation graph factorizes along the chunk axis, the factor for the final chunk depends onallKV cache buffers of all layers, so cannot be represented on a single device222In fact, RingAttentionβs way to compute gradients makes use of this graph structure implicitly\.\(attempts to sparsify this computation are heuristics, and experiments are done only on rather short sequences of up to 16k tokens\)\. OOMB\([37](https://arxiv.org/html/2608.19920#bib.bib35)\)shares properties with our work, such as chunk\-level processing, activation checkpointing, and efforts to compress KV cache buffers forautograd\. While for exact KV caches, they run into the same issues as\([38](https://arxiv.org/html/2608.19920#bib.bib34)\), their implementation supports NSA and DSA as well\. Their way of hiding KV cache buffers fromautogradrequires a number of complex dedicated CUDA kernels, which need to be hardcoded for every sparse attention variant\. We manage KV buffer size inautogradvia delta encoding, which renders our implementation agnostic to the KV cache policy\. Details are given in Section[A\.8](https://arxiv.org/html/2608.19920#A1.SS8)\. LongRoPE\([13](https://arxiv.org/html/2608.19920#bib.bib13);[53](https://arxiv.org/html/2608.19920#bib.bib45)\)combines SP with a search for non\-uniform RoPE and several lifting stages\. Other work tuning position encoding, data mix and fine\-tuning recipes, but not compressing KV cache, includes\([67](https://arxiv.org/html/2608.19920#bib.bib58);[80](https://arxiv.org/html/2608.19920#bib.bib72);[19](https://arxiv.org/html/2608.19920#bib.bib17)\)\. LongStraw\([84](https://arxiv.org/html/2608.19920#bib.bib75)\)is a system designed for long context reinforcement learning, with a specific emphasis on sharing prompt graphs and KV caches between different roll\-outs\. It uses OOMB for gradient computations, but could likely be configured with our method as well\. Highly optimized implementations of CP/SP are the state of the art for long\-context inference, e\.g\. vLLM\([33](https://arxiv.org/html/2608.19920#bib.bib28)\), SGLang\([83](https://arxiv.org/html/2608.19920#bib.bib74)\), and fine\-tuning, e\.g\. Nvidia NeMo RL \([https://github\.com/NVIDIA\-NeMo/RL](https://github.com/NVIDIA-NeMo/RL)\), MS\-SWIFT\([82](https://arxiv.org/html/2608.19920#bib.bib73)\)\. In Section[3\.3](https://arxiv.org/html/2608.19920#S3.SS3), we comment on reasons why sparse attention methods are less frequently used in practice, and how this could be changed\.
## 3Long\-Context Fine\-Tuning
In this section, we first introduce sparse attention and key\-value caching, providing several improvements to the heavy\-hitter oracle \(H2O\) cache policy\([76](https://arxiv.org/html/2608.19920#bib.bib69)\), leading to a more efficient implementation with dedicated SDPA kernel support\. Then, we detail our main contribution: a novel method to fine\-tune models with sparse attention in place, using resources comparable to sparse attention inference\. While in SotA CP/SP techniques, GPUs need to be used for sharding along the context, they can be used to increase throughput \(i\.e\., larger batch sizes\) or to handle larger models in our method\.
### 3\.1Sparse Attention\. Key\-Value Caching
Multi\-head attention \(MHA\)is the most important mechanism in modern transformer architectures\([64](https://arxiv.org/html/2608.19920#bib.bib55)\)\. At its core liesscaled dot product attention \(SDPA\):
π=ππ³πΏπ°β‘\(πΈ,π²,π½\),π,πΈββ\(B,Hq,Nq,dh\),π²,π½ββ\(B,Hk,Nk,dh\)\.\\boldsymbol\{Y\}=\\mathtt\{SDPA\}\(\\boldsymbol\{Q\},\\boldsymbol\{K\},\\boldsymbol\{V\}\),\\quad\\boldsymbol\{Y\},\\boldsymbol\{Q\}\\in\\mathbb\{R\}^\{\(B,H\_\{q\},N\_\{q\},d\_\{h\}\)\},\\;\\boldsymbol\{K\},\\boldsymbol\{V\}\\in\\mathbb\{R\}^\{\(B,H\_\{k\},N\_\{k\},d\_\{h\}\)\}\.\(1\)Here,πΈ\\boldsymbol\{Q\}\(queries\),π²\\boldsymbol\{K\}\(keys\),π½\\boldsymbol\{V\}\(values\) are 4D arrays,BBis the batch size,dhd\_\{h\}theper\-head embedding dimension,Hq,HkH\_\{q\},H\_\{k\}are numbers of heads, andNq,NkN\_\{q\},N\_\{k\}are sequence lengths \(i\.e\., the third dimension is mapping to token positions in the model context\)\. Themodel embedding dimensionisd=Hqβ
dhd=H\_\{q\}\\cdot d\_\{h\}\. Let us first assume thatHq=HkH\_\{q\}=H\_\{k\}and drop the first two dimensions\. Then:
π=π΄π½,π΄=πππππππ‘\(ππππ\(dhβ1/2πΈπ²T\),πππ=π·\)\.\\boldsymbol\{Y\}=\\boldsymbol\{M\}\\boldsymbol\{V\},\\quad\\boldsymbol\{M\}=\\mathtt\{softmax\}\\left\(\\mathtt\{mask\}\\left\(d\_\{h\}^\{\-1/2\}\\boldsymbol\{Q\}\\boldsymbol\{K\}^\{T\}\\right\),\\mathtt\{dim=1\}\\right\)\.\(2\)π\\boldsymbol\{Y\}are weighted combinations of valuesπ½\\boldsymbol\{V\}withattention weightsπ΄ββ\(B,Hq,Nq,Nk\)\\boldsymbol\{M\}\\in\\mathbb\{R\}^\{\(B,H\_\{q\},N\_\{q\},N\_\{k\}\)\},πππππππ‘\\mathtt\{softmax\}appliesπβ¦expβ‘\(π\)/\(πTβexpβ‘\(π\)\)\\boldsymbol\{x\}\\mapsto\\exp\(\\boldsymbol\{x\}\)/\(\\boldsymbol\{1\}^\{T\}\\exp\(\\boldsymbol\{x\}\)\)along rows\.ππππ\\mathtt\{mask\}implements causal masking:\(ππππ\(πΏ\)\)i,j=xi,jββI\{P\+i<t\(j\)\}\(\\mathtt\{mask\}\(\\boldsymbol\{X\}\)\)\_\{i,j\}=x\_\{i,j\}\-\\infty\\mathrm\{I\}\_\{\\\{P\+i<t\(j\)\\\}\}, wherePPandtβ‘\(j\)t\(j\)are token positions \(see Section[3\.3\.1](https://arxiv.org/html/2608.19920#S3.SS3.SSS1)for details\)\. If arrays are indexed by\(b,h,j,k\)\(b,h,j,k\), SDPA operates on\(j,k\)\(j,k\)in the same way for all\(b,h\)\(b,h\), computations are parallelized over batch and head positions\.
Inference in transformers switches between prompt processing and token generation\. Generating a token after a prompt of sizeNNrequires SDPA withNk=N,Nq=1N\_\{k\}=N,N\_\{q\}=1, with keys and values of size\(B,Hk,N,dh\)\(B,H\_\{k\},N,d\_\{h\}\)in GPU memory, for each ofLLmodel layers\. Exact transformer inference therefore requiresπͺβ‘\(Lβ
Nβ
BβHkβdh\)\\mathcal\{O\}\(L\\cdot N\\cdot BH\_\{k\}d\_\{h\}\)GPU memory for the fullkey\-value \(KV\) cache\. Even for moderate context lengthsNNof several hundred thousands, the KV cache far surpasses the model weights in size and cannot be stored in GPU memory as is\.
A large amount of prior work confronts this problem \(see also Section[2](https://arxiv.org/html/2608.19920#S2)\)\. In grouped query attention \(GQA\)\([1](https://arxiv.org/html/2608.19920#bib.bib1)\), we setHq=Hkβ
qgH\_\{q\}=H\_\{k\}\\cdot q\_\{g\},qg\>1q\_\{g\}\>1, so thatqgq\_\{g\}heads map to the same query group, which reduces KV cache size by a factor ofqgq\_\{g\}\. Most relevant to our work issparse attention\(orselective KV caching; e\.g\.[76](https://arxiv.org/html/2608.19920#bib.bib69)\), where the KV cache is represented by fixed\-size buffersindependentof the context length of the model\. Once all slots are filled, new information overwrites \(orevicts\) existing ones\. Formally, the cache \(for one model layer\) is represented by arraysπππ’π,ππππππ:\(B,Hk,NC,dh\)\\mathtt\{keys\},\\mathtt\{values\}:\(B,H\_\{k\},N\_\{C\},d\_\{h\}\)andπππππβ\_βπππ:\(B,Hk,NC\)\\mathtt\{token\\\_pos\}:\(B,H\_\{k\},N\_\{C\}\)\. Here,NCN\_\{C\}is thecache length, which is chosen as large as GPU memory permits\. For up toNCN\_\{C\}tokens, the cache is filled from left to right\. After that, theKV cache policyΟlβ\(b,h,t\)β\{0,β¦,NCβ1\}\\pi\_\{l\}\(b,h,t\)\\in\\\{\{0\},\\dots,\{N\_\{C\}\-1\}\\\}dictates where additional key\-value information is written for token positiontβ₯NCt\\geq N\_\{C\}, batch positionbβ\{0,β¦,Bβ1\}b\\in\\\{\{0\},\\dots,\{B\-1\}\\\}and head \(or query group\)hβ\{0,β¦,Hkβ1\}h\\in\\\{\{0\},\\dots,\{H\_\{k\}\-1\}\\\}\. Importantly,Οl\\pi\_\{l\}can depend onb,hb,h: a token may be in the cache for some batch positions and heads, and not for others\.tβ‘\(b,h,j\)=πππππβ\_βπππβ\[b,h,j\]t\(b,h,j\)=\\mathtt\{token\\\_pos\}\[b,h,j\]lists the token position of what is stored in\(b,h,j\)\(b,h,j\)\. We do not require complex memory layouts and dedicated kernels for this setup, as for example PagedAttention\([33](https://arxiv.org/html/2608.19920#bib.bib28)\)needs\. In fact, \([2](https://arxiv.org/html/2608.19920#S3.E2)\) depends on absolute token positions only viaππππ\\mathtt\{mask\}\. This is as sparse as the conventional triangular one, but depends on token positionstβ‘\(β
\)=πππππβ\_βπππt\(\\cdot\)=\\mathtt\{token\\\_pos\}, which through cache evictions becomes non\-monotonic in general\. Moreover,πππππ\.ππππππ\\mathtt\{torch\.gather\}andπππππ\.πππππππ\\mathtt\{torch\.scatter\}provide fast read and write access for these buffers \(see Section[A\.1\.1](https://arxiv.org/html/2608.19920#A1.SS1.SSS1)\)\.
With sparse attention, we can run inference for any context widthNN\. First, we process up to the firstNCN\_\{C\}tokens with a single SDPA call \(Nq=Nk=NCN\_\{q\}=N\_\{k\}=N\_\{C\}\), this is known asprefilling\. The remainingNβNCN\-N\_\{C\}tokens are processed inchunksof sizeS<NCS<N\_\{C\}, using SDPA calls withNq=S,Nk=NCN\_\{q\}=S,N\_\{k\}=N\_\{C\}\(see Section[A\.4\.1](https://arxiv.org/html/2608.19920#A1.SS4.SSS1)for details\)\. Token generation usesNq=1,Nk=NCN\_\{q\}=1,N\_\{k\}=N\_\{C\}\. Memory requirements are independent ofNN\. For each chunk, the policy\[Οl\]\[\\pi\_\{l\}\]is used to determineBβ
Hkβ
SB\\cdot H\_\{k\}\\cdot Spositions\(b,h,j\)\(b,h,j\)which are overwritten by the new keys and values\. WhileNCN\_\{C\}is chosen as large as memory permits, the choice ofSSis more subtle\. The largerSS, the fewer chunks, and less sequential computation results in faster processing\. The smallerSS, the more fine\-grained the cache policy is used, which can lead to better decisions \(see also Section[3\.3](https://arxiv.org/html/2608.19920#S3.SS3)\)\.
#### 3\.1\.1Variants of Heavy\-Hitter Oracle
The key idea behind the heayy\-hitter oracle \(H2O\)\([76](https://arxiv.org/html/2608.19920#bib.bib69)\)is to make use of the attention weightsπ΄=\[mi,j\]\\boldsymbol\{M\}=\[m\_\{i,j\}\], a by\-product of SDPA \([2](https://arxiv.org/html/2608.19920#S3.E2)\)\. Dropping\(b,h\)\(b,h\)for the moment, we have thatπi,:=βjmi,jπ½j,:\\boldsymbol\{Y\}\_\{i,:\}=\\sum\_\{j\}m\_\{i,j\}\\boldsymbol\{V\}\_\{j,:\}andβjmi,j=1\\sum\_\{j\}m\_\{i,j\}=1\.mi,jm\_\{i,j\}quantifies how much valuesπ½j,:\\boldsymbol\{V\}\_\{j,:\}are used to createπi,:\\boldsymbol\{Y\}\_\{i,:\}\. The cumulative sumβimi,j\\sum\_\{i\}m\_\{i,j\}can be used to score the usefulness of vectors\(π²j,:,π½j,:\)\(\\boldsymbol\{K\}\_\{j,:\},\\boldsymbol\{V\}\_\{j,:\}\)in the KV cache\. Bringing\(b,h\)\(b,h\)back, we define the H2O score after having processedtttokens as
Οh2otβ\(b,h,j\)=βtβ‘\(b,h,j\)β€s<tmb,h,s,j,\\phi^\{t\}\_\{\\text\{h2o\}\}\(b,h,j\)=\\sum\_\{t\(b,h,j\)\\leq s<t\}m\_\{b,h,s,j\},\(3\)wheretβ‘\(b,h,j\)=πππππβ\_βπππβ\[b,h,j\]t\(b,h,j\)=\\mathtt\{token\\\_pos\}\[b,h,j\]is the position represented at\(b,h,j\)\(b,h,j\)right now\. We sum oversβ\{tβ‘\(b,h,j\),β¦,t\}s\\in\\\{\{t\(b,h,j\)\},\\dots,\{t\}\\\}because the slot is occupied from KV information corresponding to token positiontβ‘\(b,h,j\)t\(b,h,j\), which entered the cache only then\. The largerΟh2otβ\(b,h,j\)\\phi^\{t\}\_\{\\text\{h2o\}\}\(b,h,j\), the more valuable this information has been so far\. When asked to insert new content forSStokens, for each\(b,h\)\(b,h\), we overwrite theseSSslotsjjfor whichΟh2otβ\(b,h,j\)\\phi^\{t\}\_\{\\text\{h2o\}\}\(b,h,j\)is smallest\.
In this paper, we modify the original H2O policy\([76](https://arxiv.org/html/2608.19920#bib.bib69)\)\(as provided by their implementation\) in several ways\. First, their code selects the same cache slots for each batch positionbb, using the scoreΟh2o\-origtβ\(h,j\)=βbΟh2otβ\(b,h,j\)\\phi^\{t\}\_\{\\text\{h2o\-orig\}\}\(h,j\)=\\sum\_\{b\}\\phi^\{t\}\_\{\\text\{h2o\}\}\(b,h,j\)\. The rationale for this restriction is unclear, we implement H2O without it as well\. Second, the cumulative H2O score seems to favour entries\(b,h,j\)\(b,h,j\)which have been in the cache for longer, since more terms in\[0,1\]\[0,1\]are summed then\. We introduce thenormalized H2O score:Οh2o\-normtβ\(b,h,j\)=\(tβtβ‘\(b,h,j\)\)β1βΟh2otβ\(b,h,j\)\\phi^\{t\}\_\{\\text\{h2o\-norm\}\}\(b,h,j\)=\(t\-t\(b,h,j\)\)^\{\-1\}\\phi^\{t\}\_\{\\text\{h2o\}\}\(b,h,j\)\.
Despite convincing empirical results of H2O, both in\([76](https://arxiv.org/html/2608.19920#bib.bib69)\)and Section[4](https://arxiv.org/html/2608.19920#S4), it is not widely used\. This is mostly because current implementations of H2O are much slower than the state of the art\. We need summed attention weightsβimb,h,i,j\\sum\_\{i\}m\_\{b,h,i,j\}for each\(b,h,j\)\(b,h,j\), as by\-product of SDPA \([2](https://arxiv.org/html/2608.19920#S3.E2)\), but none of the fast SDPA kernels derived from FlashAttention\([10](https://arxiv.org/html/2608.19920#bib.bib8)\)provide them\. Current H2O implementations use naive SDPA implementations, which are much too slow in practice\. Our implementation containsTritoncode to return summed attention weights alongside a FlashInfer SDPA kernel\([72](https://arxiv.org/html/2608.19920#bib.bib63)\)\. In Section[A\.6](https://arxiv.org/html/2608.19920#A1.SS6), we show how FlexAttention\([14](https://arxiv.org/html/2608.19920#bib.bib14)\)can be used to this end as well\. We come back to efficiency of sparse attention in Section[3\.3](https://arxiv.org/html/2608.19920#S3.SS3)\.
### 3\.2Fine\-Tuning for Sparse Attention
How should we train a model which uses sparse attention with some KV cache policy such as H2O? As noted in Section[2](https://arxiv.org/html/2608.19920#S2), all prior long\-context fine\-tuning methods either restrict the MHA approximation to a particular form, or use exact MHA with KV cache buffers distributed across several devices \(i\.e\., sequence or context parallelism\)\. However, the choice of KV cache policy, which dictates how the modelβs short term memory is organized, should influence how the model is best trained\. Our results in Section[4](https://arxiv.org/html/2608.19920#S4)validate this hypothesis\.Sparse attention inference for a model trained with exact MHA and sequence parallelism \(which is the SotA\) often performs significantly worse than for a model trained with sparse attention and the desired policy in place\.
Fine\-tuning for models with sparse attention is difficult, because an enormous amount of memory is required, while GPU memory is on short supply\. We need to compute gradients for training loss functions on sequences of lengthNβ«NCN\\gg N\_\{C\}, which is done by \(reverse mode\) automatic differentiation \(or error backpropagation,autograd\)\. Autograd works by creating a computation graph during the forward pass, whose nodes store arrays needed during the backward pass\. If the model hasLLlayers and the chunk size isSS, the training sequence is split into1\+β\(NβNC\)/Sβ1\+\\lceil\(N\-N\_\{C\}\)/S\\rceilchunks, the first \(prefill\) chunk of lengthNCN\_\{C\}and subsequent chunks of lengthSS\. SDPA is called for each layer and chunk, creating at least one node of the size of the KV cache, so we need at leastπͺβ‘\(Lβ
Sβ1β\(NβNC\)β
NCβ
π\)\\mathcal\{O\}\(L\\cdot S^\{\-1\}\(N\-N\_\{C\}\)\\cdot N\_\{C\}\\cdot\\mathcal\{D\}\)of memory, whereπ=BβHkβdh\\mathcal\{D\}=BH\_\{k\}d\_\{h\}\. AssumingS=aβNCS=aN\_\{C\}for some constantaa, this isπͺβ‘\(Lβ
Nβ
π\)\\mathcal\{O\}\(L\\cdot N\\cdot\\mathcal\{D\}\): more than thefullKV cache would need, and far beyond what is tractable\.
We need several ideas in order to bring GPU memory requirements down to levels comparable to what inference needs\. First, we avoid differentiation through the KV cache policy \(which is often not even possible, and in general not tractable\)\. Along the forward pass, we store all KV cache policy decisions in areplay log, containing for each chunk \(and each layerll\) the tokens processed, and the decisions\{Οlβ\(b,h,t\)\}\\\{\\pi\_\{l\}\(b,h,t\)\\\}\. Later on, we usereplay caches, which act like normal KV caches, except that eviction decisions are replayed from the log\. If a cache policy is complex and expensive to compute, it needs to be run during the forward pass only\.
Next, we use activation checkpointing\([26](https://arxiv.org/html/2608.19920#bib.bib23)\)\. Even with moderate context widths, this technique is routinely used for models with many layers\. Gradients are computed in two passes: forward and backward\. Different from autograd, there is no computation graph built during the forward pass, only the input tensors for each transformer layer are stored to CPU memory\. The backward pass is split intoLLautograd calls, starting from the top\. Head gradients are supplied from the previous layer, inputs are loaded from CPU\. Computations graphs on GPU areLLtimes smaller, while forward computations have to be run twice\.
While standard activation checkpointing tackles largeLL, in long\-context situations the context widthNNis the more serious problem\. We cannot even keep complete inputs or head gradients for a single layer in GPU memory \(see also Section[A\.4\.1](https://arxiv.org/html/2608.19920#A1.SS4.SSS1)\), let alone KV buffers attached to each chunk in the computation graph\. We therefore use activation checkpointing twice, in a nested fashion\. To this end, we partition chunks intocells:\{\(B,S,d\)\}β\(B,kβS,d\)\\\{\(B,S,d\)\\\}\\to\(B,kS,d\), wherek=βΞ±βNC/Sβk=\\lfloor\\alpha N\_\{C\}/S\\rfloor, andΞ±\>0\\alpha\>0is a hyperparameter which defaults toΞ±=1\\alpha=1\. The first \(prefill\) chunk becomes the first cell\. As a rule of thumb, we group chunks into cells which occupy about the size of KV cache buffers\. The complete computation graph can be seen aslattice of cells: rows are layers, columns are cells \(i\.e\., groups of chunks\) along the context\. Our backward pass runs an outer loop over rows \(layers\), then inner loops over cells in each layer\. Each inner loop starts with a \(non\-autograd\) forward pass along the context, storing KV cache buffers \(the inner loop βactivationsβ to checkpoint\) going into each cell to CPU\. Next, autograd is run separately on each cell, starting from the right\. Inputs to a cell \(layer inputs from the bottom and KV cache buffers from the left\) and head gradients from the top are read from CPU, while head gradients from the right stay in GPU memory\. Gradients are accumulated\. We reuse the same CPU and GPU buffers for all inner loops\.333It is tempting to store all KV cache checkpoints to CPU during the initial forward pass, along with layer inputs\. However, this requires a lot of CPU memory, and the per\-layer forward passes to obtain KV cache checkpoints are subdominant to all other computations\.A detailed summary of our method is given in Section[A\.4\.2](https://arxiv.org/html/2608.19920#A1.SS4.SSS2)\.
Even with nested activation checkpointing, the autograd calls still need too much GPU memory\. Recall that a cell consists ofk=βΞ±βNC/Sβk=\\lfloor\\alpha N\_\{C\}/S\\rfloorchunks\. Autograd stores KV cache buffers for each chunk, so needs at leastπͺβ‘\(kβ
NCβ
π\)\\mathcal\{O\}\(k\\cdot N\_\{C\}\\cdot\\mathcal\{D\}\)memory, whereπ=BβHkβdh\\mathcal\{D\}=BH\_\{k\}d\_\{h\}\. As detailed in Section[3\.1](https://arxiv.org/html/2608.19920#S3.SS1),kkmust be sizable to allow cache policies to make good decisions\. In this section, we detail the last \(and maybe most important\) idea, which cuts GPU memory by a factor ofkk, toπͺβ‘\(NCβ
π\)\\mathcal\{O\}\(N\_\{C\}\\cdot\\mathcal\{D\}\)per autograd call\. This is comparable to what is needed during inference alone\.
Consider KV cache buffers\(πππ’π,ππππππ\)\(\\mathtt\{keys\},\\mathtt\{values\}\),\(πππ’πβ²,ππππππβ²\)\(\\mathtt\{keys\}^\{\\prime\},\\mathtt\{values\}^\{\\prime\}\)for neighboring chunks\. Their size is\(B,Hk,NC,dh\)\(B,H\_\{k\},N\_\{C\},d\_\{h\}\), but they only differ inSβ
πS\\cdot\\mathcal\{D\}values, because a chunk consists ofSStokens only\. The relationship is simple:
πππ’πβ²=πππππππβ‘\(πππ’π,πππππ‘,πππ’β\_βπππ \),ππππππβ²=πππππππβ‘\(ππππππ,πππππ‘,πππππβ\_βπππ \)\.\\mathtt\{keys\}^\{\\prime\}=\\mathtt\{scatter\}\(\\mathtt\{keys\},\\mathtt\{index\},\\mathtt\{key\\\_new\}\),\\;\\mathtt\{values\}^\{\\prime\}=\\mathtt\{scatter\}\(\\mathtt\{values\},\\mathtt\{index\},\\mathtt\{value\\\_new\}\)\.Here,πππ’β\_βπππ ,πππππβ\_βπππ \\mathtt\{key\\\_new\},\\mathtt\{value\\\_new\}are KV vectors for new tokens with sizes\(B,Hq,S,dh\)\(B,H\_\{q\},S,d\_\{h\}\),πππππ‘\\mathtt\{index\}is based on the cache policyΟl\\pi\_\{l\}, determining which slots are overwritten, andπππππππ,ππππππ\\mathtt\{scatter\},\\mathtt\{gather\}are linearπππππ\\mathtt\{torch\}operators defined in Section[A\.1\.1](https://arxiv.org/html/2608.19920#A1.SS1.SSS1)\.
This is a linear recurrence, which is easily inverted:
πππ’π=πππππππβ‘\(πππ’πβ²,πππππ‘,πππππβ\_βπππ’\),πππππβ\_βπππ’=ππππππβ‘\(πππ’π,πππππ‘\),\\mathtt\{keys\}=\\mathtt\{scatter\}\(\\mathtt\{keys\}^\{\\prime\},\\mathtt\{index\},\\mathtt\{delta\\\_key\}\),\\quad\\mathtt\{delta\\\_key\}=\\mathtt\{gather\}\(\\mathtt\{keys\},\\mathtt\{index\}\),\(4\)and the same forππππππ\\mathtt\{values\}\. Instead of storingπππ’π,ππππππ\\mathtt\{keys\},\\mathtt\{values\}for each chunk in the compute graph, it suffices to store444This is a form ofdelta encoding\([https://en\.wikipedia\.org/wiki/Delta\_encoding](https://en.wikipedia.org/wiki/Delta_encoding)\)\.πππππβ\_βπππ’,πππππβ\_βπππππ\\mathtt\{delta\\\_key\},\\mathtt\{delta\\\_value\}\. Since memory requirements of autograd calls are dominated by the KV cache buffers, they are reduced by a factor ofkk\.
While the linear recurrence relation between neighboring cache buffers is simple, implementing it in the context ofPyTorch autogradis not\. We use a mechanism calledautograd saved tensors hooks555[https://docs\.pytorch\.org/tutorials/intermediate/autograd\_saved\_tensors\_hooks\_tutorial\.html](https://docs.pytorch.org/tutorials/intermediate/autograd_saved_tensors_hooks_tutorial.html), originally intended to implement activation checkpointing by CPU offloading, which can be shaped to ours needs\. In a nutshell, we use thePyTorchmechanism to store\(πππππβ\_βπππ’,πππππβ\_βπππππ\)\(\\mathtt\{delta\\\_key\},\\mathtt\{delta\\\_value\}\)in the autograd graph in place of\(πππ’π,ππππππ\)\(\\mathtt\{keys\},\\mathtt\{values\}\)\(called βpackingβ\), reconstructing the latter from the former and subsequent\(πππ’πβ²,ππππππβ²\)\(\\mathtt\{keys\}^\{\\prime\},\\mathtt\{values\}^\{\\prime\}\)during the backward pass over chunks \(called βunpackingβ\)\. The key difficulty is the non\-selectiveness of the mechanism: it provides aππππβ\_βππππ\\mathtt\{pack\\\_hook\}function called for all arraysPyTorch autograddecides to place into its graph\. There is no way to tag tensors in the forward code, so they can be recognized asππππβ\_βππππ\\mathtt\{pack\\\_hook\}arguments\. Our solution is to createannotationsalongside the forward pass code, storing\(πππππ‘,πππππβ\_βπππ’\)\(\\mathtt\{index\},\\mathtt\{delta\\\_key\}\)forπππ’π\\mathtt\{keys\},\(πππππ‘,πππππβ\_βπππππ\)\(\\mathtt\{index\},\\mathtt\{delta\\\_value\}\)forππππππ\\mathtt\{values\}\. In aππππβ\_βππππβ\(π\)\\mathtt\{pack\\\_hook\}\(\\boldsymbol\{x\}\)call, we relateπ\\boldsymbol\{x\}to current annotations:π\\boldsymbol\{x\}matches\(πππππ‘,πππππβ\_βπππ’\)\(\\mathtt\{index\},\\mathtt\{delta\\\_key\}\)\(say\) ifππππππβ‘\(π,πππππ‘\)=πππππβ\_βπππ’\\mathtt\{gather\}\(\\boldsymbol\{x\},\\mathtt\{index\}\)=\\mathtt\{delta\\\_key\}\. A match leads toππππβ\_βππππβ\(π\)\\mathtt\{pack\\\_hook\}\(\\boldsymbol\{x\}\)returning a reference to\(πππππ‘,πππππβ\_βπππ’\)\(\\mathtt\{index\},\\mathtt\{delta\\\_key\}\), which is removed from the annotation list\. Note that failing to match an annotation does not lead to errors, but at most to a bit more memory being used\. More details are given in Section[A\.4\.3](https://arxiv.org/html/2608.19920#A1.SS4.SSS3)\.
### 3\.3Sparse Attention and Sequence Parallelism
While with context or sequence parallelism, the context width is strictly limited by the number and memory size of GPUs available, sparse attention inference can be run for any context width on moderate GPU resources\. Moreover, redundancies which exist in multi\-head attention, can be exploited by way of cache compression, and experimental results with H2O are in general not worse than with exact attention even if the KV cache is compressed to 20% or less\([76](https://arxiv.org/html/2608.19920#bib.bib69);[81](https://arxiv.org/html/2608.19920#bib.bib70)\)\. Even if many GPUs are available, using sparse attention allows us to increase batch size by way of distributed data parallel, or to keep more layers in GPU memory\. A large number of sparse attention variants have been proposed \(see Section[2](https://arxiv.org/html/2608.19920#S2)\)\.Why is it then that sparse attention methods are hardly used in SotA inference libraries such as vLLM\([33](https://arxiv.org/html/2608.19920#bib.bib28)\)? The short answer is that latency is significantly higher with existing sparse attention implementations\. Further comments are in Section[A\.7](https://arxiv.org/html/2608.19920#A1.SS7)\.
Some of the gap is due to less low level implementation support for sparse attention\. Highly optimized SDPA kernels are vital for fast inference\([10](https://arxiv.org/html/2608.19920#bib.bib8);[14](https://arxiv.org/html/2608.19920#bib.bib14);[72](https://arxiv.org/html/2608.19920#bib.bib63)\)\. However, as noted in Section[3\.1\.1](https://arxiv.org/html/2608.19920#S3.SS1.SSS1), existing kernels do not cater for sparse attention inference \(see details in Section[3\.3\.1](https://arxiv.org/html/2608.19920#S3.SS3.SSS1)\)\. Other reasons for the gap are more difficult to address\. A long sequence is split into chunks, the first \(prefill\) chunk of lengthNCN\_\{C\}\(cache length\), subsequent chunks of lengthSS\. LargerSSmeans fewer chunks and lower latency\. But KV cache policies can make useful eviction decisions only ifSSis much less thanNCN\_\{C\}\(in our experiments in Section[4](https://arxiv.org/html/2608.19920#S4), we useNC=32768N\_\{C\}=32768andSβ\{1024,2048\}S\\in\\\{1024,2048\\\}\)\. For the extreme choiceS=NCS=N\_\{C\}, the whole cache is overwritten by new content for every chunk, and the KV cache policy plays no role at all\! Information cannot be kept in the cache beyond a chunk if we do not allow for substantial overlap\.
For example, suppose we use 8 devices, each supporting a cache lengthNCN\_\{C\}, and the sequence length isN=8βNCN=8N\_\{C\}\. With RingAttention, each device holdsNCN\_\{C\}slots, and the sequence is processed in 8 sequential chunks\. But for sparse attention, we need1\+7βNC/S1\+7N\_\{C\}/Schunks, which can be substantially larger\. Despite sparse attention supporting a 8 times larger batch size via distributed data parallel \(DDP\), inference tends to still be slower than with RingAttention\. In future work, we plan to improve sparse attention latency by appropriate kernel fusion\. However, the sequential nature of decision making in sparse attention may be an inherent disadvantage over sequence or context parallelism, which may remain the best choice if a large hardware budget can be afforded for inference\.
Apart from large hardware requirements to even work on long sequences, RingAttention requiresπͺβ‘\(Lβ
D\)\\mathcal\{O\}\(L\\cdot D\)synchronizations between all devices per gradient update, while sparse attention DDP only needs a single gradient averaging reduction\. While memory transfer between devices can be run in parallel with computations, this needs double buffering666On each device, one set ofπππ’π,ππππππ\\mathtt\{keys\},\\mathtt\{values\}are read for computation and transfer, another set is written to\([42](https://arxiv.org/html/2608.19920#bib.bib36)\)\.in RingAttention, doubling the GPU memory needed\. The peer\-to\-peer memory transfer is more brittle than DDP used with sparse attention, and robust training code is more difficult to implement\. Finally, the βwaste by pre\-allocationβ issues which motivate the fairly complex PagedAttention[33](https://arxiv.org/html/2608.19920#bib.bib28), have a simpler solution with sparse inference: KV cache buffers are of a fixed length, there is no need to split777If we frequently encounter batches shorter than the cache length, we can build up buffers in chunks\. But most modern agentic AI applications come with long prompts anyway\.them into pages along the sequence axis, and no custom SDPA code is needed\.
#### 3\.3\.1Discussion: SDPA Kernels for Sparse Attention
Here, we list some ideas for SDPA kernel developers to better support sparse attention\. First, we consider causal masking for sparse attention\. In standard MHA \(the βtraining caseβ\),\(ππππ\(πΏ\)\)i,j=xi,jββI\{i<j\}\(\\mathtt\{mask\}\(\\boldsymbol\{X\}\)\)\_\{i,j\}=x\_\{i,j\}\-\\infty\\mathrm\{I\}\_\{\\\{i<j\\\}\}\. For sparse attention, KV information is stored in cache buffers in an ordering given by token positionstβ‘\(b,h,j\)t\(b,h,j\), and the causal mask is given by\(b,h,i,j\)β¦\(ββ\)I\{P\+i<t\(b,h,j\)\}\(b,h,i,j\)\\mapsto\(\-\\infty\)\\mathrm\{I\}\_\{\\\{P\+i<t\(b,h,j\)\\\}\}, wherePPis the number of tokens processed before the current MHA call \(so the new information is for tokens\{P,β¦,P\+Nqβ1\}\\\{\{P\},\\dots,\{P\+N\_\{q\}\-1\}\\\}\)\. The new key\-value information has been written into the cache already, so that\{P,β¦,P\+Nqβ1\}\\\{\{P\},\\dots,\{P\+N\_\{q\}\-1\}\\\}is part of\{tβ‘\(b,h,j\)\}\\\{t\(b,h,j\)\\\}for each\(b,h\)\(b,h\)\.
Unfortunately, none of the fast SDPA kernel codes we know of support such variants of causal masking in an implicitly888We cannot pass an explicit mask matrix, which would be huge and defy the purpose of fast SDPA\.defined way\. In our implementation, we sort the token positions and reorder keys and values according to this index, separate for each\(b,h\)\(b,h\), after which we can use standard causal masking, where queries are right\-aligned with keys and values\. This needs extra computation and memory which could be saved with better SDPA kernel support\. Based on our experience, the following simple extensions of fast SDPA kernel libraries could make a major difference for sparse attention:
- β’Return summed attention weightsβimb,h,i,j\\sum\_\{i\}m\_\{b,h,i,j\}\(see Section[3\.1\.1](https://arxiv.org/html/2608.19920#S3.SS1.SSS1)\), an array of size\(B,Hq,Nk\)\(B,H\_\{q\},N\_\{k\}\), based on attention weights which are computed anyway\. This allows for H2O and related scores to be computed, driving advanced KV cache policies\.
- β’Allow for implicitly defined causal masks of the form\(b,h,i,j\)β¦\(ββ\)I\{P\+i<t\(b,h,j\)\}\(b,h,i,j\)\\mapsto\(\-\\infty\)\\mathrm\{I\}\_\{\\\{P\+i<t\(b,h,j\)\\\}\}, wheretβ‘\(β
\)t\(\\cdot\)is an\(B,Hk,Nk\)\(B,H\_\{k\},N\_\{k\}\)integer array\. While FlexAttention\([14](https://arxiv.org/html/2608.19920#bib.bib14)\)supports custom mask patterns, they need to be written in terms of scalar index variables, so cannot have a 3D array as input to the compute graph\.
## 4Experiments
The key question addressed in our experiments is:if long context inference uses sparse attention with a particular KV cache policy, how much is gained by fine\-tuning the model with the same policy in place \(using our novel method\) over training it with state of the art libraries using sequence or context parallelism? We run comparisons on the Helmet\([73](https://arxiv.org/html/2608.19920#bib.bib64)\)benchmarks, with context widths of 64k and 128k, covering a range of cache policies:
- β’πππππππ\\mathtt\{lastrec\}\(lr\):Ο\(b,h,t\)=tI\{t<NC\}\+\(mod\(tβNC,NCβΞ²\)\+Ξ²\)I\{tβ₯NC\}\\pi\(b,h,t\)=t\\mathrm\{I\}\_\{\\\{t<N\_\{C\}\\\}\}\+\(\\mathrm\{mod\}\(t\-N\_\{C\},N\_\{C\}\-\\beta\)\+\\beta\)\\mathrm\{I\}\_\{\\\{t\\geq N\_\{C\}\\\}\}, whereΞ²β\[0,NC\)\\beta\\in\[0,N\_\{C\}\)\. Keeps the last recentNCβΞ²N\_\{C\}\-\\betaand firstΞ²\\betatokens in the cache\. It is important to chooseΞ²\>0\\beta\>0as default βattention sinkβ\([69](https://arxiv.org/html/2608.19920#bib.bib59)\)\. Our default isΞ²=minβ‘\(16,βNC/8β\)\\beta=\\min\(16,\\lceil N\_\{C\}/8\\rceil\)\.
- β’πππππβ\_βπππππππ\\mathtt\{smart\\\_lastrec\}\(slr\): Variant ofπππππππ\\mathtt\{lastrec\}, where the numberΞ²\\betaof initial tokens is chosen dependent on content \(see Section[A\.2\.1](https://arxiv.org/html/2608.19920#A1.SS2.SSS1)for details\)\. A simple version of this heuristic appeared in\([24](https://arxiv.org/html/2608.19920#bib.bib21)\)\.
- β’ππΈπ\\mathtt\{h2o\}\(h2o\\mathrm\{h2o\}\),ππΈπβ\_βππππ\\mathtt\{h2o\\\_norm\}\(h2ono\\mathrm\{h2o\}^\{\\text\{no\}\}\),ππΈπβ\_βππππ\\mathtt\{h2o\\\_orig\}\(h2oor\\mathrm\{h2o\}^\{\\text\{or\}\}\): Variants of H2O\([76](https://arxiv.org/html/2608.19920#bib.bib69)\)\(see Section[3\.1\.1](https://arxiv.org/html/2608.19920#S3.SS1.SSS1)for details\)\.ππΈπβ\_βππππ\\mathtt\{h2o\\\_orig\}is equivalent to their code released, whereΟβ‘\(b,h,t\)\\pi\(b,h,t\)does not depend on batch positionbb\.
We train aQwen3\-4B\-Instruct\-2507999This checkpoint has been post\-trained to process long contexts\. We still need to adjust the RoPE position encoding, which we do with YaRN\.model\([70](https://arxiv.org/html/2608.19920#bib.bib61)\), usingAdamW\([45](https://arxiv.org/html/2608.19920#bib.bib39)\)with base learning rate0\.00050\.0005for up to 5 epochs\. We train LoRA weights only\([29](https://arxiv.org/html/2608.19920#bib.bib26)\)\(rankr=16r=16,Ξ±=16\\alpha=16, on all linear blocks\)\. We run on four Nvidia A100 40 GB devices with a per\-device batch size of 2, using RoPE\([59](https://arxiv.org/html/2608.19920#bib.bib50)\)and YaRN\([48](https://arxiv.org/html/2608.19920#bib.bib41)\)for position encoding\. Fine\-tuning is done in different ways:
- β’Sequence parallelism \(sp\): We use MS\-SWIFT\([82](https://arxiv.org/html/2608.19920#bib.bib73)\)for fine\-tuning with DeepSpeed ZeRO\-3 offload, FlashAttention, and Liger kernels enabled, running on four Nvidia A100 40GB GPUs\. We use a per\-device batch size of 2 and sequential gradient accumulation \(effective batch size 8\)101010For 64k \(128k\), 2 \(4\) devices cover the context, so we need 2 \(4\) sequential gradient accumulation steps\.\.
- β’Our method \(us\): We use a cache lengthNc=32768N\_\{c\}=32768, batch sizeSβ\{1024,2048\}S\\in\\\{1024,2048\\\}, and chunks per cell multiplierΞ±=1\\alpha=1forS=2048S=2048,Ξ±=0\.75\\alpha=0\.75forS=1024S=1024\(see also Section[A\.4\.1](https://arxiv.org/html/2608.19920#A1.SS4.SSS1)\)\. KV cache buffers are quantized to 8 bits usingπππππππ\\mathtt\{torchao\}\. We run distributed data parallel optimization on 4 devices to obtain an effective batch size of 8\. We evaluate the model on a heldout validation set every 10 gradient steps \(5 forpop\_qa\), and choose the checkpoint with the lowest validation loss for testing\.
64k datasets128k datasetsnqtri\_qahot\_qapop\_qanqtri\_qahot\_qapop\_qausspusspusspusspusspusspusspusspexact\\mathrm\{exact\}\-β50\.7\-β79\.8\-β60\.0\-β62\.7\-β50\.7\-β68\.7\-β46\.3\-β57\.0lr2βk\\mathrm\{lr\}\_\{2k\}β33\.5β57\.2β75\.3β57\.5β53\.3β62\.7β43\.7β60\.5β26\.0β33\.0β50\.8β52\.3β31\.0β46\.3β34\.0β25\.0slr2βk\\mathrm\{slr\}\_\{2k\}β47\.3β56\.5β74\.5β60\.8β50\.0β67\.3β44\.0β56\.7β26\.0β33\.7β61\.2β51\.8β34\.0β42\.0β37\.7β22\.2h2o2βk\\mathrm\{h2o\}\_\{2k\}β47\.2β70\.8β78\.0β72\.0β53\.0β68\.7β57\.5β44\.7β24\.2β40\.7β47\.8β63\.7β19\.3β26\.0β53\.3β49\.8h2o2βkno\\mathrm\{h2o\}\_\{2k\}^\{\\text\{no\}\}β47\.8β68\.2β63\.2β54\.5β58\.3β70\.0β53\.0β39\.8β43\.5β51\.3β66\.7β55\.3β37\.3β51\.0β50\.2β25\.2h2o2βkor\\mathrm\{h2o\}\_\{2k\}^\{\\text\{or\}\}β49\.5β73\.3β66\.3β65\.7β57\.3β68\.7β62\.2β45\.5β45\.3β58\.8β71\.2β71\.0β36\.7β44\.3β50\.2β33\.3lr1βk\\mathrm\{lr\}\_\{1k\}β59\.7β57\.0β73\.0β60\.7β47\.7β65\.3β41\.7β59\.3β23\.5β32\.7β59\.5β50\.0β28\.7β45\.0β34\.5β25\.2slr1βk\\mathrm\{slr\}\_\{1k\}β37\.8β57\.0β59\.8β59\.7β52\.7β65\.0β46\.8β57\.0β29\.3β36\.2β58\.2β49\.7β33\.7β44\.7β34\.3β21\.2h2o1βk\\mathrm\{h2o\}\_\{1k\}β62\.0β72\.8β79\.7β72\.0β55\.0β68\.0β59\.3β45\.8β23\.2β41\.3β51\.7β58\.7β25\.3β24\.3β51\.0β50\.5h2o1βkno\\mathrm\{h2o\}\_\{1k\}^\{\\text\{no\}\}β47\.5β71\.3β62\.3β59\.3β61\.7β73\.0β51\.0β43\.5β42\.7β53\.3β70\.3β58\.2β42\.3β54\.7β44\.1β26\.8h2o1βkor\\mathrm\{h2o\}\_\{1k\}^\{\\text\{or\}\}β49\.0β72\.2β75\.7β68\.7β57\.0β66\.7β55\.0β47\.3β44\.3β60\.5β72\.0β74\.8β31\.0β41\.3β51\.0β30\.8Table 1:Results for long\-context inference with 5 KV cache policies and chunk sizes2048=2βk,1024=1βk2048=2k,1024=1k\(rows\)\. The first rowexactis for exact inference \(sequence parallelism\)\. We showSubEMvalues on test splits for different Helmet datasetsnq, trivia\_qa, hotpot\_qa, pop\_qa, limiting sequence lengths to 64k or 128k tokens\. Columnsusare for models trained using our novel method with the same cache policy in place, columnsspare for models trained with sequence parallelism\.datasettrnexactslr1βk\\mathrm\{slr\}\_\{1k\}h2o1βkno\\mathrm\{h2o\}\_\{1k\}^\{\\text\{no\}\}h2o1βkor\\mathrm\{h2o\}\_\{1k\}^\{\\text\{or\}\}trec\_coarseus\-β96\.0β96\.4β96\.2spβ97\.8β30\.0β23\.2β77\.6no\-β28\.2β19\.8β36\.0nluus\-β90\.0β87\.4β79\.8spβ90\.2β28\.6β32\.8β74\.0no\-β24\.8β30\.0β21\.2clinc150us\-β97\.4β96\.8β94\.0spβ97\.6β64\.2β61\.6β68\.0no\-β62\.6β54\.0β34\.8inf\_qaus\-β26\.6β32\.2β36\.8spβ40\.8β2\.2β2\.2β3\.3no\-β2\.5β2\.9β3\.4inf\_mcus\-β40\.0β42\.0β54\.0spβ66\.0β25\.0β29\.0β39\.0no\-β36\.0β41\.0β40\.0json\_kvus\-β49\.0β50\.0β3\.0spβ100\.0β0\.0β0\.0β1\.0no\-β0\.0β0\.0β0\.0Table 2:Results for 6 additional Helmet datasets not featured in Table[1](https://arxiv.org/html/2608.19920#S4.T1)\(context width 128k\)\. Inference under 3 KV cache policies \(chunk size1024=1βk1024=1k\),exactuses sequence parallelism \(column\)\.trndenotes model checkpoint being used:ususes our novel method with the same cache policy in place,spis using sequence parallelism,nois the base checkpointQwen3\-4B\-Instruct\-2507\(no fine\-tuning\)\. Note that metrics are different, depending on the dataset \(see Table[3](https://arxiv.org/html/2608.19920#A1.T3)\)\.Results on 4 Helmet datasets \(nq, trivia\_qa, hotpot\_qa, pop\_qa\)\([73](https://arxiv.org/html/2608.19920#bib.bib64)\)and 10 different cache setups \(5 policies, 2 chunk sizes\) are provided in Table[1](https://arxiv.org/html/2608.19920#S4.T1)\. Respective results for the base checkpoint \(no fine\-tuning\) are given in Table[4](https://arxiv.org/html/2608.19920#A1.T4)in the Appendix \(referred to asnoelsewhere\)\. For further 6 Helmet datasets \(trec\_coarse, nlu, clinc150, inf\_qa, inf\_mc, json\_kv\), Table[2](https://arxiv.org/html/2608.19920#S4.T2)provides results for 3 cache policies and chunk sizeS=1024S=1024\. Details about Helmet datasets and metrics are given in Section[A\.3\.1](https://arxiv.org/html/2608.19920#A1.SS3.SSS1)\.
For the datasets in Table[1](https://arxiv.org/html/2608.19920#S4.T1), results are mixed and inconclusive:spis best fornqandhotpot\_qa,nofortrivia\_qa\(fine\-tuning does not help\), andusforpop\_qa\. However, for the datasets in Table[2](https://arxiv.org/html/2608.19920#S4.T2),usstrongly outperformsspandno\. A closer look at generated samples \(which can be up to 128 tokens\) reveals a major failure mode ofsp\(see Section[A\.5\.3](https://arxiv.org/html/2608.19920#A1.SS5.SSS3)\):its outputs are far too long and contain mostly random nonsense\. For most datasets in Table[2](https://arxiv.org/html/2608.19920#S4.T2), targets are single numerical values, and theAccuracymetric \(see Section[A\.3\.1](https://arxiv.org/html/2608.19920#A1.SS3.SSS1)\) compares this to the most frequently occuring number in the output\. Poor results are due to the output forspoften containing many numbers\. In contrast,uslearns how to stop properly and usually outputs a single number\. In fact,the same failure mode dominates outcomes in Table[1](https://arxiv.org/html/2608.19920#S4.T1)just as well, but the metricSubEMused for the 4 datasets ignores content or length of output, as long as the target string is contained in it\. Finally,spandnofail forjson\_kvas well, despite this using theSubEMmetric\. Targets are UUIDs of length 32 tokens\. While variants ofusidentify them about half the time, they are hardly ever contained in the outputs ofspandno\. In Section[A\.5\.3](https://arxiv.org/html/2608.19920#A1.SS5.SSS3), we quantify the failure mode in Table[7](https://arxiv.org/html/2608.19920#A1.T7)\. While outputs forusare close in length to true targets, they are longer by large factors forsp,no, which often \(but not always\) span the full 128 tokens \(despite true targets being much shorter\)\. We also provide randomly chosen examples for outputs there, showcasing their nonsense content forsp\.
The shortness of desired targets is a clear signal in the training data, expressed not only byus, but also by thespcheckpoints if exact inference is used with them \(see Table[8](https://arxiv.org/html/2608.19920#A1.T8)\)\. We should not be surprised byspexhibiting such failure modes\. When training with sequence parallelism \(SP\), each token can attend to any earlier one\. This property is cut during inference, when most KV information is evicted at some point according to a logic which SP was never aware of\. Clearly,models should be trained under the same conditions and restrictions which govern inference later on\. Our new method allows practitioners to do that even on a low budget, no matter what KV cache policy they like to use during inference\.
While not our main focus here, the different KV cache policies exhibit variable performance across the different datasets\. Ideally, the best policy is chosen for each task\. Our results are inconclusive when it comes to ranking the different H2O variants \(see Section[3\.1\.1](https://arxiv.org/html/2608.19920#S3.SS1.SSS1)\)\. However, one concerning datapoint is the poor performance ofh2o1βkor\\text\{h2o\}\_\{1k\}^\{\\text\{or\}\}onjson\_kvin Table[2](https://arxiv.org/html/2608.19920#S4.T2)\. In Table[7](https://arxiv.org/html/2608.19920#A1.T7), we see thatR=3\.7R=3\.7andp128=85%p\_\{128\}=85\\%for this logic, hinting to a similar failure mode thanspandno\. At least in this case, the decision in\([76](https://arxiv.org/html/2608.19920#bib.bib69)\)to score and evict batch dimensions together works much less well than the alternatives\.
## 5Conclusions
We showed how transformer language models with sparse attention can be fine\-tuned on a moderate hardware budget \(e\.g\., a single Nvidia A100 GPU with 40 GB RAM\)\. Our method works for any KV cache selection or compression policy and allows the model to co\-adapt with the policy, often outperforming models trained with exact attention \(sequence parallelism\)\. We also provide a much more efficient implementation of H2O sparse attention \(the leading policy in our experiments\) with dedicated scaled dot product attention \(SDPA\) kernel support\. By simplifying KV cache structure and clarifying the requirements on SDPA, we hope to direct more attention of the fast inference community on sparse attention \(see Section[3\.3\.1](https://arxiv.org/html/2608.19920#S3.SS3.SSS1)\), which despite its major potential for post\-training specialization via cache selection or compression policy design does not currently play a significant role in long\-context inference or fine\-tuning practice\.
In future work, we will combine context parallelism with sparse attention\. We are also considering kernel fusion ideas in order to narrow the latency gap further\. An important direction will be multi\-stream asynchronous implementations which allow for on\-the\-fly CPU offloading\([75](https://arxiv.org/html/2608.19920#bib.bib66)\)\. We believe that once the host memory of a system can be used without much synchronization overhead and less double buffering, many current difficulties with KV caching will be much diminished\. Finally, we hope thatπΊππ’ππ°πππ
πππππ\\mathtt\{KeysAndValues\}\([https://github\.com/awslabs/keys\_values](https://github.com/awslabs/keys_values)\), the open source library with which most experiments were run here \(see Section[A\.9](https://arxiv.org/html/2608.19920#A1.SS9)\), will make it easier to use, compare and extend sparse attention policies, work on which so far is somewhat cluttered when it comes to implementations\.
## References
- Ainslieet al\.\(2023\)J\. Ainslie, J\. Lee\-Thorp, M\. de Jong, Y\. Zemlyanskiy, LebrΓ³n, and F\. SanghaiGQA: training generalized multi\-query transformer models from multi\-head checkpoints\.InProceedings of the 2023 Conference on Empirical Methods in Natural Language Processing \(EMNLP\),pp\. 4895β4901\.Cited by:[Β§1](https://arxiv.org/html/2608.19920#S1.p2.1),[Β§2](https://arxiv.org/html/2608.19920#S2.p1.1),[Β§3\.1](https://arxiv.org/html/2608.19920#S3.SS1.p3.1)\.
- Baiet al\.\(2026\)Y\. Bai, Q\. Dong, T\. Jiang, X\. Lv, Z\. Du, A\. Zeng, J\. Tang, and J\. LiIndexCache: accelerating sparse attention via cross\-layer index reuse\.Technical reportTechnical ReportarXiv:2603\.12201 \[cs\.CL\]\.Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p3.1)\.
- Bansalet al\.\(2026\)R\. Bansal, A\. Zhang, R\. Tiwari, L\. Madaan, S\. Duvvuri, F\. Devvrit, D\. Brandfonbrener, D\. Alvarez\-Melis, P\. Bhargava, M\. Kale, and S\. JelassiLetβs \(not\) just put things in context: test\-time training for long\-context LLMs\.InInt\. Conf\. Learning Representations,Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p1.1)\.
- \[4\]M\. Beck, K\. PΓΆppel, M\. Spanring, A\. Auer, O\. Prudnikova, M\. Kopp, G\. Klambauer, J\. Brandstetter, and S\. HochreiterxLSTM: extended long short\-term memory\.See[22](https://arxiv.org/html/2608.19920#bib.bib83),Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p1.1),[Β§2](https://arxiv.org/html/2608.19920#S2.p3.1)\.
- D\. Belgrave, C\. Zhang, H\. Lin, R\. Pascanu, P\. Koniusz, M\. Ghassemi, and N\. Chen \(Eds\.\) \(2025\)D\. Belgrave, C\. Zhang, H\. Lin, R\. Pascanu, P\. Koniusz, M\. Ghassemi, and N\. Chen \(Eds\.\)Advances in neural information processing systems38\.Curran Associates\.Cited by:[18](https://arxiv.org/html/2608.19920#bib.bib16),[34](https://arxiv.org/html/2608.19920#bib.bib29),[40](https://arxiv.org/html/2608.19920#bib.bib31),[43](https://arxiv.org/html/2608.19920#bib.bib38)\.
- S\. Bengio, H\. Wallach, H\. Larochelle, K\. Grauman, N\. Cesa\-Bianchi, and R\. Garnett \(Eds\.\) \(2018\)S\. Bengio, H\. Wallach, H\. Larochelle, K\. Grauman, N\. Cesa\-Bianchi, and R\. Garnett \(Eds\.\)Advances in neural information processing systems31\.Curran Associates\.Cited by:[64](https://arxiv.org/html/2608.19920#bib.bib55)\.
- \[7\]W\. Brandon, M\. Mishra, A\. Nrusimha, R\. Panda, and J\. Ragan\-KelleyReducing transformer key\-value cache size with cross\-layer attention\.See[22](https://arxiv.org/html/2608.19920#bib.bib83),Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p1.1)\.
- Caiet al\.\(2025\)Z\. Cai, Y\. Zhang, B\. Gao, Y\. Liu, Y\. Li, T\. Liu, K\. Lu, W\. Xiong, Y\. Dong, J\. Hu, and W\. XiaoPyramidKV: dynamic KV cache compression based on pyramidal information funneling\.InConference on Language Modeling,Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p1.1)\.
- Chenet al\.\(2024\)Y\. Chen, S\. Qian, H\. Tang, X\. Lai, Z\. Liu, S\. Han, and J\. JiaLongLoRA: efficient fine\-tuning of long\-context large language models\.InInt\. Conf\. Learning Representations,Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p3.1)\.
- \[10\]T\. Dao, D\. Fu, S\. Ermon, A\. Rudra, and C\. RΓ©FlashAttention: fast and memory\-efficient exact attention with IO\-awareness\.See[47](https://arxiv.org/html/2608.19920#bib.bib82),Cited by:[4th item](https://arxiv.org/html/2608.19920#A1.I8.i4.p1.1),[Β§A\.6](https://arxiv.org/html/2608.19920#A1.SS6.p1.1),[Β§2](https://arxiv.org/html/2608.19920#S2.p2.1),[Β§3\.1\.1](https://arxiv.org/html/2608.19920#S3.SS1.SSS1.p3.1),[Β§3\.3](https://arxiv.org/html/2608.19920#S3.SS3.p2.1)\.
- \[11\]T\. Dao and A\. GuTransformers are SSMs: generalized models and efficient algorithms through structured state space duality\.See[50](https://arxiv.org/html/2608.19920#bib.bib77),pp\. 10041β10071\.Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p3.1)\.
- Devotoet al\.\(2025\)A\. Devoto, M\. Jeblick, and S\. JΓ©gouExpected attention: KV cache compression by estimating attention from future queries distribution\.Technical reportTechnical ReportarXiv:2510\.00636 \[cs\.AI\]\.Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p1.1)\.
- \[13\]Y\. Ding, L\. Zhang, C\. Zhang, Y\. Xu, N\. Shang, J\. Xu, F\. Yang, and M\. YangLongRoPE: extending LLM context window beyond 2 million tokens\.See[50](https://arxiv.org/html/2608.19920#bib.bib77),pp\. 11091β11104\.Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p4.1)\.
- Donget al\.\(2025\)J\. Dong, B\. Feng, D\. Guessous, Y\. Liang, and H\. HeFlexAttention: a programming model for generating optimized attention kernels\.InProceedings of the 8th MLSys Conference,pp\. 381β394\.Cited by:[4th item](https://arxiv.org/html/2608.19920#A1.I8.i4.p1.1),[Β§A\.6\.2](https://arxiv.org/html/2608.19920#A1.SS6.SSS2.p1.1),[Β§A\.6](https://arxiv.org/html/2608.19920#A1.SS6.p1.1),[Β§A\.6](https://arxiv.org/html/2608.19920#A1.SS6.p2.1),[Β§2](https://arxiv.org/html/2608.19920#S2.p1.1),[Β§2](https://arxiv.org/html/2608.19920#S2.p2.1),[2nd item](https://arxiv.org/html/2608.19920#S3.I1.i2.p1.1),[Β§3\.1\.1](https://arxiv.org/html/2608.19920#S3.SS1.SSS1.p3.1),[Β§3\.3](https://arxiv.org/html/2608.19920#S3.SS3.p2.1)\.
- etal\. \(2024\)D\. etal\.DeepSeek\-V2: a strong, economical, and efficient mixture\-of\-experts language model\.Technical reportTechnical ReportarXiv:2405\.04434 \[cs\.CL\]\.Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p1.1)\.
- etal\. \(2025\)D\. etal\.DeepSeek\-V3\.2: pushing the frontier of open large language models\.Technical reportTechnical ReportarXiv:2512\.02556 \[cs\.CL\]\.Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p3.1)\.
- Fenget al\.\(2025\)J\. Feng, S\. Huang, X\. Qu, G\. Zhang, Y\. Qin, B\. Zhong, C\. Jiang, J\. Chi, and W\. ZhongReTool: reinforcement learning for strategic tool use in LLMs\.Technical reportTechnical ReportarXiv:2504\.11536 \[cs\.CL\]\.Cited by:[Β§1](https://arxiv.org/html/2608.19920#S1.p1.1)\.
- \[18\]Y\. Feng, J\. Lv, Y\. Cao, X\. Xie, and S\. ZhouAda\-KV: optimizing KV cache eviction by adaptive budget allocation for efficient LLM inference\.See[5](https://arxiv.org/html/2608.19920#bib.bib84),Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p1.1)\.
- Gaoet al\.\(2023\)T\. Gao, A\. Wettig, H\. Yen, and D\. ChenHow to train long\-context language models \(effectively\)\.InProceedings of the 63rd Annual Meeting of the Association for Computational Linguistics \(ACL\),pp\. 2391β2404\.Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p4.1)\.
- Geet al\.\(2025\)S\. Ge, X\. Lin, Y\. Zhang, J\. Han, and H\. PengA little goes a long way: efficient long context training and inference with partial contexts\.InInt\. Conf\. Learning Representations,Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p3.1)\.
- Geet al\.\(2024\)S\. Ge, Y\. Zhang, L\. Liu, M\. Zhang, J\. Han, and J\. GaoModel tells you what to discard: adaptive KV cache compression for LLMs\.InInt\. Conf\. Learning Representations,Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p1.1)\.
- A\. Globerson, L\. Mackey, D\. Belgrave, A\. Fan, U\. Paquet, J\. Tomczak, and C\. Zhang \(Eds\.\) \(2024\)A\. Globerson, L\. Mackey, D\. Belgrave, A\. Fan, U\. Paquet, J\. Tomczak, and C\. Zhang \(Eds\.\)Advances in neural information processing systems37\.Curran Associates\.Cited by:[4](https://arxiv.org/html/2608.19920#bib.bib4),[7](https://arxiv.org/html/2608.19920#bib.bib5),[28](https://arxiv.org/html/2608.19920#bib.bib25),[30](https://arxiv.org/html/2608.19920#bib.bib27),[52](https://arxiv.org/html/2608.19920#bib.bib44),[61](https://arxiv.org/html/2608.19920#bib.bib51),[67](https://arxiv.org/html/2608.19920#bib.bib58),[79](https://arxiv.org/html/2608.19920#bib.bib71),[80](https://arxiv.org/html/2608.19920#bib.bib72),[83](https://arxiv.org/html/2608.19920#bib.bib74)\.
- Gu and Dao \(2023\)A\. Gu and T\. DaoMamba: linear\-time sequence modeling with selective state spaces\.Technical reportTechnical ReportarXiv:2312\.00752 \[cs\.LG\]\.Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p3.1)\.
- Hanet al\.\(2024\)C\. Han, Q\. Wang, H\. Peng, W\. Xiong, Y\. Chen, H\. Ji1, and S\. WangLM\-Infinite: zero\-shot extreme length generalization for large language models\.InProceedings of the 2024 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies \(NAACL\-HLT\),pp\. 3991β4008\.Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p1.1),[2nd item](https://arxiv.org/html/2608.19920#S4.I1.i2.p1.1)\.
- Hauzenbergeret al\.\(2026\)L\. Hauzenberger, N\. Schmidinger, A\. Hartl, D\. Stap, T\. Schmied, BΓΆck, S\. Klambauer, and S\. HochreiterKVpop β key\-value cache compression with predictive online pruning\.Technical reportTechnical ReportarXiv:2607\.05061 \[cs\.LG\]\.Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p1.1)\.
- Herrmannet al\.\(2019\)J\. Herrmann, O\. Beaumont, L\. Eyraud\-Dubois, J\. Hermann, A\. Joly, and A\. ShilovaOptimal checkpointing for heterogeneous chains: how to train deep neural networks with limited memory\.Technical reportTechnical ReportarXiv:1911\.13214 \[cs\.LG\]\.Cited by:[Β§A\.4\.2](https://arxiv.org/html/2608.19920#A1.SS4.SSS2.p2.1),[Β§3\.2](https://arxiv.org/html/2608.19920#S3.SS2.p4.1)\.
- Hochreiter and Schmidhuber \(1997\)S\. Hochreiter and J\. SchmidhuberLong short\-term memory\.Neural Computation9\(8\),pp\. 1735β1780\.Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p3.1)\.
- \[28\]C\. Hooper, S\. Kim, H\. Mohammadzadeh, M\. Mahoney, S\. Shao, K\. Keutzer, and A\. GholamiKVQuant: towards 10 million context length LLM inference with KV cache quantization\.See[22](https://arxiv.org/html/2608.19920#bib.bib83),Cited by:[Β§1](https://arxiv.org/html/2608.19920#S1.p2.1),[Β§2](https://arxiv.org/html/2608.19920#S2.p1.1)\.
- Huet al\.\(2022\)E\. Hu, Y\. Shen, P\. Wallis, Z\. Allen\-Zhu, Y\. Li, S\. Wang, L\. Wang, and W\. ChenLoRA: low\-rank adaptation of large language models\.InInt\. Conf\. Learning Representations,Cited by:[Β§4](https://arxiv.org/html/2608.19920#S4.p1.2)\.
- \[30\]H\. Jiang, Y\. Li, C\. Zhang, Q\. Wu, X\. Luo, S\. Ahn, Z\. Han, A\. Abdi, D\. Li, C\. Lin, Y\. Yang, and L\. QiuMInference 1\.0: accelerating pre\-filling for long\-context LLMs via dynamic sparse attention\.See[22](https://arxiv.org/html/2608.19920#bib.bib83),Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p1.1)\.
- S\. Koyejo, S\. Mohamed, A\. Agarwal, D\. Belgrave, K\. Cho, and A\. Oh \(Eds\.\) \(2022\)S\. Koyejo, S\. Mohamed, A\. Agarwal, D\. Belgrave, K\. Cho, and A\. Oh \(Eds\.\)Advances in neural information processing systems35\.Curran Associates\.Cited by:[66](https://arxiv.org/html/2608.19920#bib.bib57)\.
- A\. Krause, E\. Brunskill, K\. Cho, B\. Engelhardt, S\. Sabato, and J\. Scarlett \(Eds\.\) \(2023\)A\. Krause, E\. Brunskill, K\. Cho, B\. Engelhardt, S\. Sabato, and J\. Scarlett \(Eds\.\)International conference on machine learning40\.Vol\.202,Proceedings of Machine Learning Research\.Cited by:[55](https://arxiv.org/html/2608.19920#bib.bib47)\.
- Kwonet al\.\(2023\)W\. Kwon, Z\. Li, S\. Zhuang, Y\. Sheng, L\. Zheng, C\. Yu, J\. Gonzalez, H\. Zhang, and I\. StoicaEfficient memory management for large language model serving with PagedAttention\.InProceedings of the 29th Symposium on Operating Systems Principles,pp\. 611β626\.Cited by:[1st item](https://arxiv.org/html/2608.19920#A1.I7.i1.p1.1),[Β§A\.7](https://arxiv.org/html/2608.19920#A1.SS7.p2.1),[Β§A\.7](https://arxiv.org/html/2608.19920#A1.SS7.p3.1),[Β§A\.9](https://arxiv.org/html/2608.19920#A1.SS9.p3.1),[Β§1](https://arxiv.org/html/2608.19920#S1.p3.1),[Β§2](https://arxiv.org/html/2608.19920#S2.p4.1),[Β§3\.1](https://arxiv.org/html/2608.19920#S3.SS1.p3.1),[Β§3\.3](https://arxiv.org/html/2608.19920#S3.SS3.p1.1),[Β§3\.3](https://arxiv.org/html/2608.19920#S3.SS3.p4.1)\.
- \[34\]A\. LaΕcucki, K\. Staniszewski, P\. Nawrot, and E\. PontiInference\-time hyper\-scaling with kv cache compression\.See[5](https://arxiv.org/html/2608.19920#bib.bib84),Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p1.1)\.
- H\. Larochelle, M\. Ranzato, R\. Hadsell, M\.F\. Balcan, and H\. Lin \(Eds\.\) \(2020\)H\. Larochelle, M\. Ranzato, R\. Hadsell, M\.F\. Balcan, and H\. Lin \(Eds\.\)Advances in neural information processing systems33\.Curran Associates\.Cited by:[77](https://arxiv.org/html/2608.19920#bib.bib67)\.
- Liet al\.\(2023\)S\. Li, F\. Xue, C\. Baranwal, Y\. Li, and Y\. YouSequence parallelism: long sequence training from system perspective\.InProceedings of the 61st Annual Meeting of the Association for Computational Linguistics \(ACL\),pp\. 7376β7399\.Cited by:[3rd item](https://arxiv.org/html/2608.19920#S1.I1.i3.p1.1),[Β§2](https://arxiv.org/html/2608.19920#S2.p4.1)\.
- Liet al\.\(2026\)W\. Li, D\. Yu, G\. Luo, Y\. Zhang, Y\. Wu, J\. Liu, Z\. Gong, Z\. Liao, F\. Chao, and R\. JiOut of the memory barrier: a highly memory\-efficient training system for LLMs with million\-token contexts\.InInt\. Conf\. Learning Representations,Cited by:[Β§A\.8](https://arxiv.org/html/2608.19920#A1.SS8.p1.1),[Β§2](https://arxiv.org/html/2608.19920#S2.p4.1)\.
- Liet al\.\(2025a\)W\. Li, Y\. Zhang, G\. Luo, D\. Yu, and R\. JiTraining long\-context LLMs efficiently via chunk\-wise optimization\.InFindings of the Association for Computational Linguistics \(ACL\),pp\. 2691β2700\.Cited by:[1st item](https://arxiv.org/html/2608.19920#A1.I7.i1.p1.1),[Β§2](https://arxiv.org/html/2608.19920#S2.p4.1)\.
- \[39\]X\. Li, Z\. Xing, M\. Li, L\. Qu, H\. Zhen, Y\. Yao, W\. Liu, S\. Pan, and M\. YuanKVTuner: sensitivity\-aware layer\-wise mixed\-precision KV cache quantization for efficient and nearly lossless LLM inference\.See[57](https://arxiv.org/html/2608.19920#bib.bib78),Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p1.1)\.
- \[40\]Y\. Li, Y\. Huang, B\. Yang, B\. Venkitesh, A\. Locatelli, H\. Ye, T\. Cai, P\. Lewis, and D\. ChenSnapKV: LLM knows what you are looking for before generation\.See[5](https://arxiv.org/html/2608.19920#bib.bib84),pp\. 529β536\.Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p1.1)\.
- Liet al\.\(2025b\)Y\. Li, H\. Jiang, Q\. Wu, X\. Luo, S\. Ahn, C\. Zhang, A\. Abdi, D\. Li, J\. Gao, Y\. Yang, and L\. QiuSCBench: a KV cache\-centric analysis of long\-context methods\.InInt\. Conf\. Learning Representations,Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p1.1)\.
- Liuet al\.\(2024\)H\. Liu, M\. Zaharia, and P\. AbbeelRingAttention with blockwise transformers for near\-infinite context\.InInt\. Conf\. Learning Representations,Cited by:[1st item](https://arxiv.org/html/2608.19920#A1.I7.i1.p1.1),[Β§2](https://arxiv.org/html/2608.19920#S2.p4.1),[footnote 6](https://arxiv.org/html/2608.19920#footnote6)\.
- \[43\]Z\. Liu, S\. Wang, S\. Cheng, Z\. Zhao, K\. Wang, X\. Zhao, J\. Demmel, and Y\. YouStarTrail: concentric ring sequence parallelism for efficient near\-infinite\-context transformer model training\.See[5](https://arxiv.org/html/2608.19920#bib.bib84),Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p4.1)\.
- \[44\]Z\. Liu, J\. Yuan, H\. Jin, S\. Zhong, Z\. Xu, V\. Braverman, D\. Chen, and X\. HuKIVI: a tuning\-free asymmetric 2bit quantization for KV cache\.See[50](https://arxiv.org/html/2608.19920#bib.bib77),pp\. 32332β32344\.Cited by:[Β§1](https://arxiv.org/html/2608.19920#S1.p2.1),[Β§2](https://arxiv.org/html/2608.19920#S2.p1.1)\.
- Loshchilov and Hutter \(2017\)I\. Loshchilov and F\. HutterDecoupled weight decay regularization\.Technical reportTechnical ReportarXiv:1711\.05101 \[cs\.LG\]\.External Links:[Link](https://arxiv.org/abs/1711.05101)Cited by:[Β§4](https://arxiv.org/html/2608.19920#S4.p1.2)\.
- \[46\]P\. Nawrot, A\. Lancucki, M\. Chochowski, D\. Tarjan, and E\. PontiDynamic memory compression: retrofitting LLMs for accelerated inference\.See[50](https://arxiv.org/html/2608.19920#bib.bib77),pp\. 37396β37412\.Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p3.1)\.
- A\. Oh, T\. Naumann, A\. Globerson, K\. Saenko, M\. Hardt, and S\. Levine \(Eds\.\) \(2023\)A\. Oh, T\. Naumann, A\. Globerson, K\. Saenko, M\. Hardt, and S\. Levine \(Eds\.\)Advances in neural information processing systems36\.Curran Associates\.Cited by:[10](https://arxiv.org/html/2608.19920#bib.bib8),[51](https://arxiv.org/html/2608.19920#bib.bib43),[76](https://arxiv.org/html/2608.19920#bib.bib69)\.
- Penget al\.\(2024\)B\. Peng, J\. Quesnelle, H\. Fan, and E\. ShippoleYaRN: efficient context window extension of large language models\.InInt\. Conf\. Learning Representations,Cited by:[Β§4](https://arxiv.org/html/2608.19920#S4.p1.2)\.
- Qinet al\.\(2025\)Z\. Qin, Y\. Cao, M\. Lin, W\. Hu, S\. Fan, K\. Cheng, W\. Lin, and J\. LiCAKE: cascading and adaptive KV cache eviction with layer preferences\.InInt\. Conf\. Learning Representations,Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p1.1)\.
- R\. Salakhutdinov, Z\. Kolter, K\. Heller, A\. Weller, N\. Oliver, J\. Scarlett, and F\. Berkenkamp \(Eds\.\) \(2024\)R\. Salakhutdinov, Z\. Kolter, K\. Heller, A\. Weller, N\. Oliver, J\. Scarlett, and F\. Berkenkamp \(Eds\.\)International conference on machine learning41\.Proceedings of Machine Learning Research\.Cited by:[11](https://arxiv.org/html/2608.19920#bib.bib9),[13](https://arxiv.org/html/2608.19920#bib.bib13),[44](https://arxiv.org/html/2608.19920#bib.bib37),[46](https://arxiv.org/html/2608.19920#bib.bib40),[63](https://arxiv.org/html/2608.19920#bib.bib53)\.
- \[51\]T\. Schick, J\. Dwivedi\-Yu, R\. Dessi, R\. Raileanu, M\. Lomeli, E\. Hambro, L\. Zettlemoyer, N\. Cancedda, and T\. ScialomToolformer: language models can teach themselves to use tools\.See[47](https://arxiv.org/html/2608.19920#bib.bib82),Cited by:[Β§1](https://arxiv.org/html/2608.19920#S1.p1.1)\.
- \[52\]J\. Shah, G\. Bikshandi, Y\. Zhang, V\. Thakkar, P\. Ramani, and T\. DaoFlashAttention\-3: fast and accurate attention with asynchrony and low\-precision\.See[22](https://arxiv.org/html/2608.19920#bib.bib83),pp\. 68658β68685\.Cited by:[4th item](https://arxiv.org/html/2608.19920#A1.I8.i4.p1.1),[Β§2](https://arxiv.org/html/2608.19920#S2.p2.1)\.
- \[53\]N\. Shang, L\. Zhang, S\. Wang, G\. Zhang, G\. Lopez, F\. Yang, W\. Chen, and M\. YangLongRoPE2: near\-lossless LLM context window scaling\.See[57](https://arxiv.org/html/2608.19920#bib.bib78),Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p4.1)\.
- Shazeer \(2019\)N\. ShazeerFast transformer decoding: one write\-head is all you need\.Technical reportTechnical ReportarXiv:1911\.02150 \[cs\.NE\]\.Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p1.1)\.
- \[55\]Y\. Sheng, L\. Zheng, B\. Yuan, Z\. Li, M\. Ryabinin, D\. Fu, Z\. Xie, B\. Chen, C\. Barrett, J\. Gonzalez, P\. Liang, C\. Re, I\. Stoica, and C\. ZhangFlexGen: high\-throughput generative inference of large language models with a single GPU\.See[32](https://arxiv.org/html/2608.19920#bib.bib76),Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p1.1)\.
- \[56\]A\. Shutova, V\. Malinovskii, V\. Egiazarian, D\. Kuznedelev, D\. Mazur, S\. Nikita, I\. Ermakov, and D\. AlistarhCache me if you must: adaptive key\-value quantization for large language models\.See[57](https://arxiv.org/html/2608.19920#bib.bib78),Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p1.1)\.
- A\. Singh, M\. Fazel, D\. Hsu, S\. Lacoste\-Julien, F\. Berkenkamp, T\. Maharaj, K\. Wagstaff, and J\. Zhu \(Eds\.\) \(2025\)A\. Singh, M\. Fazel, D\. Hsu, S\. Lacoste\-Julien, F\. Berkenkamp, T\. Maharaj, K\. Wagstaff, and J\. Zhu \(Eds\.\)International conference on machine learning42\.Proceedings of Machine Learning Research\.Cited by:[39](https://arxiv.org/html/2608.19920#bib.bib32),[53](https://arxiv.org/html/2608.19920#bib.bib45),[56](https://arxiv.org/html/2608.19920#bib.bib48),[60](https://arxiv.org/html/2608.19920#bib.bib52)\.
- Staniszewski and LaΕcucki \(2026\)K\. Staniszewski and A\. LaΕcuckiKV cache transform coding for compact storage in LLM inference\.InInt\. Conf\. Learning Representations,Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p1.1)\.
- Suet al\.\(2024\)J\. Su, M\. Ahmed, Y\. Lu, S\. Pan, W\. Bo, and Y\. LiuRoFormer: enhanced transformer with rotary position embedding\.Neurocomputing568\(C\)\.Cited by:[Β§4](https://arxiv.org/html/2608.19920#S4.p1.2)\.
- \[60\]H\. Sun, L\. Chang, W\. Bao, S\. Zheng, N\. Zheng, X\. Liu, H\. Dong, Y\. Chi, and B\. ChenShadowKV: KV cache in shadows for high\-throughput long\-context LLM inference\.See[57](https://arxiv.org/html/2608.19920#bib.bib78),pp\. 57355β57373\.Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p1.1)\.
- \[61\]Y\. Sun, L\. Dong, Y\. Zhu, S\. Huang, W\. Wang, S\. Ma, Q\. Zhang, Z\. Wang, and F\. WeiYou only cache once: decoder\-decoder architectures for language models\.See[22](https://arxiv.org/html/2608.19920#bib.bib83),Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p3.1)\.
- Tanget al\.\(2025\)H\. Tang, Y\. Lin, J\. Lin, Q\. Han, D\. Ke, S\. Hong, Y\. Yao, and G\. WangRazorAttention: efficient KV cache compression through retrieval heads\.InInt\. Conf\. Learning Representations,Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p1.1)\.
- \[63\]J\. Tang, Y\. Zhao, K\. Zhu, G\. Xiao, B\. Kasikci, and S\. HanQuest: query\-aware sparsity for efficient long\-context llm inference\.See[50](https://arxiv.org/html/2608.19920#bib.bib77),pp\. 47901β47911\.Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p1.1)\.
- \[64\]A\. Vaswani, N\. Shazeer, N\. Parmar, J\. Uszkoreit, L\. Jones, A\. Gomez, L\. Kaiser, and I\. PolosukhinAttention is all you need\.See[6](https://arxiv.org/html/2608.19920#bib.bib79),pp\. 6000β6010\.Cited by:[Β§3\.1](https://arxiv.org/html/2608.19920#S3.SS1.p1.1)\.
- Wanget al\.\(2025\)G\. Wang, S\. Upasani, C\. Wu, D\. Gandhi, J\. Li, C\. Hu, B\. Li, and U\. ThakkerLLMs know what to drop: self\-attention guided KV cache eviction for efficient long\-context inference\.InInt\. Conf\. Learning Representations,Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p1.1)\.
- \[66\]J\. Wei, X\. Wang, D\. Schuurmans, M\. Bosma, B\. Ichter, F\. Xia, W\. Chi, Q\. Le, and D\. ZhouChain\-of\-thought prompting elicits reasoning in large language models\.See[31](https://arxiv.org/html/2608.19920#bib.bib81),Cited by:[Β§1](https://arxiv.org/html/2608.19920#S1.p1.1)\.
- \[67\]T\. Wu, Y\. Zhao, and Z\. ZhengAn efficient recipe for long context extension via middle\-focused positional encoding\.See[22](https://arxiv.org/html/2608.19920#bib.bib83),Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p4.1)\.
- Xiaoet al\.\(2025\)G\. Xiao, J\. Tang, J\. Zuo, J\. Guo, S\. Yang, H\. Tang, Y\. Fu, and S\. HanDuoAttention: efficient long\-context LLM inference with retrieval and streaming heads\.InInt\. Conf\. Learning Representations,Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p1.1)\.
- Xiaoet al\.\(2024\)G\. Xiao, Y\. Tian, B\. Chen, S\. Han, and M\. LewisEfficient streaming language models with attention sinks\.InInt\. Conf\. Learning Representations,Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p1.1),[1st item](https://arxiv.org/html/2608.19920#S4.I1.i1.p1.1),[footnote 12](https://arxiv.org/html/2608.19920#footnote12)\.
- Yanget al\.\(2025a\)A\. Yang, A\. Li, B\. Yang, B\. Zhang, B\. Hui, B\. Zheng, B\. Yu, C\. Gao, C\. Huang, C\. Lv, C\. Zheng, D\. Liu, F\. Zhou, F\. Huang, F\. Hu, H\. Ge, H\. Wei, H\. Lin, J\. Tang, J\. Yang, J\. Tu, J\. Zhang, J\. Yang, J\. Yang, J\. Zhou, J\. Zhou, J\. Lin, K\. Dang, K\. Bao, K\. Yang, L\. Yu, L\. Deng, M\. Li, M\. Xue, M\. Li, P\. Zhang, P\. Wang, Q\. Zhu, R\. Men, R\. Gao, S\. Liu, S\. Luo, T\. Li, T\. Tang, W\. Yin, X\. Ren, X\. Wang, X\. Zhang, X\. Ren, Y\. Fan, Y\. Su, Y\. Zhang, Y\. Zhang, Y\. Wan, Y\. Liu, Z\. Wang, Z\. Cui, Z\. Zhang, Z\. Zhou, and Z\. QiuQwen3 technical report\.Technical reportTechnical ReportarXiv:2505\.09388 \[cs\.CL\]\.Cited by:[Β§4](https://arxiv.org/html/2608.19920#S4.p1.2)\.
- Yanget al\.\(2025b\)S\. Yang, J\. Guo, H\. Tang, Q\. Hu, G\. Xiao, J\. Tang, Y\. Lin, Z\. Liu, Y\. Lu, and S\. HanLServe: efficient long\-sequence LLM serving with unified sparse attention\.InProceedings of the 8th MLSys Conference,Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p1.1)\.
- Yeet al\.\(2025\)Z\. Ye, L\. Chen, R\. Lai, W\. Lin, Y\. Zhang, S\. Wang, T\. Chen, B\. Kasikci, V\. Grover, A\. Krishnamurthy, and L\. CezeFlashInfer: efficient and customizable attention engine for LLM inference serving\.Technical reportTechnical ReportarXiv:2501\.01005 \[cs\.DC\]\.Cited by:[4th item](https://arxiv.org/html/2608.19920#A1.I8.i4.p1.1),[Β§A\.6](https://arxiv.org/html/2608.19920#A1.SS6.p2.1),[2nd item](https://arxiv.org/html/2608.19920#S1.I1.i2.p1.1),[Β§2](https://arxiv.org/html/2608.19920#S2.p2.1),[Β§3\.1\.1](https://arxiv.org/html/2608.19920#S3.SS1.SSS1.p3.1),[Β§3\.3](https://arxiv.org/html/2608.19920#S3.SS3.p2.1)\.
- Yenet al\.\(2025\)H\. Yen, T\. Gao, M\. Hou, K\. Ding, D\. Fleischer, P\. Izsak, M\. Wasserblat, and D\. ChenHelmet: how to evaluate long\-context models effectively and thoroughly\.InInt\. Conf\. Learning Representations,Cited by:[Β§A\.3\.1](https://arxiv.org/html/2608.19920#A1.SS3.SSS1.p1.1),[Β§4](https://arxiv.org/html/2608.19920#S4.p1.1),[Β§4](https://arxiv.org/html/2608.19920#S4.p2.1)\.
- Yuanet al\.\(2025\)J\. Yuan, H\. Gao, D\. Dai, J\. Luo, L\. Zhao, Z\. Zhang, Z\. Xie1, Y\. Wei, L\. Wang, Z\. Xiao, Y\. Wang, C\. Ruan, M\. Zhang, W\. Liang, and W\. ZengNative sparse attention: hardware\-aligned and natively trainable sparse attention\.Technical reportTechnical ReportarXiv:2502\.11089 \[cs\.CL\]\.Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p3.1)\.
- Yuanet al\.\(2026\)Z\. Yuan, H\. Sun, L\. Sun, and Y\. YeMegaTrain: full precision training of 100b\+ parameter large language models on a single GPU\.Technical reportTechnical ReportarXiv:2604\.05091 \[cs\.CL\]\.Cited by:[4th item](https://arxiv.org/html/2608.19920#A1.I7.i4.p1.1),[Β§5](https://arxiv.org/html/2608.19920#S5.p2.1)\.
- \[76\]Z\. Z\., Y\. Sheng, T\. Zhou\., T\. Chen, L\. Zheng, R\. Cai, Z\. Song, Y\. Tian, C\. Re, C\. Barrett, Z\. Wang, and B\. ChenH2O: heavy\-hitter oracle for efficient generative inference of large language models\.See[47](https://arxiv.org/html/2608.19920#bib.bib82),pp\. 34661β34710\.Cited by:[2nd item](https://arxiv.org/html/2608.19920#A1.I8.i2.p1.1),[2nd item](https://arxiv.org/html/2608.19920#S1.I1.i2.p1.1),[Β§1](https://arxiv.org/html/2608.19920#S1.p3.1),[Β§2](https://arxiv.org/html/2608.19920#S2.p1.1),[Β§3\.1\.1](https://arxiv.org/html/2608.19920#S3.SS1.SSS1.p1.1),[Β§3\.1\.1](https://arxiv.org/html/2608.19920#S3.SS1.SSS1.p2.1),[Β§3\.1\.1](https://arxiv.org/html/2608.19920#S3.SS1.SSS1.p3.1),[Β§3\.1](https://arxiv.org/html/2608.19920#S3.SS1.p3.1),[Β§3\.3](https://arxiv.org/html/2608.19920#S3.SS3.p1.1),[Β§3](https://arxiv.org/html/2608.19920#S3.p1.1),[3rd item](https://arxiv.org/html/2608.19920#S4.I1.i3.p1.1),[Β§4](https://arxiv.org/html/2608.19920#S4.p5.1)\.
- \[77\]M\. Zaheer, G\. Guruganesh, A\. Dubey, J\. Ainslie, C\. Alberti, S\. Ontanon, P\. Pham, A\. Ravula, Q\. Wang, L\. Yang, and A\. AhmedBig Bird: transformers for longer sequences\.See[35](https://arxiv.org/html/2608.19920#bib.bib80),pp\. 17283β17297\.Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p1.1)\.
- Zandiehet al\.\(2026\)A\. Zandieh, M\. Daliri, M\. Hadian, and V\. MirrokniTurboQuant: online vector quantization with near\-optimal distortion rate\.InInt\. Conf\. Learning Representations,Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p1.1)\.
- \[79\]T\. Zhang, J\. Yi, Z\. Xu, and A\. ShrivastavaKV cache is 1 bit per channel: efficient large language model inference with coupled quantization\.See[22](https://arxiv.org/html/2608.19920#bib.bib83),pp\. 3304β3331\.Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p1.1)\.
- \[80\]Z\. Zhang, R\. Chen, S\. Liu, Z\. Yao, O\. Ruwase, B\. Chen, X\. Wu, and Z\. WangFound in the middle: how language models use long contexts better via plug\-and\-play positional encoding\.See[22](https://arxiv.org/html/2608.19920#bib.bib83),pp\. 60755β60775\.Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p4.1)\.
- Zhanget al\.\(2024\)Z\. Zhang, S\. Liu, R\. Chen, B\. Kailkhura, B\. Chen, and A\. WangQ\-Hitter: a better token oracle for efficient LLM inference via sparse\-quantized KV cache\.InProceedings of Machine Learning and Systems \(MLSys\),P\. Gibbons, G\. Pekhimenko, and C\. D\. Sa \(Eds\.\),Vol\.6,pp\. 381β394\.Cited by:[Β§A\.5\.1](https://arxiv.org/html/2608.19920#A1.SS5.SSS1.p2.1),[Table 5](https://arxiv.org/html/2608.19920#A1.T5),[Β§2](https://arxiv.org/html/2608.19920#S2.p1.1),[Β§3\.3](https://arxiv.org/html/2608.19920#S3.SS3.p1.1)\.
- Zhaoet al\.\(2025\)Y\. Zhao, J\. Huang, J\. Hu, X\. Wang, Y\. Mao, D\. Zhang, Z\. Jiang, Z\. Wu, B\. Ai, A\. Wang, W\. Zhou, and Y\. ChenSWIFT: a scalable lightweight infrastructure for fine\-tuning\.InProceedings of the 39th Conference on Artificial Intelligence \(AAAI\),pp\. 29733β29735\.Cited by:[1st item](https://arxiv.org/html/2608.19920#A1.I7.i1.p1.1),[Β§2](https://arxiv.org/html/2608.19920#S2.p4.1),[1st item](https://arxiv.org/html/2608.19920#S4.I2.i1.p1.1)\.
- \[83\]L\. Zheng, L\. Yin, Z\. Xie, C\. Sun, J\. Huang, C\. Yu, S\. Cao, C\. Kozyrakis, I\. Stoica, J\. Gonzalez, C\. Barrett, and Y\. ShengSGLang: efficient execution of structured language model programs\.See[22](https://arxiv.org/html/2608.19920#bib.bib83),pp\. 62557β62583\.Cited by:[Β§A\.9](https://arxiv.org/html/2608.19920#A1.SS9.p3.1),[Β§2](https://arxiv.org/html/2608.19920#S2.p4.1)\.
- Zhouet al\.\(2026\)C\. Zhou, K\. Liu, Y\. Zhou, Q\. Qiao, J\. Gao, H\. Zhang, I\. Lu, N\. Ho, L\. Li, A\. Lei, C\. Cheng, S\. Chiang, Y\. Zeng, D\. Zhang, R\. Yang, K\. Chen, A\. Chen, P\. Ma, W\. Zhang, and C\. JinLongStraw: long\-context RL beyond 2M tokens under a fixed GPU budget\.Technical reportTechnical ReportarXiv:2607\.14952 \[cs\.LG\]\.Cited by:[Β§2](https://arxiv.org/html/2608.19920#S2.p4.1)\.
## Appendix AAppendix
### A\.1Notation\. Definitions
Here, we add some details missing in the main text\.
#### A\.1\.1Buffer Read/Write Access byπππππ\.πππππππ,πππππ\.ππππππ\\mathtt\{torch\.scatter\},\\mathtt\{torch\.gather\}
These linear operations are defined in[https://docs\.pytorch\.org/docs/2\.12/generated/torch\.Tensor\.scatter\_\.html](https://docs.pytorch.org/docs/2.12/generated/torch.Tensor.scatter_.html)\.πππππππβ\_\\mathtt\{scatter\\\_\}assigns values to entries in certain positions,ππππππ\\mathtt\{gather\}extracts values of entries at certain positions\. For reference,πππ\.πππππππβ\_β\(πππ,πππππ‘,πππ\)\\mathtt\{arr\.scatter\\\_\(dim,index,src\)\}requiresπππ\.ππππ==πππππ‘\.ππππ==πππ\.ππππ\\mathtt\{arr\.ndim==index\.ndim==src\.ndim\}andπππππ‘\.πππππ==πππ\.πππππ\\mathtt\{index\.shape==src\.shape\}, whereasπππ\.πππππ\\mathtt\{arr\.shape\}can differ on positionπππ\\mathtt\{dim\}\. Say thatπππ\.ππππ==πΉ\\mathtt\{arr\.ndim==3\}\. Then:
πππβ‘\[πππππ‘β‘\[π,π,π\],π,π\]=πππβ‘\[π,π,π\]\|dim==0πππβ‘\[π,πππππ‘β‘\[π,π,π\],π\]=πππβ‘\[π,π,π\]\|dim==1πππβ‘\[π,π,πππππ‘β‘\[π,π,π\]\]=πππβ‘\[π,π,π\]\|dim==2\\begin\{split\}\\mathtt\{arr\[index\[i,j,k\],j,k\]=src\[i,j,k\]\}\\quad&\|\\;dim==0\\\\ \\mathtt\{arr\[i,index\[i,j,k\],k\]=src\[i,j,k\]\}\\quad&\|\\;dim==1\\\\ \\mathtt\{arr\[i,j,index\[i,j,k\]\]=src\[i,j,k\]\}\\quad&\|\\;dim==2\\\\ \\end\{split\}Also, ifπππ=πππ\.ππππππβ‘\(πππ,πππππ‘\)\\mathtt\{res=arr\.gather\(dim,index\)\}, then:
πππβ‘\[π,π,π\]=πππβ‘\[πππππ‘β‘\[π,π,π\],π,π\]\|dim==0πππβ‘\[π,π,π\]=πππβ‘\[π,πππππ‘β‘\[π,π,π\],π\]\|dim==1πππβ‘\[π,π,π\]=πππβ‘\[π,π,πππππ‘β‘\[π,π,π\]\]\|dim==2\\begin\{split\}\\mathtt\{res\[i,j,k\]=arr\[index\[i,j,k\],j,k\]\}\\quad&\|\\;dim==0\\\\ \\mathtt\{res\[i,j,k\]=arr\[i,index\[i,j,k\],k\]\}\\quad&\|\\;dim==1\\\\ \\mathtt\{res\[i,j,k\]=arr\[i,j,index\[i,j,k\]\]\}\\quad&\|\\;dim==2\\\\ \\end\{split\}In our use case, we apply these operations to 4D arrays withπππ=πΈ\\mathtt\{dim=2\}, so thatπππ,πππ\\mathtt\{arr,src\}are 4D, butπππππ‘\\mathtt\{index\}is 3D\. This is done by broadcastingπππππ‘\\mathtt\{index\}along the final axis:πππππ‘\.ππππππππ£πβ‘\(βπ·\)\.ππ‘ππππβ‘\(βπ·,βπ·,βπ·,ππ\)\\mathtt\{index\.unsqueeze\(\-1\)\.extend\(\-1,\-1,\-1,d\_\{h\}\)\}\.
### A\.2Key\-Value Cache Policies
In this section, we present additional details about KV cache policies used in our experiments\.
#### A\.2\.1Policyπππππβ\_βπππππππ\\mathtt\{smart\\\_lastrec\}\(slr\)
Recall the simpleπππππππ\\mathtt\{lastrec\}\(lr\) policy from Section[4](https://arxiv.org/html/2608.19920#S4), which keeps the last recentNCβΞ²N\_\{C\}\-\\betaand firstΞ²\\betatokens in the cache\. One drawback of this policy is thatΞ²\\betais fixed, while prompts often start with initial important control information ofvariablelength\. Ourπππππβ\_βπππππππ\\mathtt\{smart\\\_lastrec\}policy is defined in terms of a regular expression for the end of this task control prefix, as well as some maximum prefix lengthMprefix<NCM\_\{\\text\{prefix\}\}<N\_\{C\}\. When processing the first \(prefill\) chunk, we search for the first match \(separately for each batch positionbb\)\. If this results in a prefix lengthMβ‘\(b\)β€MprefixM\(b\)\\leq M\_\{\\text\{prefix\}\}, this is used, otherwiseMβ‘\(b\)=MprefixM\(b\)=M\_\{\\text\{prefix\}\}\. For subsequent chunks and token positionstβ₯NCt\\geq N\_\{C\}, the policy isΟβ‘\(b,h,t\)=Mβ‘\(b\)\+modβ‘\(tβNC,NCβMβ‘\(b\)\)\\pi\(b,h,t\)=M\(b\)\+\\mathrm\{mod\}\(t\-N\_\{C\},N\_\{C\}\-M\(b\)\)\.
We also implemented a generalization where arange\[M0β\(b\),M1β\(b\)\)\[M\_\{0\}\(b\),M\_\{1\}\(b\)\)is protected from eviction\.111111We allow forM1β\(b\)<M0β\(b\)M\_\{1\}\(b\)<M\_\{0\}\(b\), in which case the protected area is\[0,M1β\(b\)\)βͺ\[M0β\(b\),NC\)\[0,M\_\{1\}\(b\)\)\\cup\[M\_\{0\}\(b\),N\_\{C\}\)\.Here,M0β\(b\)M\_\{0\}\(b\)is chosen as the position of the first non\-padding token, andM1β\(b\)M\_\{1\}\(b\)is chosen as above\. The idea is that initial padding tokens do not carry information and should not be attended to, so they can be evicted as soon as the cache is full\. In this variant, if all tokens in the prefill chunk are padding for somebb, the search for\[M0β\(b\),M1β\(b\)\)\[M\_\{0\}\(b\),M\_\{1\}\(b\)\)is shifted to subsequent chunks\. The prefix case above is obtained withM0β\(b\)=0M\_\{0\}\(b\)=0\. Surprisingly, in our experiments, the general variant did not improve over the prefix variant,121212This needs further analysis\. Maybe some initial padding tokens are used as so\-called βattention sinksβ\[[69](https://arxiv.org/html/2608.19920#bib.bib59)\]\.so thatπππππβ\_βπππππππ\\mathtt\{smart\\\_lastrec\}in Section[4](https://arxiv.org/html/2608.19920#S4)is the prefix variant throughout\.
### A\.3Long\-Context Benchmarks
#### A\.3\.1Helmet
Our training and evaluation suite is derived from Helmet\[[73](https://arxiv.org/html/2608.19920#bib.bib64)\], a benchmark designed for inference\-time evaluation of long\-context language models\. Helmet covers five capability categories across five context\-length scales \(8k to 128k tokens\)\. Helmet provides only a small number of instances per task\. For supervised fine\-tuning, we adapted it as follows\.
##### Instance Construction and Task Scope\.
We reconstruct each task from its upstream source data, following the original Helmet logic for forming contexts and controlling sequence length\. We focus on the 64k and 128k context\-length settings and include 10 tasks spanning five capability categories\. Table[3](https://arxiv.org/html/2608.19920#A1.T3)provides a summary of each task\.
##### Split Separation\.
For each task we produce two non\-overlapping partitions\. The instances used in the original Helmet evaluation are reserved as a held\-out*evaluation \(test\) set*\. All remaining instances are collected into a*development set*used for training\. For RAG tasks, we sample a single depth \(difficulty\) variant per query in the development set to prevent the model from memorising the same question paired with multiple distractor configurations\. For InfiniteBench QA/MC, we remove in\-context demonstrations from development instances because the demonstrations are drawn from the same small pool and would otherwise create data leakage during training\.
##### Evaluation Metrics\.
Our evaluation metrics are taken from the code coming with Helmet \([https://github\.com/princeton\-nlp/HELMET/blob/main/utils\.py](https://github.com/princeton-nlp/HELMET/blob/main/utils.py)\)\. Here, the output is a string generated by the model, the target is a string or a list of strings:
- β’SubEM: Depending on the dataset, the target can be a list of strings\. We normalize the output \(strip whitespace, quotes, and common phrases such as βAnswer:β\), map output and target\(s\) to lower\-case\. The value is 1 if at least one of the targets is a substring in the output, 0 otherwise\.
- β’Accuracy: The target is a numerical value\. We extract all numerical values from the output and find the value which occurs most often \(with ties, the value is chosen which appears first\)\. We then use exact match between this value and the target\.
- β’ROUGE\-F1: The target is a string\. We compute ROUGE\-N precision/recall/F1 between output \(after normalization as in SubEM\) and target\.
CategoryIDSourceMetricDevEvalRAGnqNatural QuestionsSubEM893600trivia\_qaTriviaQASubEM876600pop\_qaPopQASubEM192600hotpot\_qaHotpotQASubEM787300Many\-shot ICLtrec\_coarseTRECAccuracy1000500nluSNIPS NLUAccuracy2094500clinc150CLINC150Accuracy2600500Long\-doc QAinf\_qaInfiniteBench QAROUGE\-F1251100inf\_mcInfiniteBench MCAccuracy129100Synthetic Recalljson\_kvJSON\-KVSubEM500100Table 3:Overview of the 10 Helmet tasks\.*Dev*and*Eval*denote the number of instances in the training and evaluation partitions, respectively, at a single context\-length setting\.In what follows, we provide details for the different tasks\.
##### Retrieval\-augmented Generation \(RAG\)\.
Each instance consists of a natural\-language question, one or more gold passages, and a pool of hard\-negative distractors\. The context is formed by inserting gold passages at a random depth among the distractors, and the whole context is truncated to the target length\.Natural Questions\(NQ\) uses real Google search queries paired with Wikipedia passages\.TriviaQAuses trivia questions authored with independently collected evidence\.PopQAfocuses on long\-tail, entity\-centric questions generated from Wikidata triples; we filter the evaluation set to queries whose subject entities fall below a popularity threshold of 3\.HotpotQArequires multi\-hop reasoning across two gold passages\. Each of the six depth variants of a query places the gold passage\(s\) at a different relative position in the distractor pool\. All four tasks are evaluated with substring exact match \(SubEM\)\.
##### Many\-shot In\-context Learning\.
Three intent/question\-type classification datasets test the modelβs ability to exploit many labelled demonstrations placed entirely within the context window\. Unlike most other tasks, where demonstrations serve only as formatting guides, here they carry essential semantic information: each demonstration encodes a \(text, ordinal\-label\) pair, and the label\-to\-class mapping is only recoverable by reading the demonstrations\.TREC Coarsehas 6 question\-type classes;SNIPS NLUhas 68 intent classes;CLINC150has 151 intent classes\. The number of demonstrations is calibrated to fill the context window while maintaining an approximately balanced class distribution across shots\.
##### Long\-document QA\.
BothInfiniteBench QA\(Inf\-QA\) andInfiniteBench MC\(Inf\-MC\) are derived from full\-length novels whose named entities have been replaced by synthetic ones to prevent answer memorisation\. The source document typically exceeds the target context window, so it is truncated to fit\. Inf\-QA is open\-ended, evaluated by ROUGE\-F1; Inf\-MC is a 4\-way multiple\-choice variant evaluated by accuracy\.
##### Synthetic Recall\.
JSON\-KVasks the model to retrieve the value associated with a specified key from a large JSON dictionary that fills the context window\. This task is evaluated with SubEM and serves as controlled probes of the modelβs ability to locate and copy specific information over very long spans\.
### A\.4Gradient Computation
In this section, we provide additional details about our long\-context gradient computation method from Section[3\.2](https://arxiv.org/html/2608.19920#S3.SS2)\.
#### A\.4\.1Chunks, Cells, CPU Offloading
Recall that for long\-context inference or fine\-tuning with cache lengthNCN\_\{C\}, we split a sequence of lengthN\>NCN\>N\_\{C\}into1\+β\(NβNC\)/Sβ1\+\\lceil\(N\-N\_\{C\}\)/S\\rceilchunks, the first \(prefill\) chunk of lengthNCN\_\{C\}, subsequent chunks of lengthS<NCS<N\_\{C\}\. The chunk sizeSSis chosen according to a latency\-vs\-accuracy trade\-off, it is in general much shorter thanNCN\_\{C\}\(Section[3\.3](https://arxiv.org/html/2608.19920#S3.SS3)\)\. We also group chunks intocells\. The first cell consists of the prefill chunk alone, subsequent cells groupk=βΞ±βNC/Sβk=\\lfloor\\alpha N\_\{C\}/S\\rfloorofSS\-length chunks, whereΞ±\>0\\alpha\>0is a hyperparameter which defaults toΞ±=1\\alpha=1\.
In our gradient computation method,PyTorch autogradis run on cells\. WhileSSis chosen also with accuracy in mind, the choice ofkkandΞ±\\alphais determined by efficiency \(both runtime and memory\) only\. The idea is that theautogradGPU memory requirements are on the order of one KV cache buffer, if we exploit the linear recurrence \(see Section[3\.2](https://arxiv.org/html/2608.19920#S3.SS2)and below\)\. If a cell was much larger, thedeltanodes in the computation graph would dominate\. TheΞ±\\alphaparameter is adjusted so to not run out of memory\. Empirically, a smaller chunk sizeSSnecessitates a smallerΞ±\\alpha, likely due to overhead inautograd\(for constantΞ±\\alpha, smallerSSmeans largerkk, so a larger computation graph\)\. In our experiments, we choseΞ±=1\\alpha=1forS=2048S=2048,Ξ±=0\.75\\alpha=0\.75forS=1024S=1024, andΞ±=0\.1\\alpha=0\.1forS=128S=128, for a cache length ofNC=32768N\_\{C\}=32768and 40 GB of GPU memory\.
The grouping of chunks into cells is also relevant for long\-contextinference\. Recall thatLLdenotes the number of layers of our model, and layer inputs are of shape\(B,N,d\)\(B,N,d\), whered=Hqβ
dhd=H\_\{q\}\\cdot d\_\{h\}is the model embedding dimension\. For largeNN, not even the inputs to one layer can be kept in GPU memory\. This has implications for how inference is computed and what can be offloaded to CPU memory at which point during the process \(our library supports CPU offloading of KV cache buffers during the forward passes, as well as CPU offloading of weights during the backward pass, but this is not used in the experiments reported here\)\.
Outer loop over chunks, inner loop over layers: This seems the simplest ordering\. Also, layer inputs can be kept in GPU memory, with outputs overwriting inputs\. A major drawback is that either all KV cache buffers need to be kept in GPU memory, or they need to be read from and written back to CPU memory frequently\. When KV cache buffers are stored in quantized form, the quantization computation can be considerable\. For long\-context inference, this ordering is not suitable\.
Outer loop over layers, inner loop over chunks: With this ordering, KV cache buffers \(and even model weights\) can be offloaded to CPU for all but the currently active layer\. A drawback of this ordering is that layer inputs and outputs cannot be kept in GPU memory in total, so need to be offloaded eventually\. Still, this ordering is much better than the previous one\.
Outer loop over cells, middle loop over layers, inner loop over chunks per cell: This ordering provides a good compromise between the two previous ones\. Layer inputs and outputs can be kept in GPU memory, while KV cache buffers can be quantized and/or offloaded to CPU, which happens much less frequently\. We use this ordering in our implementation, also because CPU offloading of KV cache buffers is needed during gradient computation, so we can just reuse this code\.
#### A\.4\.2Summary of Method
Here, we present a detailed summary of our gradient computation technique\. Recall that we process a batch ofBBsequences of token lengthNN, and that caches in each layer have lengthNCN\_\{C\}\. ForNβ€NCN\\leq N\_\{C\}, our method reduces to standard training, so assume thatN\>NCN\>N\_\{C\}\. For simplicity, we assume that caches in all layers have the same lengthNCN\_\{C\}\. This is easy to relax, and our implementation does so\.
At the top level, our method runs a forward pass followed by a backward pass, just like standard code\. However, we runautogradon cells only, which constitute small parts of the overall model graph\. As with activation checkpointing\[[26](https://arxiv.org/html/2608.19920#bib.bib23)\], this means we need to run forward passes over the model three times \(instead of just once\)\. The first two passes are run in non\-autograd mode, checkpointing \(so called\) boundary information to CPU memory\. The third pass is part of the autograd runs on cells, which consume boundary information as inputs\.
We need some notation\. Letβ\\mathcal\{L\}denote the training loss for the current batch\. Layers are indexed byl=0,β¦,Lβ1l=\{0\},\\dots,\{L\-1\}, cells byc=0,β¦,Ncellsβ1c=\{0\},\\dots,\{N\_\{\\text\{cells\}\}\-1\}\.πΏl\\boldsymbol\{X\}\_\{l\}are inputs to layerll, of shape\(B,N,d\)\(B,N,d\), andπΏL\\boldsymbol\{X\}\_\{L\}is the top layer output\. Moreover,πΏl,c\\boldsymbol\{X\}\_\{l,c\}denotes the slice ofπΏl\\boldsymbol\{X\}\_\{l\}along axis 1 corresponding to the cell\. Finally, letπ²l,c\\boldsymbol\{K\}\_\{l,c\}denote the KV cache buffers131313These are really two tensors \(keys, values\), but we concatenate them into one for notational simplicity\.of shape\(2,B,Hk,NC,dh\)\(2,B,H\_\{k\},N\_\{C\},d\_\{h\}\)at the input of cellc\>0c\>0in layerll\.
Forward pass 1\. This runs in non\-autograd mode, using the ordering cells, then layers, then chunks detailed in Section[A\.4\.1](https://arxiv.org/html/2608.19920#A1.SS4.SSS1)\. Alongside:
- β’Store KV cache replay log in each layer, containing the decisions\{Οβ‘\(b,h,t\)\}\\\{\\pi\(b,h,t\)\\\}\.
- β’Checkpoint layer inputsπΏl\\boldsymbol\{X\}\_\{l\}to CPU memory for each layerl=0,β¦,Lβ1l=\{0\},\\dots,\{L\-1\}\. Our implementation allows to quantize them in order to save CPU memory and CPU\-GPU transfer time, but this is not activated in our experiments, since the time is subdominant\. We also checkpoint top layer outputsπΏL\\boldsymbol\{X\}\_\{L\}\.
Backward pass\. This runs backwards over layers\. In each step, we compute gradients for weights in layerllusing activation checkpointing\. We start with computing head gradientsββ/βπΏL\\partial\\mathcal\{L\}/\\partial\\boldsymbol\{X\}\_\{L\}based on top layer outputsπΏL\\boldsymbol\{X\}\_\{L\}, writing them to CPU \(in fact, head gradientsββ/βπΏl\\partial\\mathcal\{L\}/\\partial\\boldsymbol\{X\}\_\{l\}overwriteπΏl\\boldsymbol\{X\}\_\{l\}on CPU\)\. Next, we iterate over layersl=Lβ1,β¦,0l=\{L\-1\},\\dots,\{0\}:
- β’Forward pass 2 for layerll\(non\-autograd mode\)\. Runs over cellsc=1,β¦,Ncellsβ1c=\{1\},\\dots,\{N\_\{\\text\{cells\}\}\-1\}, computing the cache buffersπ²l,c\\boldsymbol\{K\}\_\{l,c\}and storing them to CPU\. These are quantized in order to save CPU memory and CPU\-GPU transfer time, and we overwrite the cache buffer checkpoints from previous layerl\+1l\+1\. Cache decisions are replayed from the log\. Note that we could checkpointallπ²l,c\\boldsymbol\{K\}\_\{l,c\}during forward pass 1, but this would requireLLtimes more CPU memory, and the extra time for forward pass 2 is subdominant\. Also note that we load inputsπΏl,c\\boldsymbol\{X\}\_\{l,c\}to forward pass 2 to GPU cell by cell: the wholeπΏl\\boldsymbol\{X\}\_\{l\}does not fit in GPU memory \(see Section[A\.4\.1](https://arxiv.org/html/2608.19920#A1.SS4.SSS1)\)\.
- β’Runautogradon each cell, iterating from right to left,c=Ncellsβ1,β¦,0c=\{N\_\{\\text\{cells\}\}\-1\},\\dots,\{0\}\. For each cellcc, we load layer inputsπΏl,c\\boldsymbol\{X\}\_\{l,c\}\(bottom\), layer head gradientsββ/βπΏl\+1,c\\partial\\mathcal\{L\}/\\partial\\boldsymbol\{X\}\_\{l\+1,c\}\(top\) and incoming cache buffersπ²l,c\\boldsymbol\{K\}\_\{l,c\}\(left; only forc\>0c\>0\) from CPU, while cache buffer head gradientsββ/βπ²l,c\+1\\partial\\mathcal\{L\}/\\partial\\boldsymbol\{K\}\_\{l,c\+1\}\(right; only forc<Ncellsβ1c<N\_\{\\text\{cells\}\}\-1\) are kept in GPU memory\. Cache decisions are replayed from the log\.autogradworks as follows: - βForward pass 3 for cell\(l,c\)\(l,c\), in autograd mode\. Whenever a KV cache buffer node \(πππ’π\\mathtt\{keys\},ππππππ\\mathtt\{values\}\) is created, we store anannotationin a list\. In theππππβ\_βππππ\\mathtt\{pack\\\_hook\}function, we match arguments of the right shape against all annotation\. For a match, we replace the argument with itsdeltaencoding, which is stored in the computation graph instead\. See Section[A\.4\.3](https://arxiv.org/html/2608.19920#A1.SS4.SSS3)for details\. - βBackward: WhenPyTorchtraverses the computation graph in reverse order, it callsππππππβ\_βππππ\\mathtt\{unpack\\\_hook\}for each node\. For eachdeltaencoding, we play the recurrence \([4](https://arxiv.org/html/2608.19920#S3.E4)\) backwards, replacingπππ’πβ²\\mathtt\{keys\}^\{\\prime\}byπππ’π\\mathtt\{keys\}orππππππβ²\\mathtt\{values\}^\{\\prime\}byππππππ\\mathtt\{values\}\. The outcome ofautogradon cell\(l,c\)\(l,c\)are gradients w\.r\.t\. layer weights \(which are accumulated\), a head gradientββ/βπΏl,c\\partial\\mathcal\{L\}/\\partial\\boldsymbol\{X\}\_\{l,c\}\(written to CPU, overwritingπΏl,c\\boldsymbol\{X\}\_\{l,c\}\), and a head gradientββ/βπ²l,c\\partial\\mathcal\{L\}/\\partial\\boldsymbol\{K\}\_\{l,c\}which replaces the previous one \(forc\>0c\>0\)\. At the end of the loop over cells, gradients w\.r\.t\. layer weights are complete, and the head gradientββ/βπ²l\\partial\\mathcal\{L\}/\\partial\\boldsymbol\{K\}\_\{l\}is on CPU, so the layer below can be addressed \(or, forl=0l=0, gradients w\.r\.t\. input embeddings can be computed based onββ/βπ²0\\partial\\mathcal\{L\}/\\partial\\boldsymbol\{K\}\_\{0\}\)\.
#### A\.4\.3Exploiting Linear Recurrence of KV Cache Buffers
Recall the recurrence between KV cache buffers for subsequent chunks from Section[3\.2](https://arxiv.org/html/2608.19920#S3.SS2)\. We can exploit this recurrence by askingPyTorchto storeπππππβ\_βπππ’\\mathtt\{delta\\\_key\}instead ofπππ’π\\mathtt\{keys\}andπππππβ\_βπππππ\\mathtt\{delta\\\_value\}instead ofππππππ\\mathtt\{values\}in the computation graph, restoring the latter from the former during backward using \([4](https://arxiv.org/html/2608.19920#S3.E4)\)\.
While this is simple in principle, we need to do it insidePyTorch autograd\. To this end, we use a mechanism calledautograd saved tensors hooks\([https://docs\.pytorch\.org/tutorials/intermediate/autograd\_saved\_tensors\_hooks\_tutorial\.html](https://docs.pytorch.org/tutorials/intermediate/autograd_saved_tensors_hooks_tutorial.html)\)\. This was designed in order to implement activation checkpointing by CPU offloading, but can be used for our purposes as well\. It works by allowing the specification of two functions:
- β’ππππβ\_βππππβ\(π\)βπβ‘\(π\)\\mathtt\{pack\\\_hook\}\(\\boldsymbol\{x\}\)\\to\\boldsymbol\{p\}\(\\boldsymbol\{x\}\): When building its computation graph during forward, this function is called for every arrayπ\\boldsymbol\{x\}PyTorch plans to store in the computation graph\. It then storesπβ‘\(π\)\\boldsymbol\{p\}\(\\boldsymbol\{x\}\)in the graph instead ofπ\\boldsymbol\{x\}\.
- β’ππππππβ\_βππππβ\(π\)βπβ‘\(π\)\\mathtt\{unpack\\\_hook\}\(\\boldsymbol\{p\}\)\\to\\boldsymbol\{x\}\(\\boldsymbol\{p\}\): When traversing the computation graph in reverse order during backward, PyTorch calls this function for every arrayπ\\boldsymbol\{p\}stored in the graph\. It then usesπβ‘\(π\)\\boldsymbol\{x\}\(\\boldsymbol\{p\}\)instead ofπ\\boldsymbol\{p\}\.
A major difficulty for us is the non\-selectiveness of this mechanism\. We do not want to pack all arrays stored in the graph, but only specific ones: the KV cache buffers \(for all other nodes, we just pass throughπβ‘\(π\)=π\\boldsymbol\{p\}\(\\boldsymbol\{x\}\)=\\boldsymbol\{x\}andπβ‘\(π\)=π\\boldsymbol\{x\}\(\\boldsymbol\{p\}\)=\\boldsymbol\{p\}\)\. Butππππβ\_βππππβ\(π\)\\mathtt\{pack\\\_hook\}\(\\boldsymbol\{x\}\)just takes aπππππ\.ππππππ\\mathtt\{torch\.Tensor\}argument, there is no obvious way for tagging the nodes we want\. Also, there is some delay between a node being created in the forward pass andππππβ\_βππππβ\(π\)\\mathtt\{pack\\\_hook\}\(\\boldsymbol\{x\}\)being called for it, we even detected some differences in the relative ordering\. Finally, due to internal operator fusion, we cannot even be sure whether any node appearing in the forward code is indeed stored in the graph\.
Our implementation maintains anannotation list, which is appended to during the forward code, while entries are removed duringππππβ\_βππππ\\mathtt\{pack\\\_hook\}calls\. Whenever a KV cache buffer update in the form of a statementπππ’πβ²=πππππππβ‘\(πππ’π,πππππ‘,πππ’β\_βπππ \)\\mathtt\{keys\}^\{\\prime\}=\\mathtt\{scatter\}\(\\mathtt\{keys\},\\mathtt\{index\},\\mathtt\{key\\\_new\}\)is passed in the forward code, we computeπππππβ\_βπππ’=ππππππβ‘\(πππ’π,πππππ‘\)\\mathtt\{delta\\\_key\}=\\mathtt\{gather\}\(\\mathtt\{keys\},\\mathtt\{index\}\), appending anannotationcontaining\(πππππ‘,πππππβ\_βπππ’\)\(\\mathtt\{index\},\\mathtt\{delta\\\_key\}\)and some meta\-data to the list\. Here,πππππβ\_βπππ’\\mathtt\{delta\\\_key\}serves a double role\. First, it is needed to reconstructπππ’π\\mathtt\{keys\}fromπππ’πβ²\\mathtt\{keys\}^\{\\prime\}inππππππβ\_βππππ\\mathtt\{unpack\\\_hook\}\. Second, it serves141414Ifπππππ‘\\mathtt\{index\}is small, we extend the fingerprint by additional random positions in order to avoid false matches\.as a βfingerprintβ ofπππ’π\\mathtt\{keys\}\. Namely, whenππππβ\_βππππβ\(π\)\\mathtt\{pack\\\_hook\}\(\\boldsymbol\{x\}\)is called, we need to match the argumentπ\\boldsymbol\{x\}against annotations\. This is first done by shape, filtering out most calls\. Next, for any annotation\(πππππ‘,πππππβ\_βπππ’\)\(\\mathtt\{index\},\\mathtt\{delta\\\_key\}\), we check whetherππππππβ‘\(π,πππππ‘\)=πππππβ\_βπππ’\\mathtt\{gather\}\(\\boldsymbol\{x\},\\mathtt\{index\}\)=\\mathtt\{delta\\\_key\}\. If so, we returnπβ‘\(π\)\\boldsymbol\{p\}\(\\boldsymbol\{x\}\)containingπππππβ\_βπππ’\\mathtt\{delta\\\_key\}and remove the annotation from the list\. If there is no match, we returnπβ‘\(π\)=π\\boldsymbol\{p\}\(\\boldsymbol\{x\}\)=\\boldsymbol\{x\}\.
Forππππππβ\_βππππβ\(π\)\\mathtt\{unpack\\\_hook\}\(\\boldsymbol\{p\}\), we reconstruct the sequencesπππ’π\\mathtt\{keys\}andππππππ\\mathtt\{values\}in reverse order\. Ifπ\\boldsymbol\{p\}is not a packed object, we returnπβ‘\(π\)=π\\boldsymbol\{x\}\(\\boldsymbol\{p\}\)=\\boldsymbol\{p\}\. Otherwise, we check the chunk number stored withπ\\boldsymbol\{p\}against the current state\(πππ’πβ²,ππππππβ²\)\(\\mathtt\{keys\}^\{\\prime\},\\mathtt\{values\}^\{\\prime\}\)\. If this fits, we reconstructπππ’π\\mathtt\{keys\}from\(πππ’πβ²,πππππβ\_βπππ’\)\(\\mathtt\{keys\}^\{\\prime\},\\mathtt\{delta\\\_key\}\)orππππππ\\mathtt\{values\}from\(ππππππβ²,πππππβ\_βπππππ\)\(\\mathtt\{values\}^\{\\prime\},\\mathtt\{delta\\\_value\}\), using \([4](https://arxiv.org/html/2608.19920#S3.E4)\)\. The new buffer overwrites the old one\.
Our implementation tracks which pack hook arguments of the right shape are not matched by annotations, and which annotations are not matched\. Both events do happen, but at a low rate\. It is important to note that we still obtain correct results even if some arguments are not matched\. This just means that a bit more GPU memory is being used\. What we need to avoid, however, are false matches, which we do by keeping fingerprints large enough\.
An important direction for future work is to simplify and robustify the mechanism for exploiting the linear recurrences\. We tried several simplifications\. One assumes that KV buffer nodes are created in exactly the same order asππππβ\_βππππβ\(π\)\\mathtt\{pack\\\_hook\}\(\\boldsymbol\{x\}\)calls\. If true, matching and managing the annotation list would be much simplified\. Unfortunately, this does not hold true, likely due to internals of PyTorch autograd we have no influence over\. In fact, the instructionπππ’πβ²=πππππππβ‘\(πππ’π,πππππ‘,πππ’β\_βπππ \)\\mathtt\{keys\}^\{\\prime\}=\\mathtt\{scatter\}\(\\mathtt\{keys\},\\mathtt\{index\},\\mathtt\{key\\\_new\}\)need not even trigger a call ofππππβ\_βππππ\\mathtt\{pack\\\_hook\}withπ=πππ’πβ²\\boldsymbol\{x\}=\\mathtt\{keys\}^\{\\prime\}\. The arrayπππ’πβ²\\mathtt\{keys\}^\{\\prime\}is processed further inside the SDPA code, and PyTorch may use some form of operator fusion\. The simplest solution would be to tag each KV buffer node during creation in a way that allows us to recognize the tag in a pack hook argumentπ\\boldsymbol\{x\}\. However, we did not find a way to do that yet\.
### A\.5Experimental Results
In this section, we provide additional experimental results beyond what is shown in the main text, as well as timing figures\. We also explain a failure mode we consistently observed when fine\-tuning a model with RingAttention to be used for inference with sparse attention\.
#### A\.5\.1Additional Results
64k datasets128k datasetsnqtri\_qahot\_qapop\_qanqtri\_qahot\_qapop\_qaexact\\mathrm\{exact\}\-\-\-\-\-\-\-\-lr2βk\\mathrm\{lr\}\_\{2k\}β47\.5β80\.2β57\.7β53\.8β35\.3β70\.5β37\.0β40\.2slr2βk\\mathrm\{slr\}\_\{2k\}β45\.3β80\.2β55\.3β52\.0β37\.5β69\.7β34\.7β34\.8h2o2βk\\mathrm\{h2o\}\_\{2k\}β42\.8β70\.8β44\.7β59\.0β20\.5β63\.2β12\.3β27\.3h2o2βkno\\mathrm\{h2o\}\_\{2k\}^\{\\text\{no\}\}β46\.0β82\.2β52\.7β59\.3β42\.2β78\.5β34\.3β39\.3h2o2βkor\\mathrm\{h2o\}\_\{2k\}^\{\\text\{or\}\}β44\.2β74\.7β47\.7β61\.0β43\.7β79\.8β25\.0β43\.3lr1βk\\mathrm\{lr\}\_\{1k\}β47\.5β80\.2β59\.7β54\.0β35\.8β70\.2β37\.7β37\.5slr1βk\\mathrm\{slr\}\_\{1k\}β49\.0β79\.0β55\.0β54\.3β37\.3β67\.3β32\.0β35\.7h2o1βk\\mathrm\{h2o\}\_\{1k\}β43\.2β71\.7β41\.7β59\.8β21\.0β62\.8β13\.0β27\.0h2o1βkno\\mathrm\{h2o\}\_\{1k\}^\{\\text\{no\}\}β47\.0β81\.2β50\.0β56\.7β40\.0β79\.8β32\.7β42\.3h2o1βkor\\mathrm\{h2o\}\_\{1k\}^\{\\text\{or\}\}β47\.5β76\.3β46\.7β58\.2β41\.8β79\.8β23\.7β39\.3Table 4:Results for long\-context inference with 5 KV cache policies and chunk sizes2048=2βk,1024=1βk2048=2k,1024=1k\(rows\)\. Here, the base checkpointQwen3\-4B\-Instruct\-2507is used without fine\-tuning\. The first rowexactis for exact inference \(sequence parallelism\)\. We showπππβ\_βππ‘πππβ\_βπππππ\\mathtt\{sub\\\_exact\\\_match\}values on test splits for different Helmet datasetsnq, trivia\_qa, hotpot\_qa, pop\_qa, limiting sequence lengths to 64k or 128k tokens\.In Table[4](https://arxiv.org/html/2608.19920#A1.T4), we provide results on Helmet 64k and 128k datasets for base checkpointsQwen3\-4B\-Instruct\-2507\(no fine\-tuning\)\. They should be related to results in Table[1](https://arxiv.org/html/2608.19920#S4.T1), where the base model was trained by our method \(columnsus\) or by sequence parallelism \(columnssp\)\.
64k datasetsnqtri\_qahot\_qapop\_qaslr128\\mathrm\{slr\}\_\{128\}β38\.8β66\.2β51\.7β41\.0h2o128\\mathrm\{h2o\}\_\{128\}β44\.5β65\.3β55\.7β54\.3h2o128no\\mathrm\{h2o\}\_\{128\}^\{\\text\{no\}\}β49\.0β74\.3β55\.0β56\.3h2o128or\\mathrm\{h2o\}\_\{128\}^\{\\text\{or\}\}β46\.8β67\.3β48\.3β52\.3qh2o2βk\\mathrm\{qh2o\}\_\{2k\}β37\.5β64\.0β40\.3β53\.7qh2o2βkno\\mathrm\{qh2o\}\_\{2k\}^\{\\text\{no\}\}β40\.2β65\.5β46\.3β53\.5Table 5:Results for long\-context inference with setups not covered in the main text\. We showπππβ\_βππ‘πππβ\_βπππππ\\mathtt\{sub\\\_exact\\\_match\}values on test splits for different Helmet datasetsnq, trivia\_qa, hotpot\_qa, pop\_qa, limiting sequence lengths to 64k or 128k tokens\.
slr128\\mathrm\{slr\}\_\{128\},h2o128\\mathrm\{h2o\}\_\{128\},h2o128no\\mathrm\{h2o\}\_\{128\}^\{\\text\{no\}\},h2o128or\\mathrm\{h2o\}\_\{128\}^\{\\text\{or\}\}use chunk sizeS=128S=128\.qh2o2βk\\mathrm\{qh2o\}\_\{2k\}andqh2o2βkno\\mathrm\{qh2o\}\_\{2k\}^\{\\text\{no\}\}are variants of Q\-Hitter\[[81](https://arxiv.org/html/2608.19920#bib.bib70)\]\.In Table[5](https://arxiv.org/html/2608.19920#A1.T5), we provide results on Helmet 64k and 128k datasets for setups not covered in the main text \(see Table[1](https://arxiv.org/html/2608.19920#S4.T1)\)\.slr128\\mathrm\{slr\}\_\{128\},h2o128\\mathrm\{h2o\}\_\{128\},h2o128no\\mathrm\{h2o\}\_\{128\}^\{\\text\{no\}\},h2o128or\\mathrm\{h2o\}\_\{128\}^\{\\text\{or\}\}use chunk sizeS=128S=128\. This runs significantly longer thanSβ\{1024,2048\}S\\in\\\{1024,2048\\\}used in the main text experiments, but allows the KV cache policy to make decisions 8 or 16 times more frequently\. However, at least in the experiments here, this does not lead to better results, justifying our choice of larger chunk sizes above\. We also ran experiments with Q\-Hitter\[[81](https://arxiv.org/html/2608.19920#bib.bib70)\], where KV cache buffers are quantized \(to 8 bits in our experiments\) and the decision score is a convex combination of \([3](https://arxiv.org/html/2608.19920#S3.E3)\) and a term quantifying the quantization error\. The results are consistently worse than for the H2O variants\.
#### A\.5\.2Running Time Figures
nqtri\_qahot\_qapop\_qaexact\\mathrm\{exact\}β258\.38 \(15\.14\)β266\.05 \(11\.31\)β262\.53 \(8\.18\)β236\.74 \(21\.44\)lr2βk\\mathrm\{lr\}\_\{2k\}β326\.07 \(21\.86\)β333\.28 \(16\.56\)β330\.76 \(22\.49\)β312\.29 \(27\.71\)slr2βk\\mathrm\{slr\}\_\{2k\}β323\.84 \(21\.19\)β333\.03 \(16\.19\)β330\.29 \(22\.55\)β310\.73 \(24\.46\)h2o2βk\\mathrm\{h2o\}\_\{2k\}β330\.83 \(21\.98\)β344\.83 \(16\.70\)β336\.79 \(23\.13\)β316\.02 \(27\.66\)h2o2βkno\\mathrm\{h2o\}\_\{2k\}^\{\\text\{no\}\}β331\.48 \(22\.10\)β341\.71 \(16\.65\)β337\.77 \(23\.12\)β317\.60 \(25\.16\)h2o2βkor\\mathrm\{h2o\}\_\{2k\}^\{\\text\{or\}\}β331\.83 \(22\.25\)β344\.85 \(16\.89\)β338\.46 \(23\.25\)β316\.94 \(25\.34\)lr1βk\\mathrm\{lr\}\_\{1k\}β364\.10 \(23\.28\)β374\.80 \(18\.62\)β375\.38 \(26\.38\)β343\.96 \(27\.99\)slr1βk\\mathrm\{slr\}\_\{1k\}β362\.84 \(23\.20\)β370\.55 \(18\.66\)β371\.18 \(25\.77\)β344\.77 \(27\.65\)h2o1βk\\mathrm\{h2o\}\_\{1k\}β378\.85 \(24\.88\)β385\.19 \(20\.21\)β382\.83 \(26\.94\)β359\.51 \(32\.00\)h2o1βkno\\mathrm\{h2o\}\_\{1k\}^\{\\text\{no\}\}β378\.61 \(24\.99\)β385\.29 \(19\.32\)β388\.77 \(27\.69\)β357\.95 \(29\.02\)h2o1βkor\\mathrm\{h2o\}\_\{1k\}^\{\\text\{or\}\}β378\.65 \(24\.79\)β385\.64 \(19\.46\)β382\.52 \(26\.91\)β358\.99 \(31\.74\)Table 6:Running time figures for training update step, for Helmet 128k datasets \(columns\), 5 KV cache policies and chunk sizes2048=2βk,1024=1βk2048=2k,1024=1k\(rows\)\. Batch size 8, running on 4 devices\. The step from 2k to 1k is 11% to 13% more expensive forππ,πππ\\mathtt\{lr\},\\mathtt\{slr\}, 12% to 14% more expensive forππΈπ\\mathtt\{h2o\}variants\. The step fromππ,πππ\\mathtt\{lr\},\\mathtt\{slr\}toππΈπ\\mathtt\{h2o\}variants is 2% to 3% more expensive for 2k, 3% to 4% more expensive for 1k\.In this section, we present running time figures\. First, we consider training updates \(batch size 8; four Nvidia A100s with 40 GB each\)\. For Helmet 128k datasets,exactuses sequence parallelism with batch size 2, processing 4 micro\-batches sequentially, whereas our method \(for different cache logics\) processes 4 micro\-batches in parallel\.
First, our method is about 30% more expensive thanexactfor chunk sizeS=2048S=2048\(2k\)\. Given that our method computes gradients on a single GPU independent of the sequence length, using advanced cache logics such as H2O, nested activation checkpointing and delta encoding of cache buffers, this overhead is surprisingly small\. Reasons for the overhead are explained in Section[3\.3](https://arxiv.org/html/2608.19920#S3.SS3)\. The gap can likely be narrowed further by operator fusion, increasing the chunk sizeautogradis operating with\. Next, we would expectS=1024S=1024\(1k\) to run slower thanS=2048S=2048\(2k\), because more chunks need to be processed sequentially; and H2O policies to run slower thanππ,πππ\\mathtt\{lr\},\\mathtt\{slr\}, because summed attention weights are required, and scores need to be computed and sorted\. We see that chunk size 1k variants run between 11% and 14% longer than 2k variants, which is substantial\. On the other hand, H2O variants are only between 2% to 4% slower thanππ,πππ\\mathtt\{lr\},\\mathtt\{slr\}\. At least with our fast SDPA implementation, there is no penalty for using more advanced policies over simple baselines\.
#### A\.5\.3Analysis of Errors
In this paper, we compare different ways of fine\-tuning a model to be used with sparse attention inference under different KV cache logics: training by sequence parallelism \(sp\) versus training with the new, resource\-efficient technique developed here \(us\)\. While for datasetsnq, trivia\_qa, hotpot\_qa, pop\_qacoming with theSubEMmetric, results are inconclusive \(see Table[1](https://arxiv.org/html/2608.19920#S4.T1)\),usstrongly outperformsspon datasetstrec\_coarse,nlu,clinc150,inf\_qa,inf\_mc,json\_kv, where the metric is mostlyAccuracy\(see Table[2](https://arxiv.org/html/2608.19920#S4.T2)\)\. In this section, we identify a consistent failure mode ofsp, both via randomly chosen examples and statistics on the generated samples\.
Recall details about Helmet datasets from Section[A\.3\.1](https://arxiv.org/html/2608.19920#A1.SS3.SSS1)\. Fortrec\_coarse,nlu,clinc150,inf\_mc, targets are single integers, and theAccuracymetric requires the correct number to appear most frequently in the output\. Fornq, trivia\_qa, hotpot\_qa, pop\_qa, json\_kv, targets are lists of noun phrases of one of few words, and theSubEMmetric requires one of the targets to be a substring of the output\. As with all sample\-based metrics in our experiments, we allow the model to generate up to 128 tokens, or otherwise terminate by emitting the<eos\>token\. A closer look at generated samples reveals a major failure mode ofsp:its outputs are far too long and contain mostly random nonsense\. Here are some randomly chosen examples of tasks and outputs underusandsprespectively\.
trec\_coarse / smart\_lastrec\_1024:
\-idx:10
raw\_target:β2β
exact\_match\_us:1
output\_us:β2β
exact\_match\_sp:0
output\_sp:β2
WhatistheaveragelifeexpectancyofafemaleinIrelandin1996?
1
WhatisthenameoftheAmericanwhowascapturedwhenhisplanewentdownover
Syrian\-heldLebanon?
1
0
WhatisthefullnameofthePLO?
1
3
Whatisthedifferencebetweenacollegeandauniversity?
1
4
WhatistheoriginofthetermβTheBrooklynSideββinbowling?
1
4
Whatistheoriginofthewordβassassinateββ?
1
4
Whatdoestheabbreviationcwt\.?mean?
1
3
Whatdoestheβ
\-idx:318
raw\_target:β5β
exact\_match\_us:1
output\_us:β5β
exact\_match\_sp:0
output\_sp:β1
WhatdoestheacronymCPRmean?
label:3
Whatdoestheabbreviationcwt\.?
3
WhatistheoriginofthenameβMabelβ?
3
Whatisthefullformof\.com?
3
WhatisthenameofthecompanythatmanufacturestheβAmericanGirlββdoll
collection?
4
Howmanypeoplewerekilledinthe1974fireatthePentagon?
4
Whatisthepurposeofacarbra?
4
Whatisthedifferencebetweenaclassicalandanacousticguitar?
1
Whatisthenameofthecompanythatmanufacturedthefirstphonograph?
4β
clinc150 / smart\_lastrec\_1024:
\-idx:25
raw\_target:β27β
exact\_match\_us:1
output\_us:β27β
exact\_match\_sp:1
output\_sp:β27
howlonguntilmynextdayoff
label\|15β
\-idx:78
raw\_target:β8β
exact\_match\_us:1
output\_us:β8β
exact\_match\_us:0
output\_sp:β8\\n\\ncanyoufindmearecipeforchocolatechipcookies\\nlabelle66\\
\\\\n66\\n66\\n66\\n66\\n66\\n66\\n66\\n66\\n66\\n66\\n66\\n66\\n66\\
\\\\n66\\n66\\n66\\n66\\n66\\n66\\n66\\n66\\n66\\n66\\n66\\n66\\n\\
66\\n66\\n66\\n66\\n66\\n66\\n66\\n66\\n66\\n66\\n66\\nβ
nlu / smart\_lastrec\_1024:
\-idx:63
raw\_target:β61β
exact\_match\_us:1
output\_us:β61β
exact\_match\_sp:0
output\_sp:β61
whatistheweatherinthecity
graph
57
howfarisitfromheretonewyork
graph
25
howmanycaloriesinabanana
graph:6
whatisthedefinitionofthewordpda
graph:11
whatisthebestmovietowatchthisweekend
graph:2
whatisthetimedifferencebetweeneasternandwestern
graph:49
turnonthewemoplug
graph:29
whatβstheweatherinboston
graph:57
whatβstheweatherinnewyork
graph:β
\-idx:245
raw\_target:β27β
exact\_match\_us:1
output\_us:β27β
exact\_match\_sp:1
output\_sp:β27
whatistheexchangeratebetweenusandcanada
graph:5
whatβsthenameofthepersonbehindthesongoftaylorswiftbacktodecember
graph:52
whatβstheweatherintampa
graph:27
whatistheweatherforecastfortheweek
graph:27
whatβstheweathergoingtobeliketodayintampa
graph:27
iwouldliketoknowtheweatherinnewyork
graph:27
whatisthetimeinthepacifictimezone
graph:63
whatistheβ
json\_kv / h2onorm\_1024:
\-idx:81
raw\_target:d823df41\-5af0\-4f11\-925d\-d0e8018cc5be
sub\_exact\_match\_us:1
output\_us:d823df41\-5af0\-4f11\-925d\-d0e8018cc5be
sub\_exact\_match\_sp:0
output\_sp:β923928d\-2e95\-426c\-8893\-b5e80880a88c
json
\{βcβ:β11984809639058896β,βaβ:β923928d\-2e95\-426c\-8893\-b5e80880a88cβ,βbβ:β0e2b980e\-da28\-4af1\-8896\-3f0cβ
\-idx:51
raw\_target:d8cdc4a6\-e37e\-4cd3\-b603\-ad33233518e9
sub\_exact\_match\_us:0
output\_us:d8cdc4a6\-e37e\-4cd3\-b6d3\-ad33233b18e9
sub\_exact\_match\_sp:0
output\_sp:β033a8782\-23d2\-488c\-ae99\-488f80bbc7d6\\n\\nKey:9c71e7e3\-9f60\-47f4\-baaa\-42dbca3e2715:\\
\\\\βd477445a\-0f1b\-4729\-b586\-10cbca0a5ba3\\β,\\n\\β9f71e7e3\-9f60\-47f4\-baaa\-4ββ
nq:
\-idx:418
raw\_target:
\-six
\-eight
sub\_exact\_match\_us:1
output\_us:βsixβ
sub\_exact\_match\_sp:0
output\_sp:β4hoopsareusedinagameofcroquet\.\(2blue,1redβ
\-idx:419
raw\_target:
\-six
\-eight
sub\_exact\_match\_us:0
output\_us:βfourβ
sub\_exact\_match\_sp:0
output\_sp:β20hoops\(10perside\)areusedinagameofcroquet\.β
pop\_qa:
\-idx:275
raw\_target:
\-Paraguay
\-RepublicofParaguay
\-py
\-β\\U0001F1F5\\U0001F1FEβ
\-HeartofSouthAmerica
sub\_exact\_match\_us:0
output\_us:βPeruβ
sub\_exact\_match\_sp:0
output\_sp:βPeru
Question:WhatisthecapitalofPeru?
Answer:Lima
Question:Inwhatregionβ
\-idx:273
raw\_target:
\-Paraguay
\-RepublicofParaguay
\-py
\-β\\U0001F1F5\\U0001F1FEβ
\-HeartofSouthAmerica
sub\_exact\_match\_us:0
output\_us:βPeruβ
sub\_exact\_match\_sp:0
output\_sp:βPeru
Question:WhatisthenameofthePeruviancitywheretheNationalLibraryis
located?β
Most other examples we inspected reveal the same failure mode\. Whileuslearns to output exactly the numerical answer or noun phrase and nothing else, sparse attention inference forsptends to output a lot of random content\. Recall that duringsptraining, each token can attend to any earlier one in principle\. Plugging in a cache eviction logic afterwards seems todiminish the modelβs ability to correctly stop generation\.151515For most cache logics, inference withspcheckpoints does stop with<eos\>for some samples, emitting sometimes as few as 5 or 7 tokens\. Moreover, for some logics anduscheckpoints, generation overshoots to 128 tokens as well \(albeit rarely\)\.Sometimes, the first number in the output is correct, but is followed by many others in the output\. Forclinc150, idx:25, we haveexact\_match\_sp = 1despite the output being partly random and containing another number\. Fornlu, idx:245, the correct answer 27 appears most frequently in nonsense output\. In thepop\_qaexample, whileusgets the country wrong \(βPeruβ instead of βParaguayβ\),spalso outputs nonsense extra content after the single word\. Forjson\_kv, idx:51, the output forusis only off by two letters, while that forspis nonsense, containing several UUIDs completely different from the target\.
trnslr1βk\\mathrm\{slr\}\_\{1k\}h2o1βkno\\mathrm\{h2o\}\_\{1k\}^\{\\text\{no\}\}h2o1βkor\\mathrm\{h2o\}\_\{1k\}^\{\\text\{or\}\}RRp128p\_\{128\}RRp128p\_\{128\}RRp128p\_\{128\}nqusβ1\.1Β±\\pmβ0\.8β0\.0Β±\\pmβ0\.0β1\.1Β±\\pmβ1\.0β0\.0Β±\\pmβ0\.0β1\.1Β±\\pmβ2\.7β0\.2Β±\\pmβ4\.1spβ35\.5Β±\\pmβ24\.1β99\.5Β±\\pmβ7\.1β35\.5Β±\\pmβ21\.6β100\.0Β±\\pmβ0\.0β36\.2Β±\\pmβ22\.1β99\.3Β±\\pmβ8\.1noβ35\.2Β±\\pmβ22\.0β97\.7Β±\\pmβ15\.1β35\.8Β±\\pmβ22\.8β99\.2Β±\\pmβ9\.1β34\.9Β±\\pmβ22\.0β97\.8Β±\\pmβ14\.6trivia\_qausβ1\.2Β±\\pmβ0\.8β0\.0Β±\\pmβ0\.0β1\.3Β±\\pmβ1\.0β0\.0Β±\\pmβ0\.0β1\.1Β±\\pmβ0\.7β0\.0Β±\\pmβ0\.0spβ35\.4Β±\\pmβ24\.1β97\.3Β±\\pmβ16\.1β38\.2Β±\\pmβ25\.2β99\.2Β±\\pmβ9\.1β42\.0Β±\\pmβ24\.4β96\.7Β±\\pmβ18\.0noβ43\.4Β±\\pmβ28\.5β87\.8Β±\\pmβ32\.7β46\.5Β±\\pmβ28\.9β96\.0Β±\\pmβ19\.6β48\.2Β±\\pmβ30\.4β95\.7Β±\\pmβ20\.4hotpot\_qausβ1\.0Β±\\pmβ0\.5β0\.0Β±\\pmβ0\.0β1\.0Β±\\pmβ0\.6β0\.0Β±\\pmβ0\.0β1\.3Β±\\pmβ1\.4β1\.0Β±\\pmβ9\.9spβ39\.2Β±\\pmβ31\.8β93\.0Β±\\pmβ25\.5β40\.9Β±\\pmβ31\.4β98\.3Β±\\pmβ12\.8β41\.4Β±\\pmβ31\.1β99\.0Β±\\pmβ9\.9noβ41\.0Β±\\pmβ30\.9β91\.7Β±\\pmβ27\.6β41\.3Β±\\pmβ31\.1β98\.0Β±\\pmβ14\.0β41\.4Β±\\pmβ31\.1β98\.7Β±\\pmβ11\.5pop\_qausβ1\.1Β±\\pmβ0\.6β0\.0Β±\\pmβ0\.0β1\.1Β±\\pmβ0\.5β0\.0Β±\\pmβ0\.0β1\.0Β±\\pmβ0\.4β0\.0Β±\\pmβ0\.0spβ53\.8Β±\\pmβ24\.9β98\.8Β±\\pmβ10\.7β54\.4Β±\\pmβ24\.7β99\.5Β±\\pmβ7\.1β55\.0Β±\\pmβ24\.7β98\.7Β±\\pmβ11\.5noβ58\.9Β±\\pmβ29\.3β93\.5Β±\\pmβ24\.7β60\.0Β±\\pmβ30\.9β98\.8Β±\\pmβ10\.7β58\.2Β±\\pmβ28\.9β96\.8Β±\\pmβ17\.5trec\_coarseusβ1\.0Β±\\pmβ0\.0β0\.0Β±\\pmβ0\.0β1\.0Β±\\pmβ0\.0β0\.0Β±\\pmβ0\.0β1\.0Β±\\pmβ0\.0β0\.0Β±\\pmβ0\.0spβ127\.6Β±\\pmβ6\.1β99\.6Β±\\pmβ6\.3β127\.3Β±\\pmβ8\.4β99\.0Β±\\pmβ9\.9β128\.0Β±\\pmβ0\.1β99\.6Β±\\pmβ6\.3noβ128\.0Β±\\pmβ0\.0β100\.0Β±\\pmβ0\.0β128\.0Β±\\pmβ0\.0β100\.0Β±\\pmβ0\.0β128\.0Β±\\pmβ0\.1β99\.4Β±\\pmβ7\.7nluusβ1\.0Β±\\pmβ0\.1β0\.0Β±\\pmβ0\.0β1\.0Β±\\pmβ0\.1β0\.0Β±\\pmβ0\.0β1\.0Β±\\pmβ0\.2β0\.0Β±\\pmβ0\.0spβ70\.4Β±\\pmβ21\.1β70\.6Β±\\pmβ45\.6β69\.0Β±\\pmβ21\.7β45\.6Β±\\pmβ49\.8β14\.6Β±\\pmβ18\.8β8\.4Β±\\pmβ27\.7noβ71\.7Β±\\pmβ20\.8β100\.0Β±\\pmβ0\.0β71\.7Β±\\pmβ20\.8β100\.0Β±\\pmβ0\.0β71\.7Β±\\pmβ20\.8β99\.8Β±\\pmβ4\.5clinc150usβ1\.0Β±\\pmβ0\.1β0\.0Β±\\pmβ0\.0β1\.0Β±\\pmβ0\.1β0\.0Β±\\pmβ0\.0β1\.0Β±\\pmβ0\.1β0\.0Β±\\pmβ0\.0spβ30\.2Β±\\pmβ28\.6β43\.8Β±\\pmβ49\.6β32\.6Β±\\pmβ31\.0β49\.8Β±\\pmβ50\.0β57\.6Β±\\pmβ32\.2β87\.6Β±\\pmβ33\.0noβ59\.9Β±\\pmβ19\.7β100\.0Β±\\pmβ0\.0β59\.9Β±\\pmβ19\.7β100\.0Β±\\pmβ0\.0β60\.1Β±\\pmβ20\.5β100\.0Β±\\pmβ0\.0inf\_qausβ1\.1Β±\\pmβ0\.8β0\.0Β±\\pmβ0\.0β1\.2Β±\\pmβ0\.8β0\.0Β±\\pmβ0\.0β1\.2Β±\\pmβ0\.8β0\.0Β±\\pmβ0\.0spβ45\.7Β±\\pmβ32\.4β100\.0Β±\\pmβ0\.0β45\.7Β±\\pmβ32\.4β99\.0Β±\\pmβ9\.9β45\.8Β±\\pmβ32\.3β97\.0Β±\\pmβ17\.1noβ45\.5Β±\\pmβ32\.3β95\.0Β±\\pmβ21\.8β45\.7Β±\\pmβ32\.4β99\.0Β±\\pmβ9\.9β45\.7Β±\\pmβ32\.4β96\.0Β±\\pmβ19\.6inf\_mcusβ1\.0Β±\\pmβ0\.0β0\.0Β±\\pmβ0\.0β2\.3Β±\\pmβ12\.6β1\.0Β±\\pmβ9\.9β1\.0Β±\\pmβ0\.0β0\.0Β±\\pmβ0\.0spβ128\.0Β±\\pmβ0\.0β100\.0Β±\\pmβ0\.0β128\.0Β±\\pmβ0\.0β100\.0Β±\\pmβ0\.0β127\.9Β±\\pmβ1\.2β98\.0Β±\\pmβ14\.0noβ128\.0Β±\\pmβ0\.0β100\.0Β±\\pmβ0\.0β128\.0Β±\\pmβ0\.0β100\.0Β±\\pmβ0\.0β128\.3Β±\\pmβ3\.6β97\.0Β±\\pmβ17\.1json\_kvusβ1\.1Β±\\pmβ0\.1β0\.0Β±\\pmβ0\.0β1\.0Β±\\pmβ0\.0β0\.0Β±\\pmβ0\.0β3\.7Β±\\pmβ1\.0β85\.0Β±\\pmβ35\.7spβ4\.1Β±\\pmβ0\.3β100\.0Β±\\pmβ0\.0β4\.1Β±\\pmβ0\.3β100\.0Β±\\pmβ0\.0β4\.1Β±\\pmβ0\.3β98\.0Β±\\pmβ14\.0noβ4\.1Β±\\pmβ0\.3β100\.0Β±\\pmβ0\.0β4\.1Β±\\pmβ0\.3β100\.0Β±\\pmβ0\.0β4\.1Β±\\pmβ0\.3β100\.0Β±\\pmβ0\.0Table 7:Token length statistics of generated samples for 10 Helmet datasets \(of context width 128k\) and 3 cache logics\.trndenotes model checkpoint being used:ususes our novel method with the same cache policy in place,spis using sequence parallelism,nois the base checkpointQwen3\-4B\-Instruct\-2507\(no fine\-tuning\)\.RRis based on the ratio of output length to target length \(in tokens\),p128p\_\{128\}\(in percent\) is the fraction of outputs of maximal size 128 \(means, and stddevs over all test set samples\)\.nqtri\_qahot\_qapop\_qatrec\_cRRp128p\_\{128\}RRp128p\_\{128\}RRp128p\_\{128\}RRp128p\_\{128\}RRp128p\_\{128\}β1\.1Β±\\pmβ1\.1β0\.0Β±\\pmβ0\.0β1\.0Β±\\pmβ0\.6β0\.0Β±\\pmβ0\.0β1\.1Β±\\pmβ0\.6β0\.0Β±\\pmβ0\.0β1\.0Β±\\pmβ0\.4β0\.0Β±\\pmβ0\.0β1\.0Β±\\pmβ0\.0β0\.0Β±\\pmβ0\.0nluclc150inf\_qainf\_mcjson\_kvRRp128p\_\{128\}RRp128p\_\{128\}RRp128p\_\{128\}RRp128p\_\{128\}RRp128p\_\{128\}β1\.0Β±\\pmβ0\.1β0\.0Β±\\pmβ0\.0β1\.0Β±\\pmβ0\.0β0\.0Β±\\pmβ0\.0β1\.2Β±\\pmβ0\.9β0\.0Β±\\pmβ0\.0β1\.0Β±\\pmβ0\.0β0\.0Β±\\pmβ0\.0β1\.0Β±\\pmβ0\.0β0\.0Β±\\pmβ0\.0Table 8:Token length statistics of generated samples for 10 Helmet datasets \(of context width 128k\) for training and inference with exact attention \(sequence parallelism\)\.In order to quantify the prevalence of this failure mode across all datasets and setups, we use two statistics, estimated over all samples generated for each dataset and cache logic:
R=lenβ‘\(ππππππ\)lenβ‘\(ππππππ\),p128=I\{len\(ππππππ\)=128\}\.R=\\frac\{\\mathrm\{len\}\(\\mathtt\{output\}\)\}\{\\mathrm\{len\}\(\\mathtt\{target\}\)\},\\quad p\_\{128\}=\\mathrm\{I\}\_\{\\\{\\mathrm\{len\}\(\\mathtt\{output\}\)=128\\\}\}\.Here,lenβ‘\(β
\)\\mathrm\{len\}\(\\cdot\)denotes length in tokens, and samples are capped at 128 tokens\. For some datasets, the targets are a list, in which caseππππππ\\mathtt\{target\}is the longest entry appearing as substring inππππππ\\mathtt\{output\}, or the longest entry otherwise\. Statistics for 10 Helmet datasets and 3 setups are shown in Table[7](https://arxiv.org/html/2608.19920#A1.T7)\. Withus, we haveRβ1R\\approx 1across datasets and setups: outputs are close in length to targets, the model learned the desired output type and stops generation properly\. But withsp,RRtends to be large, andp128p\_\{128\}is often close to 100%\. This is not a property of thespcheckpoints\. As seen in Table[8](https://arxiv.org/html/2608.19920#A1.T8),Rβ1R\\approx 1andp128β0p\_\{128\}\\approx 0if exact inference is used\. Instead, failures come from the inconsistency between training and inference\.
If we relate numbers in Table[7](https://arxiv.org/html/2608.19920#A1.T7)with good results in Table[1](https://arxiv.org/html/2608.19920#S4.T1)forspand in Table[4](https://arxiv.org/html/2608.19920#A1.T4)forno, this points to a shortcoming of theSubEMmetric used for these datasets\. Insensitive to any type and amount of nonsense extra output,it only requires the target to be contained in the output, without requiring a definite way to extract the substring\. Once such a requirement is added, as inAccuracy, performance forspandnoplummets\. In any case, by not even providing succinct outputs \(a very clear signal in the data\),spclearly does not behave satisfactory\. While the tolerance ofSubEM\(and alsoAccuracy, to a lesser extent\) to any amount of extra output is intended to not disadvantage LLMs \(which βsugar\-coatβ answers in longer sentences\), it makes the metrics blind to extra nonsense content returned\. We should at least ask for a deterministic way to extract the response from the output\.
### A\.6Computing Summed Attention Weights in SDPA
As noted in Section[3\.1\.1](https://arxiv.org/html/2608.19920#S3.SS1.SSS1)and Section[3\.3\.1](https://arxiv.org/html/2608.19920#S3.SS3.SSS1), KV cache policies like H2O or related ones need summed attention weightsβimb,h,i,j\\sum\_\{i\}m\_\{b,h,i,j\}for each\(b,h,j\)\(b,h,j\)\. This array of shape\(B,Hq,Nk\)\(B,H\_\{q\},N\_\{k\}\)can be obtained as byproduct of SDPA, which returnsπ\\boldsymbol\{Y\}of shape\(B,Hq,Nq,dh\)\(B,H\_\{q\},N\_\{q\},d\_\{h\}\)\. Note that summed attention weights are smaller than attention outputs, so there is a priori no reason for not returning them\. However, all fast SDPA codes we know of, do not return this information\. FlexAttention\[[14](https://arxiv.org/html/2608.19920#bib.bib14)\]can return log\-sum\-exp valueslog\(π¨π\)Nk\\log\(\\boldsymbol\{A\}\\boldsymbol\{1\}\{\}\_\{N\_\{k\}\}\), whereπ¨=ππππ\(dhβ1/2πΈπ²T\)\\boldsymbol\{A\}=\\mathtt\{mask\}\(d\_\{h\}^\{\-1/2\}\\boldsymbol\{Q\}\\boldsymbol\{K\}^\{T\}\)is the argument ofπππππππ‘\\mathtt\{softmax\}, likely because this is directly computed during FlashAttention\[[10](https://arxiv.org/html/2608.19920#bib.bib8)\]\.
Our implementation containsTritoncode for computing summed attention weights alongside a FlashInfer SDPA kernel\[[72](https://arxiv.org/html/2608.19920#bib.bib63)\]\. This is an add\-on, and it would be better if leading SDPA codes returned summed attention weights directly\. In this section, we detail how this can be done \(even though we have not implemented this\)\. We also show how to compute them with FlexAttention\[[14](https://arxiv.org/html/2608.19920#bib.bib14)\], using two calls instead of one\. This is contained in our implementation as baseline\.
#### A\.6\.1FlashAttention for Summed Attention Weights
FlashAttention works by essentially computing the attention weights tensorπ΄\\boldsymbol\{M\}in blocks, using a lattice tiling along the query and the key axes\. It can be understood asmap\-reduce, wheremapis independent per cell\. More precisely, the full attention weights have shape\(B,Hq,Nq,Nk\)\(B,H\_\{q\},N\_\{q\},N\_\{k\}\)\. In the following, we drop\(B,Hq\)\(B,H\_\{q\}\), treating them as βbatchβ dimensions\. Use cell indices\(r,s\)\(r,s\)and index rangesIβ‘\(r\)I\(r\),Jβ‘\(s\)J\(s\), so that the union of allIβ‘\(r\)I\(r\)covers\{0,β¦,Nqβ1\}\\\{\{0\},\\dots,\{N\_\{q\}\-1\}\\\}and the union of allJβ‘\(s\)J\(s\)covers\{0,β¦,Nkβ1\}\\\{\{0\},\\dots,\{N\_\{k\}\-1\}\\\}\. When computing the attention outputs,reduceoperates along the key axis\. Define an additional auxiliary tensor of shape\(B,Hq,Nq\)\(B,H\_\{q\},N\_\{q\}\), with values
πr,s:=log\(exp\(π¨Iβ‘\(r\),Jβ‘\(s\)\)π\|Jβ‘\(s\)\|\),π¨I,J:=ππππ\(dhβ1/2πΈI,β
π²J,β
T\)\.\\boldsymbol\{\\lambda\}\_\{r,s\}:=\\log\\left\(\\exp\\left\(\\boldsymbol\{A\}\_\{I\(r\),J\(s\)\}\\right\)\\boldsymbol\{1\}\_\{\|J\(s\)\|\}\\right\),\\quad\\boldsymbol\{A\}\_\{I,J\}:=\\mathtt\{mask\}\\left\(d\_\{h\}^\{\-1/2\}\\boldsymbol\{Q\}\_\{I,\\cdot\}\\boldsymbol\{K\}\_\{J,\\cdot\}^\{T\}\\right\)\.Reduction works as:
πr,s1βs2=maxβ‘\{πr,s1,πr,s2\}\+log1pβ‘\(expβ‘\(β\|πr,s1βπr,s2\|\)\),πr,s1βs2=\(diagβ‘expβ‘\(πr,s1βπr,s1βs2\)\)βπr,s1\+\(diagβ‘expβ‘\(πr,s2βπr,s1βs2\)\)βπr,s2\.\\begin\{split\}\\boldsymbol\{\\lambda\}\_\{r,s\_\{1\}\\oplus s\_\{2\}\}&=\\max\\left\\\{\\boldsymbol\{\\lambda\}\_\{r,s\_\{1\}\},\\boldsymbol\{\\lambda\}\_\{r,s\_\{2\}\}\\right\\\}\+\\mathrm\{log1p\}\\left\(\\exp\\left\(\-\\left\|\\boldsymbol\{\\lambda\}\_\{r,s\_\{1\}\}\-\\boldsymbol\{\\lambda\}\_\{r,s\_\{2\}\}\\right\|\\right\)\\right\),\\\\ \\boldsymbol\{Y\}\_\{r,s\_\{1\}\\otimes s\_\{2\}\}&=\\left\(\\diag\\exp\\left\(\\boldsymbol\{\\lambda\}\_\{r,s\_\{1\}\}\-\\boldsymbol\{\\lambda\}\_\{r,s\_\{1\}\\otimes s\_\{2\}\}\\right\)\\right\)\\boldsymbol\{Y\}\_\{r,s\_\{1\}\}\+\\left\(\\diag\\exp\\left\(\\boldsymbol\{\\lambda\}\_\{r,s\_\{2\}\}\-\\boldsymbol\{\\lambda\}\_\{r,s\_\{1\}\\otimes s\_\{2\}\}\\right\)\\right\)\\boldsymbol\{Y\}\_\{r,s\_\{2\}\}\.\\end\{split\}We can now runmapindependently for all\(r,s\)\(r,s\), thenreducealongssfor allrr\.
Summed attention weights are given byπββNk\\boldsymbol\{w\}\\in\\mathbb\{R\}^\{N\_\{k\}\}:
πT=πNqTβexpβ‘\(π¨βπβπNkT\)\.\\boldsymbol\{w\}^\{T\}=\\boldsymbol\{1\}\_\{N\_\{q\}\}^\{T\}\\exp\\left\(\\boldsymbol\{A\}\-\\boldsymbol\{\\lambda\}\\boldsymbol\{1\}\_\{N\_\{k\}\}^\{T\}\\right\)\.Define
π~r,s=expβ‘\(π¨Iβ‘\(r\),Jβ‘\(s\)βπr,sβπ\|Jβ‘\(s\)\|T\),πr,s=\(diagβ‘expβ‘\(πr,sβπr\)\)βπ~r,s=expβ‘\(π¨Iβ‘\(r\),Jβ‘\(s\)βπrβπ\|Jβ‘\(s\)\|T\)\.\\begin\{split\}\\tilde\{\\boldsymbol\{F\}\}\_\{r,s\}&=\\exp\\left\(\\boldsymbol\{A\}\_\{I\(r\),J\(s\)\}\-\\boldsymbol\{\\lambda\}\_\{r,s\}\\boldsymbol\{1\}\_\{\|J\(s\)\|\}^\{T\}\\right\),\\\\ \\boldsymbol\{F\}\_\{r,s\}&=\\left\(\\diag\\exp\\left\(\\boldsymbol\{\\lambda\}\_\{r,s\}\-\\boldsymbol\{\\lambda\}\_\{r\}\\right\)\\right\)\\tilde\{\\boldsymbol\{F\}\}\_\{r,s\}=\\exp\\left\(\\boldsymbol\{A\}\_\{I\(r\),J\(s\)\}\-\\boldsymbol\{\\lambda\}\_\{r\}\\boldsymbol\{1\}\_\{\|J\(s\)\|\}^\{T\}\\right\)\.\\end\{split\}If
πr,sT=π\|Iβ‘\(r\)\|Tβexpβ‘\(π¨Iβ‘\(r\),Jβ‘\(s\)βπrβπ\|Jβ‘\(s\)\|T\)=π\|Iβ‘\(r\)\|Tβπr,s,\\boldsymbol\{w\}\_\{r,s\}^\{T\}=\\boldsymbol\{1\}\_\{\|I\(r\)\|\}^\{T\}\\exp\\left\(\\boldsymbol\{A\}\_\{I\(r\),J\(s\)\}\-\\boldsymbol\{\\lambda\}\_\{r\}\\boldsymbol\{1\}\_\{\|J\(s\)\|\}^\{T\}\\right\)=\\boldsymbol\{1\}\_\{\|I\(r\)\|\}^\{T\}\\boldsymbol\{F\}\_\{r,s\},thenπ=\[βrπr,s\]\\boldsymbol\{w\}=\[\\sum\_\{r\}\\boldsymbol\{w\}\_\{r,s\}\]\. We can computeπ\\boldsymbol\{w\}andπ\\boldsymbol\{Y\}with an outer loop overrr, inner loop overss\. Initializeπ=πNk\\boldsymbol\{w\}=\\boldsymbol\{0\}\_\{N\_\{k\}\}\. The iterationrrworks as follows:
- β’Map: Compute\[πr,s\],\[π~r,s\],\[πr,s\]\[\\boldsymbol\{\\lambda\}\_\{r,s\}\],\[\\tilde\{\\boldsymbol\{F\}\}\_\{r,s\}\],\[\\boldsymbol\{Y\}\_\{r,s\}\]in parallel\.
- β’Reduce:\(πr,πr\)=ππππππβ‘\(\[πr,s\],\[πr,s\]\)\(\\boldsymbol\{\\lambda\}\_\{r\},\\boldsymbol\{Y\}\_\{r\}\)=\\mathtt\{reduce\}\\left\(\[\\boldsymbol\{\\lambda\}\_\{r,s\}\],\[\\boldsymbol\{Y\}\_\{r,s\}\]\\right\)\.
- β’Computeπr,sT=π\|Iβ‘\(r\)\|Tβπr,s=expβ‘\(πr,sβπr\)Tβπ~r,s\\boldsymbol\{w\}\_\{r,s\}^\{T\}=\\boldsymbol\{1\}\_\{\|I\(r\)\|\}^\{T\}\\boldsymbol\{F\}\_\{r,s\}=\\exp\(\\boldsymbol\{\\lambda\}\_\{r,s\}\-\\boldsymbol\{\\lambda\}\_\{r\}\)^\{T\}\\tilde\{\\boldsymbol\{F\}\}\_\{r,s\}\. Addπr=\[πr,s\]\\boldsymbol\{w\}\_\{r\}=\[\\boldsymbol\{w\}\_\{r,s\}\]toπ\\boldsymbol\{w\}\.
Compared to standard FlashAttention, we need to first reduce alongssin order to obtainπr\\boldsymbol\{\\lambda\}\_\{r\}, keepingπ~r,s\\tilde\{\\boldsymbol\{F\}\}\_\{r,s\}andπr,s\\boldsymbol\{\\lambda\}\_\{r,s\}around\.
#### A\.6\.2Summed Attention Weights with FlexAttention
FlexAttention\[[14](https://arxiv.org/html/2608.19920#bib.bib14)\]stands out among fast SDPA codes by allowing the user to configure the computation in several ways \(see also[https://pytorch\.org/blog/flexattention/](https://pytorch.org/blog/flexattention/)\)\. Here we describe how to compute summed attention weightsπ\\boldsymbol\{w\}alongside the attention outputπ\\boldsymbol\{Y\}, by calling FlexAttention twice\.
Recall that SDPA computes
π=expβ‘\(π¨βπβπT\)βπ½\.\\boldsymbol\{Y\}=\\exp\\left\(\\boldsymbol\{A\}\-\\boldsymbol\{\\lambda\}\\boldsymbol\{1\}^\{T\}\\right\)\\boldsymbol\{V\}\.The summed attention weights are
π=expβ‘\(π¨βπβπT\)βπT=expβ‘\(π¨TβπβπT\)βπ=expβ‘\(π¨T\)βπ~,π~:=expβ‘\(βπ\)\.\\boldsymbol\{w\}=\\exp\\left\(\\boldsymbol\{A\}\-\\boldsymbol\{\\lambda\}\\boldsymbol\{1\}^\{T\}\\right\)\{\}^\{T\}\\boldsymbol\{1\}=\\exp\\left\(\\boldsymbol\{A\}^\{T\}\-\\boldsymbol\{1\}\\boldsymbol\{\\lambda\}^\{T\}\\right\)\\boldsymbol\{1\}=\\exp\\left\(\\boldsymbol\{A\}^\{T\}\\right\)\\tilde\{\\boldsymbol\{v\}\},\\quad\\tilde\{\\boldsymbol\{v\}\}:=\\exp\(\-\\boldsymbol\{\\lambda\}\)\.Up to softmax normalization, we can obtain this by calling a variant of SDPA again, flippingπΈ\\boldsymbol\{Q\}andπ²\\boldsymbol\{K\}, reverting the attention masking, and passingexpβ‘\(βπ\)\\exp\(\-\\boldsymbol\{\\lambda\}\)as values\. Importantly, FlexAttention returnsπ\\boldsymbol\{\\lambda\}with the optionreturn\_aux = AuxRequest\(lse=True\)\. Now, ifπ~\\tilde\{\\boldsymbol\{\\lambda\}\}denoteslsefor the second call \(withπΈ\\boldsymbol\{Q\}andπ²\\boldsymbol\{K\}flipped\), then:
π=expβ‘\(π¨Tβπ~βπT\+π~βπT\)βπ~=\(diagβ‘expβ‘\(π~\)\)βexpβ‘\(π¨Tβπ~βπT\)βπ~=expβ‘\(π~\)βπ~\.\\boldsymbol\{w\}=\\exp\\left\(\\boldsymbol\{A\}^\{T\}\-\\tilde\{\\boldsymbol\{\\lambda\}\}\\boldsymbol\{1\}^\{T\}\+\\tilde\{\\boldsymbol\{\\lambda\}\}\\boldsymbol\{1\}^\{T\}\\right\)\\tilde\{\\boldsymbol\{v\}\}=\\left\(\\diag\\exp\(\\tilde\{\\boldsymbol\{\\lambda\}\}\)\\right\)\\exp\\left\(\\boldsymbol\{A\}^\{T\}\-\\tilde\{\\boldsymbol\{\\lambda\}\}\\boldsymbol\{1\}^\{T\}\\right\)\\tilde\{\\boldsymbol\{v\}\}=\\exp\(\\tilde\{\\boldsymbol\{\\lambda\}\}\)\\circ\\tilde\{\\boldsymbol\{y\}\}\.Finally, trying to minimize numerical errors \(we are using 16 bit data types\), we useexpβ‘\(β\(πβλ¯βπ\)\)\\exp\(\-\(\\boldsymbol\{\\lambda\}\-\\bar\{\\lambda\}\\boldsymbol\{1\}\)\)andexpβ‘\(π~βλ¯βπ\)\\exp\(\\tilde\{\\boldsymbol\{\\lambda\}\}\-\\bar\{\\lambda\}\\boldsymbol\{1\}\), whereλ¯=Nqβ1βπTβπ\\bar\{\\lambda\}=N\_\{q\}^\{\-1\}\\boldsymbol\{1\}^\{T\}\\boldsymbol\{\\lambda\}is the mean ofπ\\boldsymbol\{\\lambda\}\. All in all:
- β’\(π,π\)=ππ³πΏπ°β‘\(πΈ,π²,π½\)\(\\boldsymbol\{Y\},\\boldsymbol\{\\lambda\}\)=\\mathtt\{SDPA\}\(\\boldsymbol\{Q\},\\boldsymbol\{K\},\\boldsymbol\{V\}\),λ¯=Nqβ1βπTβπ\\bar\{\\lambda\}=N\_\{q\}^\{\-1\}\\boldsymbol\{1\}^\{T\}\\boldsymbol\{\\lambda\}\.
- β’\(π~,π~\)=ππ³πΏπ°β\_βπππβ\(π²,πΈ,expβ‘\(β\(πβλ¯βπ\)\)\)\(\\tilde\{\\boldsymbol\{y\}\},\\tilde\{\\boldsymbol\{\\lambda\}\}\)=\\mathtt\{SDPA\\\_rev\}\(\\boldsymbol\{K\},\\boldsymbol\{Q\},\\exp\(\-\(\\boldsymbol\{\\lambda\}\-\\bar\{\\lambda\}\\boldsymbol\{1\}\)\)\), thenπ=expβ‘\(π~βλ¯βπ\)βπ~\\boldsymbol\{w\}=\\exp\(\\tilde\{\\boldsymbol\{\\lambda\}\}\-\\bar\{\\lambda\}\\boldsymbol\{1\}\)\\circ\\tilde\{\\boldsymbol\{y\}\}\.
Here,ππ³πΏπ°β\_βπππ\\mathtt\{SDPA\\\_rev\}differs fromππ³πΏπ°\\mathtt\{SDPA\}by the attention masking being reversed\. FlexAttention allows to specify the attention mask asπππππβ\_βππππβ\(π,π,πβ\_βπππ‘,ππβ\_βπππ‘\)\\mathtt\{block\\\_mask\(b,h,q\\\_idx,kv\\\_idx\)\}\. The mask forππ³πΏπ°β\_βπππ\\mathtt\{SDPA\\\_rev\}is given by flippingπβ\_βπππ‘\\mathtt\{q\\\_idx\}andππβ\_βπππ‘\\mathtt\{kv\\\_idx\}in the code forππ³πΏπ°\\mathtt\{SDPA\}\. Note that FlexAttention supportsπ½\\boldsymbol\{V\}to have a different \(final\) embedding dimension thatπΈ,π²\\boldsymbol\{Q\},\\boldsymbol\{K\}\. Maybe this even translates in the second call being faster than the first\. All in all, compared to a single FlexAttention call and no attention weights, this is at most twice as expensive\.
### A\.7Sparse Attention and SotA Inference Libraries
In Section[3\.3](https://arxiv.org/html/2608.19920#S3.SS3), we discuss the \(somewhat surprising\) fact that as of today, sparse attention is not much used in real\-world practice, because existing implementations are too slow to be competitive with the state of the art\. While a part of the latency gap between sparse attention and sequence or context parallelism is probably inherent, we argued in Section[3\.3\.1](https://arxiv.org/html/2608.19920#S3.SS3.SSS1)some shortcomings of current sparse attention implementations are easy to eliminate by minor extensions of fast SDPA kernel codes\.
Here, we comment on why sparse attention policies, such as H2O, are not supported in vLLM\[[33](https://arxiv.org/html/2608.19920#bib.bib28)\], the leading fast inference library\. Details are found in[https://github\.com/vllm\-project/vllm/issues/10646](https://github.com/vllm-project/vllm/issues/10646),[https://github\.com/vllm\-project/vllm/issues/12254](https://github.com/vllm-project/vllm/issues/12254),[https://github\.com/vllm\-project/vllm/issues/5751](https://github.com/vllm-project/vllm/issues/5751)\. In vLLM, KV caches are maintained as set of fixed\-sized pages \(or blocks\)\. The main issue is that they require a page to store KV contentacross all heads: KV information for a token is stored in the cache for all heads or for none\. The cited RFCs mention that it would require significant changes to the memory layout and block manager abstractions to change that\. However, for modern sparse attention \(such as H2O\), policiesΟβ‘\(b,h,t\)\\pi\(b,h,t\)depend on\(h,t\)\(h,t\)in general: they select different tokens per head\.
As detailed in Section[3\.1](https://arxiv.org/html/2608.19920#S3.SS1), our implementation has no problems with this\. We simply maintain dense buffers of shape\(B,Hk,NC,dh\)\(B,H\_\{k\},N\_\{C\},d\_\{h\}\), where the cache lengthNCN\_\{C\}is fixed independent of context width, and then useπππππ\.ππππππ\\mathtt\{torch\.gather\}andπππππ\.πππππππ\\mathtt\{torch\.scatter\}for read and write access\. Whereas PagedAttention requires specific SDPA kernels, we can use existing dense SDPA codes, as long as we cater for causal masking \(see Section[3\.3\.1](https://arxiv.org/html/2608.19920#S3.SS3.SSS1)\)\. While not supported in our current implementation, we could build up KV cache buffers in chunks to cater for sequence lengths shorter thanNCN\_\{C\}, thereby solving the issue of unnecessary pre\-allocations\[[33](https://arxiv.org/html/2608.19920#bib.bib28)\]\. Finally, whileπππππ\.ππππππ\\mathtt\{torch\.gather\}andπππππ\.πππππππ\\mathtt\{torch\.scatter\}access the buffer in a non\-contiguous way, this is very subdominant to SDPA computations in our experience\. In fact, when callingπππππππβ‘\(πππ’π,πππππ‘,πππ’β\_βπππ \)\\mathtt\{scatter\}\(\\mathtt\{keys\},\\mathtt\{index\},\\mathtt\{key\\\_new\}\), the final axis ofπππππ‘\\mathtt\{index\}is always constant \(so that the final buffer axis of sizedhd\_\{h\}is accessed contiguously\), and optimizedπππππππ\\mathtt\{scatter\}andππππππ\\mathtt\{gather\}kernels could easily be implemented for this case if the PyTorch implementations do not already cater for this special case\. One advantage of PagedAttention over our approach is that they can in principle represent different numbers of tokens per head or batch dimension, which can render sparse attention a bit more flexible\. However, since vLLM requires each page to extend over all heads, this extra flexibility is not supported there\.
As long as highly optimized and widely used inference libraries do not support sparse attention, it may remain underused\. We hope that our work sparks some renewed interest in this direction\.
### A\.8Details on Related Work
Here, we provide additional details about relations of our method with prior work\. OOMB\[[37](https://arxiv.org/html/2608.19920#bib.bib35)\]shares properties with our work, such as chunk\-level processing, activation checkpointing, and efforts to compress KV cache buffers forautograd\. Details on the relationship are as follows:
- β’Their implementation is better suited for representing KV caches exactly \(no selection or compression\) that ours\. They implement a paged memory management like\[[33](https://arxiv.org/html/2608.19920#bib.bib28)\], which we do not \(but see Section[A\.7](https://arxiv.org/html/2608.19920#A1.SS7)and comments in Section[3\.1](https://arxiv.org/html/2608.19920#S3.SS1)\)\. However, despite all efforts in CPU offloading and activation checkpointing, they run into the same barrier as\[[38](https://arxiv.org/html/2608.19920#bib.bib34)\], in that the factor for the final chunk depends onallKV cache buffers of all layers, so cannot be represented byautogradon a single device\. At this point, RingAttention\[[42](https://arxiv.org/html/2608.19920#bib.bib36)\]is the method of choice, and it is not clear why their library would improve on implementations such as MS\-SWIFT\[[82](https://arxiv.org/html/2608.19920#bib.bib73)\]\.
- β’They deal with activation memory for GPU by activation recomputation, while we use activation checkpointing\. In the former, activations are recomputed during the backward passfrom the start, whereas in the latter, recomputation starts from the most recent checkpoint\. The former is too slow to be useful, so our guess is their code actually uses activation checkpointing\.
- β’The most important difference is how they deal with KV cache buffers as nodes in theautogradgraphs, and what this implies for generality\. This is also the biggest challenge we face, and we deal with it by a combination of nested checkpointing, delta encoding of KV cache buffers, and integration intoPyTorchby way of autograd saved tensor hooks \(Section[A\.4\.3](https://arxiv.org/html/2608.19920#A1.SS4.SSS3)\)\. Together with recording and replaying KV cache decisions, thisrenders our implementation fully agnostic to the KV cache policy: it works with any selection or compression policy \(see Section[2](https://arxiv.org/html/2608.19920#S2)for many references\)\. In contrast, they try to hide all nodes representing KV cache content fromautogradaltogether, so that none of this information can be placed in the computation graph\. This is possible only by implementing a number of complex CUDA kernels, in which all inner derivatives w\.r\.t\. these βKV cache nodesβ are made explicit\. Apart from substantial derivation and implementation complexity, their approachmust be specialized to the KV cache policy being used\. In fact, their paper only provides results for two specific sparse attention policies \(LSA and DSA\)\. Moreover, their paper is sparse on details how the hiding of KV cache buffers fromautogradworks in practice, since KV cache updates are tightly coupled with SDPA calls\. In the end, their implementation may not be agnostic to SDPA kernels, which given the speed of development of SDPA would be a major drawback\.
- β’Both their and our implementation make use of CPU offloading of activations, KV cache buffers, and head gradients\. They claim to have done this asynchronously, as in\[[75](https://arxiv.org/html/2608.19920#bib.bib66)\], which hides latency\. We have also experimented with this, but did no so far achieve significant speedups\. Moreover, asynchronous transfer requires double buffering, which drives up GPU memory requirements\. Still, more effort in this direction is warranted\.
### A\.9Open Source Library KeysAndValues\. Experiments
For all experiments above, fine\-tuning with our method \(columnusin Table[1](https://arxiv.org/html/2608.19920#S4.T1)\) and inference with sparse attention \(all policies\) were done with a new open source library for long context fine\-tuning and inference:πΊππ’ππ°πππ
πππππ\\mathtt\{KeysAndValues\}\([https://github\.com/awslabs/keys\_values](https://github.com/awslabs/keys_values)\)\.
Apart from efficient code for our fine\-tuning method, the library provides clean and simple abstractions for sparse attention and key\-value caches of limited size\. Among its features are:
- β’Long context fine\-tuning on a single GPU \(this work\)\.
- β’Several variants of the H2O KV cache policy\[[76](https://arxiv.org/html/2608.19920#bib.bib69)\]\. The library provides a generic implementation for any cache logic of the formΟβ‘\(b,h,t\)\\pi\(b,h,t\)which makes use of summed attention weights\.
- β’Quantization of KV cache buffers\.
- β’Integration of FlexAttention\[[14](https://arxiv.org/html/2608.19920#bib.bib14)\], FlashInfer\[[72](https://arxiv.org/html/2608.19920#bib.bib63)\], FlashAttention\[[10](https://arxiv.org/html/2608.19920#bib.bib8),[52](https://arxiv.org/html/2608.19920#bib.bib44)\]and eager SDPA behind a common multi\-head self\-attention interface\. This includes summed attention weights \(for H2O\-like policies\), as well as a properπππππ πππ\\mathtt\{backward\}implementation\.
- β’Model implementations and inference code is from LitGPT \([https://github\.com/lightning\-ai/litgpt](https://github.com/lightning-ai/litgpt)\), which allows for almost any Hugging Face checkpoint to be used\. However, while bringing modern KV caching to Hugging Face would require hacking several code filesseparately for every single model, you can apply your KV cache policy or attention approximation to almost all models with few changes of common code\.
- β’Support of CPU offloading of KV cache buffers and model weights\.
- β’Support of distributed training \(distributed data parallel, CPU offloading of model weights optional\)\. Support of distributed evaluation\.
With this library, we do not intend to compete with vLLM\[[33](https://arxiv.org/html/2608.19920#bib.bib28)\]or SGLang\[[83](https://arxiv.org/html/2608.19920#bib.bib74)\], which include more low level optimizations and support of latest GPU architectures\. Instead, we make it easy for researchers to explore new KV cache policies, post\-time training ideas, or unusual multi\-head self\-attention approximations, providing clean abstractions of these concepts which can be used and extended without having to deal with intricate implementation details of existing high\-performance libraries\.
#### A\.9\.1Running Our Experiments
OnceπΊππ’ππ°πππ
πππππ\\mathtt\{KeysAndValues\}has been properly installed, the training runs for our method can be reproduced as follows\. You need to be on an instance with at least four Nvidia A100 GPUs with 40 GB of RAM\. We usedAWS EC2 p4d\.24xlargeinstances, which have 8 A100 GPUs, running two experiments in parallel on each instance\.
exportDATASET\_KEY=βnqβ;\\
exportDATASET\_SIZE=β128kβ;\\
exportPOLICY\_NAME=βh2o\-origβ;\\
exportCACHE\_LENGTH=β32768β;\\
exportCHUNK\_SIZE=β2048β;\\
exportEVAL\_STEPS=10;\\
CUDA\_VISIBLE\_DEVICES=β0,1,2,3β\\
PYTORCH\_ALLOC\_CONF=expandable\_segments:True\\
KEYSVALS\_LOG\_DIR=β\./finetune/helmet\_$\{DATASET\_KEY\}\_$\{DATASET\_SIZE\}/$\{POLICY\_NAME\}\_cs$\{CHUNK\_SIZE\}/logsβ\\
python3keys\_values/\_\_main\_\_\.pyfinetune\_long\_lora\\
Qwen/Qwen3\-4B\-Instruct\-2507\\
βout\_dir\./finetune/helmet\_$\{DATASET\_KEY\}\_$\{DATASET\_SIZE\}/$\{POLICY\_NAME\}\_cs$\{CHUNK\_SIZE\}\\
βprecisionbf16\-true\\
βverbosesome\\
βdevices4\\
βdataHelmet\\
βdata\.dataset\_key$\{DATASET\_KEY\}\\
βdata\.max\_length$\{DATASET\_SIZE\}\\
βdata\.metadata\_dir\./data\\
βdata\.trainloader\_longest\_firstTrue\\
βtrain\.save\_interval$\{EVAL\_STEPS\}\\
βtrain\.micro\_batch\_size2\\
βtrain\.epochs5\\
βtrain\.average\_loss\_per\_batchTrue\\
βeval\.interval$\{EVAL\_STEPS\}\\
βeval\.initial\_validationTrue\\
βeval\.use\_sample\_metricFalse\\
βkv\_cache\.cache\_length$\{CACHE\_LENGTH\}\\
βkv\_cache\.chunk\_size$\{CHUNK\_SIZE\}\\
βkv\_cache\.name$\{POLICY\_NAME\}\-torch\-quantized8\\
βgrad\.layers\_per\_cell1\\
βgrad\.layercp\_qnamedefault\\
βgrad\.cachecp\_qnametorch\-quantized8\\
βgrad\.chunks\_per\_cell\_multiplier1\\
βoptimizer\.nameAdamW\\
βoptimizer\.learning\_rate0\.0005
Once all desired training runs have finished, evaluations \(on the test sets\) can be run as follows\.
CUDA\_VISIBLE\_DEVICES=β0,1,2,3β\\
PYTORCH\_ALLOC\_CONF=expandable\_segments:True\\
KEYSVALS\_LOG\_DIR=β\./finetune/evaluation/myruns/logsβ\\
python3keys\_values/\_\_main\_\_\.pyeval\_long\_ext\\
\./myruns\.yaml\\
βverbosesome\\
βdevices4\\
βbatch\_size2\\
βuse\_sample\_metricTrue\\
βsample\_metric\_max\_generated\_tokens20\\
βnum\_store\_generated\_samples1000
Here,myruns\.yamlis a YAML file containing entries of this form:
\-out\_dir:\./finetune/helmet\_nq\_64k/h2o\_cs2048
model\_type:lora
eval\_tasks:
\-step\-000420
For each setup, evaluations can be run for different checkpointsstep\-000\*\*\*stored alongside training\. In our experiments, for each setup, we select the checkpoint which minimize validation loss\. We refer toREADME\.mdfor further details on how to aggregate evaluation results and create result tables\.Similar Articles
BF1: A Causal Dyadic Sparse-Attention Retrofit for Efficient Long-Context Transformers
The paper introduces BF1, a causal dyadic sparse-attention retrofit designed to improve the efficiency of transformers for long-context processing.
Generative modeling with sparse transformers
OpenAI introduces the Sparse Transformer, a deep neural network that improves the attention mechanism from O(NΒ²) to O(NβN) complexity, enabling modeling of sequences 30x longer than previously possible across text, images, and audio. The model uses sparse attention patterns and checkpoint-based memory optimization to train networks up to 128 layers deep, achieving state-of-the-art performance across multiple domains.
Grammatically-Guided Sparse Attention for Efficient and Interpretable Transformers
This paper introduces a grammatically-guided sparse attention mechanism for Transformers, aiming to improve efficiency and interpretability by leveraging linguistic structure.
Attention Amnesia in Hybrid LLMs: When CoT Fine-Tuning Breaks Long-Range Recall, and How to Fix It
This paper identifies that chain-of-thought supervised fine-tuning degrades long-context recall in hybrid linear-attention models by biasing attention gradients toward short-range patterns, and proposes QK-Restore, a training-free method that restores long-context recall while preserving reasoning performance.
Hierarchical Sparse Attention Done Right: Toward Infinite Context Modeling
Introduces HiLS Attention, a chunk-wise sparse attention mechanism for LLMs that learns chunk selection end-to-end via LM loss, achieving performance comparable to full attention while enabling ultra-long-context extrapolation and faster inference.