Task-Aware KV Cache Compression for LLM Agents via Utility-Driven Step Pruning

Yusen Wu, Yefan Wang, Jia Yee Tan, Rongfeng Guo, Shuang Chen, Jing Yangum, Por Lip Yee, Yongtai Liu, Guangyuan DongNeurIPS 2026

TL;DR

When autonomous LLM agents work on long tasks, their internal memory—the Key-Value (KV) cache—balloons rapidly, creating a massive serving bottleneck. Standard memory-pruning methods decide what to keep based on what the model pays the most "attention" to, which accidentally hoards noisy, repetitive error logs while throwing away quiet, crucial instructions. TaskKV fixes this by scoring and pruning whole reasoning steps based on whether they actually help the agent take the right next action, keeping nearly 90% of an agent's performance while throwing away 80% of its memory footprint.

What Problem Does This Paper Address?

Deploying LLM agents that reason over thousands of trial-and-error steps hits a hard physical wall: the KV cache (the model's working memory of past tokens) grows linearly. A single 128k-token context on Llama-3.1-70B eats over 40 GB of memory.

To shrink this cache, existing methods like H2O and SnapKV keep "Heavy Hitters"—tokens with the highest accumulated attention scores. That works great for standard text generation, where keeping track of frequent words maintains low perplexity (text predictability). However, in agentic workflows, attention does not equal utility. When an agent gets stuck in a loop of failed SQL queries or verbose terminal logs, those recent, repetitive errors soak up tons of attention. Meanwhile, a distant system prompt or a brief sub-goal receives sparse attention, gets evicted, and derails the agent.

Figure 1: The Attention–Utility Misalignment in Agentic Memory. Left: generic token-only compression retains high-score/noisy KV entries while dropping task evidence. Right: TaskKV conditions retention on the task objective, evidence, and relation, preserving utility-bearing entries while pruning redundant/noisy ones before the LLM. This is a conceptual schematic; the blocks illustrate retention choices and do not represent measured token counts or experimental results.

Methods

Instead of pruning individual tokens (which shreds semantic coherence), TaskKV operates online at the level of semantic steps—complete Thoughts, Actions, or Observations parsed via delimiters (like Observation:), with a fixed-stride chunking fallback if text gets messy.

TaskKV introduces three clever mechanisms:

  1. Signed Directional Utility Labels (Training Signal): How do you train a tiny network to know if a step was helpful without running thousands of expensive "leave-one-out" forward passes? Standard gradient magnitude (saliency) fails because a confusing distractor causes a huge gradient—just in the wrong direction. Instead, the authors take the inner product of the action-loss gradient and the masking direction. Positive values mean keeping the step helps predict the ground-truth action; negative values mean it actively confuses the model.
  2. Structured Residual Scorer: Rather than forcing a neural network to learn memory management from scratch, TaskKV starts with two fixed priors: attention mass and semantic cosine similarity to the agent's current "intent" (a smoothed exponential moving average of final-layer key states). A lightweight MLP then learns only a denoising penalty to down-weight distracting error loops, aided by a binary "pivot" indicator that flags strategy shifts.
TaskKV's Step Utility Scorer combines step centroids, time-varying intent, and pivot features to separate useful steps from negative-utility error loops.
  1. Min-Heap Retention & Entropy Safeguard: Steps are managed in a min-heap under a strict token budget, broadcasting the exact same eviction mask across all transformer layers to keep internal representations aligned. Crucially, TaskKV monitors the normalized entropy of its own utility scores. If all steps look equally important (high entropy—common in dense tasks like summarization), TaskKV realizes it is out of its depth, disables learned pruning, and safely falls back to contiguous window retention (StreamingLLM).

Datasets

No new benchmarks were introduced; instead, the authors tested across diverse agentic and long-context environments:

  • Training & Matched Evaluation: Scorer training used trajectories exclusively from AgentBench-OS (Operating System) and AlfWorld (embodied household tasks).
  • Zero-Shot Transfer Evaluation: AgentBench-DB (Database) and AgentBench-KG (Knowledge Graph) tested whether the trained scorer generalizes to unseen domains without fine-tuning.
  • Boundary Diagnostics: LongBench (specifically Summarization) and Needle-In-A-Haystack evaluated how the system behaves on dense, non-agentic long contexts, alongside preliminary format checks on UltraChat and WebArena.

Key Insights and Ideas

  • Saliency Conflates Help and Harm: Replacing the signed utility training label with standard unsigned gradient magnitude drops AlfWorld success by 6.1%. Knowing whether a step pushes the model toward or away from the right action is the secret sauce that stops the cache from hoarding high-attention error loops.
  • Lower Perplexity $\neq$ Better Agents: Methods that optimize token-level or layer-adaptive perplexity actually reduce agent success rates by 2–3 points. Generating plausible-sounding text and remembering how to execute a multi-step bash script are fundamentally different objectives.
  • Tiny Compute, Fast Convergence: Because the MLP only learns a residual "denoising" correction on top of strong attention and semantic priors, training converges with just 500 trajectories and takes roughly 4 GPU-hours on a single A100.
  • Self-Awareness via Entropy: No compressor rules them all. Monitoring score entropy lets the model automatically switch gears—activating the fallback in 88% of dense summarization tasks while firing on fewer than 1.5% of sparse agentic steps.

Key Results

Evaluated primarily on Llama-3.1-70B-Instruct and Mistral-7B-v0.3 under a strict 20% KV-cache budget (evicting 80% of tokens, with system prompts counted inside that same budget):

  • High Retention: Across AgentBench (OS, DB, KG) and AlfWorld, TaskKV preserves 87%–89% of full-cache success rates (e.g., 64.7% vs. 73.1% full cache on AlfWorld; 38.1% vs. 42.8% on OS).
  • Beating Baselines: It outperforms SnapKV by 5.0–7.9 percentage points, H2O by 8.6–12.6 points, and a competitive Strong Heuristic (protected prompt + recent window + semantic retrieval) by 2.9–7.3 points.
  • Breaking Error Loops: On held-out AgentBench-DB tasks, H2O gets stuck in repetitive failure loops 28.5% of the time; TaskKV cuts that loop failure rate down to 12.2%.
  • Minimal Overhead: Step reduction takes $<0.3$ ms on-GPU, and the scorer adds about 16% to per-step latency without negating memory savings.

Limitations and Future Work

The authors are refreshingly candid about where TaskKV hits its limits:

  • The 10% Budget Cliff: Below a 10% KV budget, performance drops steeply (falling 8.3 points on AlfWorld from 20% to 10%), as there simply isn't enough room left to hold multi-step context.
  • Short & Dense Traces: On trajectories shorter than 20 steps, there isn't enough repetitive noise to filter, so TaskKV offers no measurable gain over a good heuristic. On Needle-In-A-Haystack, it hits 94% recall (beating H2O's 48%), but still trails Full Cache by 6 points.
  • Structural & Supervision Constraints: TaskKV shines on step-structured traces (like ReAct). Generalizing to messy, unstructured multi-tool software-engineering agents, full web navigation suites, and learning utility scorers without ground-truth reference actions remain open challenges for future work.

Summary updated

Abstract

KV-cache compression for long-horizon LLM agents is often guided by accumulated attention, yet attention frequency can retain repetitive error traces while discarding decisive instructions. We propose TaskKV, a streaming step-level retention policy with three contributions: (1) a signed directional utility label from the first-order change in action likelihood, distinguishing helpful steps from confusing distractors unlike unsigned saliency; (2) a structured residual scorer that treats attention mass and intent alignment as fixed priors and learns only a denoising correction, converging with 500 trajectories; and (3) an entropy-based regime classifier that falls back to contiguous retention when the scorer cannot confidently rank steps. With a 20% KV budget on AgentBench and AlfWorld, TaskKV preserves $\sim$87--89% of full-cache success rate, improving over SnapKV by 5.0--7.9 SR points and over a strong heuristic by 2.9--7.3 points; on dense tasks, gains come from detecting when utility pruning should be disabled. Code is available at https://github.com/Sanmu-27/taskkv.
BibTeX
@inproceedings{wu2026task,
  author = {Yusen Wu and Yefan Wang and Jia Yee Tan and Rongfeng Guo and Shuang Chen and Jing Yangum and Por Lip Yee and Yongtai Liu and Guangyuan Dong},
  title = {{Task-Aware KV Cache Compression for LLM Agents via Utility-Driven Step Pruning}},
  booktitle = {Advances in Neural Information Processing Systems},
  year = {2026},
  url = {https://openreview.net/forum?id=4z1e71VXI6},
}
Figure