[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-114572":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":9,"language":10,"languages":9,"totalLinesOfCode":9,"stars":11,"forks":12,"watchers":13,"openIssues":14,"contributorsCount":14,"subscribersCount":14,"size":14,"stars1d":14,"stars7d":15,"stars30d":16,"stars90d":14,"forks30d":14,"starsTrendScore":14,"compositeScore":17,"rankGlobal":9,"rankLanguage":9,"license":9,"archived":18,"fork":18,"defaultBranch":19,"hasWiki":20,"hasPages":18,"topics":21,"createdAt":9,"pushedAt":22,"updatedAt":23,"readmeContent":24,"aiSummary":25,"trendingCount":14,"starSnapshotCount":14,"syncStatus":26,"lastSyncTime":27,"discoverSource":28},114572,"Focus-KV-Head-wise-KV-Cache-Compression-Focus-on-Reasoning-Heads","Maverick720\u002FFocus-KV-Head-wise-KV-Cache-Compression-Focus-on-Reasoning-Heads","Maverick720","Code for Focus-KV: Head-wise KV Cache Compression Focus on Reasoning Heads",null,"Python",98,9,8,0,26,34,56.4,false,"main",true,[],"2026-11-18 12:35:32","2026-11-20 11:50:14","# Focus-KV: Head-wise KV Cache Compression Focus on Reasoning Heads\n\nCode for **Focus-KV**, a static head-wise KV-cache compression method that allocates more cache capacity to attention heads that are important for reasoning. Head importance is estimated offline on a reasoning probe set, and the resulting budgets remain fixed during decoding.\n\n## Observation: The Model's Reasoning Ability Is Concentrated in a Sparse Set of Heads\n\nDo different attention heads contribute equally to a model's reasoning ability? We study the contribution of different attention heads to reasoning and arrive at a clear conclusion: **the model's reasoning ability is highly concentrated in a small number of reasoning-critical heads.** Suppressing these heads causes reasoning performance to drop sharply, whereas suppressing other heads is much less damaging.\n\nWe first measure the importance of each query head on a reasoning probe set. The profiling procedure is described in [Importance Signal via Causal Ablation](#importance-signal-via-causal-ablation). As shown in [Figure 2](#importance-signal-via-causal-ablation), reasoning-critical heads are sparse: most heads have importance values close to zero, and only a small number of heads show large importance. This indicates strong non-uniformity across heads.\n\n\u003Cimg src=\"assets\u002Freasoning_head_ablation.png\" alt=\"Figure 1: Effect of disabling important and non-important query heads on MATH-500 accuracy and average generated tokens for Qwen3-8B and Qwen3-14B.\" align=\"right\" width=\"48%\">\n\nWe further measure how much these reasoning heads contribute to a downstream reasoning task. We evaluate with the R-KV algorithm on MATH-500 using a KV-cache budget of 4096. To disable a query head, we scale the output of that query head by $`\\varepsilon`$. We then disable either the most important heads or the least important heads and measure the change in reasoning ability using two metrics: accuracy and average generated tokens. All settings other than the disabled heads are kept the same.\n\n**Figure 1. Reasoning Head Ablation.** Disabling important heads causes a much larger accuracy drop and generates more tokens than disabling non-important heads. Results use R-KV on MATH-500 with a KV-cache budget of 4096.\n\nAs shown in Figure 1, the model's reasoning ability is highly sensitive to important heads. Compared with disabling non-important heads, disabling only a small fraction of important heads causes a much larger accuracy drop and leads the model to generate more tokens.\n\nThese results show two facts. First, our importance estimation method can identify reasoning heads. Second, the model's reasoning ability is concentrated in a small number of reasoning-critical heads. This finding drives the core design of Focus-KV: under a fixed budget, allocating more budget to reasoning heads can better preserve the model's reasoning ability.\n\n\u003Cbr clear=\"all\">\n\n## Method\n\nMotivated by the observation that reasoning ability is concentrated in a sparse subset of attention heads, we propose **Focus-KV**, a static head-wise KV-cache compression algorithm. Focus-KV improves the model's reasoning ability by assigning non-uniform cache budgets across KV heads. Using the importance signal obtained from the probe set, Focus-KV uses a balanced allocation rule with an explicit budget floor and budget cap, ensuring that reasoning-critical heads receive more cache capacity while other heads still retain sufficient budget to keep their basic functionality. By shifting more cache budget toward reasoning-critical heads, Focus-KV improves reasoning performance under the same overall memory constraint.\n\n**Notation.** We write $`S`$ for the probe set, $`\\bar{B}`$ for the average per-head KV budget, $`w`$ for the local-window size, $`\\rho\\in(0,1)`$ for the uniform-floor ratio, $`\\kappa>1`$ for the max-budget cap multiplier, and $`\\lambda`$ for the attention\u002Fsimilarity mixing weight. We use $`L`$ for the number of decoder layers, $`H_q`$ for query heads per layer, and $`H_{kv}`$ for KV heads per layer, with GQA grouping $`G=H_q\u002FH_{kv}`$.\n\nFocus-KV consists of four steps:\n\n1. [Construct a high-quality probe set.](#probe-set-construction)\n2. [Estimate the contribution of each query head to reasoning tasks.](#importance-signal-via-causal-ablation)\n3. [Convert head importance into a balanced KV-head budget allocation.](#budget-allocation)\n4. [Compress the KV cache using the allocated head-wise budgets, computed before inference and fixed during decoding.](#kv-cache-compression)\n\n### Probe Set Construction\n\nWe construct the probe set $`S`$ from OpenR1-Math-220K (Hugging Face, 2025). First, we apply data cleaning to retain usable samples. Then, for each remaining sample, we compute two metrics: (a) the average length of the `\u003Cthink>...\u003C\u002Fthink>` reasoning trace and (b) the per-sample difficulty, defined as\n\n$$\n1-\\frac{\\text{correctness count}}{n_{\\mathrm{gen}}}.\n$$\n\nFollowing recent long-CoT data-selection practice (Yang et al., 2025b), samples are ranked in descending order by reasoning trace length ($`r_\\ell`$) and difficulty ($`r_d`$); the combined rank\n\n$$\nr=0.75\\,r_\\ell+0.25\\,r_d\n$$\n\nselects the top 100 samples: long, hard reasoning problems that can effectively reflect the model's reasoning ability.\n\n### Importance Signal via Causal Ablation\n\nGiven the probe set, we estimate the importance of each query head by measuring how much the model's next-token prediction loss changes when that head is disabled. First, we perform a forward-pass evaluation on the probe set and compute the next-token cross-entropy loss, denoted as $`\\mathcal{L}_{\\mathrm{baseline}}`$, which serves as the baseline measure of the model's basic reasoning performance. Then, for each query head at position $`(k,h)`$, we scale the output of that query head by $`\\varepsilon=10^{-9}`$ to disable it and compute the next-token cross-entropy loss again, denoted as $`\\mathcal{L}_{\\mathrm{ablation}}(k,h)`$. This query head's importance is defined as\n\n$$\nI(k,h)\\triangleq\\mathcal{L}_{\\mathrm{ablation}}(k,h)-\\mathcal{L}_{\\mathrm{baseline}}.\n$$\n\nThis score has a direct causal interpretation: if disabling a head causes a large increase in next-token cross-entropy, then the head contributes substantially to the model's reasoning trajectory; if the loss change is close to zero, then this head is much less important for the reasoning task.\n\n![Figure 2: Importance Signal Visualization for Qwen3-14B, Qwen3-8B, and DeepSeek-R1-Distill-Llama-8B.](assets\u002Fimportance_signal_visualization.png)\n\n**Figure 2. Importance Signal Visualization.** Per-query-head importance measured on the reasoning probe set for Qwen3-14B, Qwen3-8B, and DeepSeek-R1-Distill-Llama-8B. Rows denote layers and columns denote query-head indices. Reasoning-critical heads are sparse: most heads have importance values close to zero, while only a small subset shows high importance.\n\n### Budget Allocation\n\nFor models using GQA, each KV head corresponds to $`G`$ query heads. We take the maximum importance score among these query heads as the importance of the KV head, denoted as $`I_{kv}(k,p)`$, where $`p`$ denotes the position of the KV head in layer $`k`$:\n\n$$\nI_{kv}(k,p)\\triangleq\\max_{h=pG,\\ldots,(p+1)G-1} I(k,h).\n$$\n\nThen, for all KV heads, we clip negative importance scores to zero and normalize them to satisfy $`\\tilde{I}_{kv}(k,p)\\geq 0`$ and $`\\sum_{k,p}\\tilde{I}_{kv}(k,p)=1`$:\n\n$$\n\\tilde{I}_{kv}(k,p)=\\frac{\\max(I_{kv}(k,p),0)}{\\sum_{k',p'}\\max(I_{kv}(k',p'),0)}.\n$$\n\nLet $`\\bar{B}\\triangleq B_{\\mathrm{total}}\u002F(LH_{kv})`$. The budget assigned to each KV head is defined as\n\n$$\nB(k,p)=w+\\underbrace{\\rho(\\bar{B}-w)}_{\\text{uniform floor }U}+r(k,p),\n\\tag{1}\n$$\n\nwhere $`r(k,p)\\geq 0`$ denotes the extra reward budget for reasoning contribution. To allocate this extra budget, define\n\n$$\nP\\triangleq B_{\\mathrm{total}}-LH_{kv}(w+U),\\qquad M\\triangleq\\kappa\\bar{B}-w-U,\n$$\n\nwhere $`P`$ is the total extra-budget pool and $`M`$ is the cap on the extra reward budget. If no head reaches the cap, the allocation reduces to\n\n$$\nr(k,p)=P\\tilde{I}_{kv}(k,p).\n$$\n\nIf some heads reach the cap, their extra budget is fixed to $`r(k,p)=M`$, equivalently $`B(k,p)=\\kappa\\bar{B}`$. We then redistribute the remaining extra budget among the uncapped heads. Let $`\\mathcal{A}`$ be the current set of uncapped heads and let $`P_{\\mathcal{A}}`$ be the remaining extra-budget pool. In each redistribution step, we assign\n\n$$\n\\hat{r}(k,p)=P_{\\mathcal{A}}\\frac{\\tilde{I}_{kv}(k,p)}{\\sum_{(k',p')\\in\\mathcal{A}}\\tilde{I}_{kv}(k',p')},\\qquad(k,p)\\in\\mathcal{A}.\n$$\n\nIf $`\\mathcal{F}_{\\mathrm{new}}`$ denotes the heads capped in the current step, we set $`r(k,p)=M`$ for $`(k,p)\\in\\mathcal{F}_{\\mathrm{new}}`$ and return the exceeded budget to the pool:\n\n$$\nE=\\sum_{(k,p)\\in\\mathcal{F}_{\\mathrm{new}}}\\left(\\hat{r}(k,p)-M\\right).\n$$\n\nThe active set and remaining pool are then updated as\n\n$$\n\\mathcal{A}\\leftarrow\\mathcal{A}\\setminus\\mathcal{F}_{\\mathrm{new}},\\qquad P_{\\mathcal{A}}\\leftarrow\\sum_{(k,p)\\in\\mathcal{A}}\\hat{r}(k,p)+E.\n$$\n\nWe repeat this cap-and-redistribute step until every uncapped head satisfies $`r(k,p)\\leq M`$, which ensures\n\n$$\n\\sum_{k,p}B(k,p)=B_{\\mathrm{total}}.\n\\tag{2}\n$$\n\n### KV Cache Compression\n\nAt inference time, Focus-KV reuses the R-KV scoring step (Cai et al., 2026) to evict tokens. For each compression event, each KV head $`p`$, and each cached position $`t`$, we score\n\n$$\ns_p(t)=\\lambda\\cdot\\mathrm{maxpool}_k\\left(\\mathrm{softmax}\\left(QK^\\top\u002F\\sqrt{d}\\right)_p\\right)[t]-(1-\\lambda)\\cdot\\mathrm{sim}_p(t),\n\\tag{3}\n$$\n\nwhere $`\\mathrm{sim}_p(t)`$ is the row-mean cosine similarity of position $`t`$'s key to the rest of the cache. We keep the top $`B(k,p)-w`$ positions and the last $`w`$ positions.\n\n## Experiment Results\n\n### Mathematical Reasoning\n\n![Figure 3: Accuracy across KV-cache budgets on MATH-500 and AIME24 for Qwen3-14B, Qwen3-8B, and DeepSeek-R1-Distill-Llama-8B.](assets\u002Ffigure4.png)\n\n**Figure 3.** Focus-KV compared with R-KV, ReasonAlloc, Ada-KV, and Full-KV on MATH-500 and AIME24. Results are reported as pass@1 based on 32 generated responses per question. Focus-KV improves accuracy over R-KV across the evaluated models, with particularly large gains under constrained KV-cache budgets.\n\n### Cross-Domain Reasoning\n\n![Figure 4: Qwen3-14B accuracy across KV-cache budgets on MuSR, LiveCodeBench, ZebraLogic, and SATBench.](assets\u002Ffigure8.png)\n\n**Figure 4.** Accuracy (%) of Focus-KV, R-KV, ReasonAlloc, and Full-KV on MuSR, LiveCodeBench, ZebraLogic, and SATBench using Qwen3-14B. These results evaluate reasoning performance beyond the mathematical domain used for head-importance profiling.\n\n## Repository Structure\n\n| Path | Contents |\n| --- | --- |\n| [`compression\u002Ffocuskv.py`](compression\u002Ffocuskv.py) | Importance loading, head-wise budget allocation, and variable-length per-head KV-cache compression. |\n| [`compression\u002Ffocuskv_v2.py`](compression\u002Ffocuskv_v2.py) | Rectangular-cache implementation with per-head padding for batched attention. |\n| [`modeling.py`](modeling.py) | Attention and model-forward integration. |\n| [`monkeypatch.py`](monkeypatch.py) | Entry points for patching Llama, Qwen2, and Qwen3. |\n| [`utils.py`](utils.py) | Attention-score, similarity, and supporting utilities. |\n| [`probeset\u002Ffind_reasoning_heads_multigpu.py`](probeset\u002Ffind_reasoning_heads_multigpu.py) | Multi-GPU query-head ablation and importance profiling. |\n| [`probeset\u002Fprobeset.jsonl`](probeset\u002Fprobeset.jsonl) | Probe data containing 300 records; the [probe-set construction](#probe-set-construction) procedure selects 100 samples for profiling. |\n| [`head_importance\u002F`](head_importance\u002F) | Precomputed query-head importance profiles for Qwen3-8B, Qwen3-14B, and DeepSeek-R1-Distill-Llama-8B. |\n\n## References\n\n- Hugging Face (2025). [*Open R1: A Fully Open Reproduction of DeepSeek-R1.*](https:\u002F\u002Fgithub.com\u002Fhuggingface\u002Fopen-r1)\n- Cehao Yang et al. (2025b). [*Select2Reason: Efficient Instruction-Tuning Data Selection for Long-CoT Reasoning.*](https:\u002F\u002Farxiv.org\u002Fabs\u002F2505.17266)\n- Zefan Cai et al. (2026). [*R-KV: Redundancy-Aware KV Cache Compression for Reasoning Models.*](https:\u002F\u002Farxiv.org\u002Fabs\u002F2505.24133)\n","Focus-KV 是一种面向大语言模型推理优化的静态头级 KV 缓存压缩方法，通过离线评估各注意力头在推理任务上的重要性，为关键推理头分配更多缓存容量，其余头则压缩更激进。其核心技术特点是基于因果消融法在推理探针集上量化头重要性，并据此固定分配缓存预算，不增加推理时开销；支持在有限 KV 缓存预算下显著保持数学推理等复杂任务的准确率与生成效率。适用于部署资源受限但需维持高阶推理能力的大模型服务场景，如边缘端推理、长上下文问答及数学\u002F逻辑密集型应用。",2,"2026-11-24 04:49:03","CREATED_QUERY"]