kv cache compression
kv cache quantization, kv cache eviction, attention memory, gqa, mqa, streamingllm, h2o, low rank kv cache
**KV cache compression reduces the memory footprint or bandwidth of stored attention keys and values used during autoregressive inference.** Long contexts and many concurrent requests can make cache capacity the binding limit even when model weights fit, so compression can raise batch size, context length, and serving throughput. For a decoder, cache storage grows with layers, sequence length, batch, key-value heads, head dimension, and bytes per element. Grouped-query and multi-query attention reduce the number of KV heads architecturally; post-training cache techniques quantize, evict, summarize, or encode states after or during generation. A production definition names the model family and release, parameter and active-parameter scale, vocabulary, context window, data cutoff and provenance, objective, precision, adaptation method, decoding policy, serving stack, target hardware, safety controls, evaluation protocol, and known limitations. Labels such as large, frontier, open, multimodal, efficient, or state of the art are not specifications; results must identify the exact artifact, prompt template, sampling settings, software version, hardware, and measurement date. Specify attention architecture, cache tensor layout, precision by key and value, calibration, scale granularity, residual windows, eviction or retention policy, positional treatment, block size, offload tier, maximum context, recomputation, and quality budget. **Architecture, algorithms, and system integration.** New token states enter a cache manager that may retain a recent high-precision window, quantize older blocks, score important tokens, evict low-value positions, project keys and values into a lower-rank form, or move blocks to host memory. Attention reconstructs or selectively reads the required representation. Quantization uses lower-bit values plus scales and sometimes zero points; eviction methods preserve recency, attention sinks, heavy hitters, or task-important tokens; low-rank methods store compressed latent factors; GQA and MQA share KV projections among query heads; paging manages fragmentation but does not itself compress bytes per live token. INT8, INT4, and mixed-precision caches trade fidelity for capacity; sliding-window and StreamingLLM-style policies bound history; H2O-style heavy-hitter retention selects influential positions; low-rank or latent attention compresses dimensions; offload and recomputation trade memory for bandwidth or compute. A modern AI system spans data collection and governance, filtering and deduplication, tokenization, distributed training, checkpointing, post-training, evaluation, model registry, quantization and compilation, inference schedulers, accelerators, memory and interconnect, retrieval or tools, application policy, observability, and incident response. Decisions at one layer change accuracy, latency, memory traffic, energy, safety, and maintainability elsewhere. Evaluation combines task quality with calibration, robustness, subgroup behavior, contamination resistance, factuality, safety, privacy, memorization, latency to first token, inter-token latency, throughput, concurrency, memory capacity and bandwidth, accelerator utilization, energy per useful output, availability, and cost. Means alone conceal tail behavior, prompt sensitivity, evaluator uncertainty, and failures on rare but consequential cases. **Implementation, compute behavior, and failure modes.** Keep a protected recent window, calibrate keys and values separately, fuse quantize and dequantize with attention kernels, align blocks with paged allocation, update importance online without quadratic metadata, preserve positional semantics, and expose a target-only uncompressed fallback. Compression saves HBM and memory traffic but adds conversion, metadata, irregular gathers, host transfers, or recomputation. Benefits depend on whether attention cache bandwidth, weight bandwidth, compute, or scheduling is actually limiting and whether kernels efficiently support the chosen format. Outliers saturate low-bit ranges, eviction removes a crucial early instruction, attention-sink mishandling destabilizes streaming, low-rank error accumulates, page metadata overwhelms savings, offload creates tail-latency spikes, and approximate cache changes output quality in hard-to-detect ways. Implementation uses immutable dataset and model manifests, content-addressed artifacts, deterministic preprocessing where feasible, seeded experiments, versioned prompts and templates, staged rollouts, bounded resource use, typed interfaces, admission control, timeouts, retries with budgets, telemetry, and reversible releases. Training and serving must agree on tokenizer files, special-token IDs, chat formatting, position treatment, numerical precision, and stop conditions. Delivered performance depends on tensor shapes, arithmetic intensity, quantization format, kernel fusion, batch and sequence distributions, HBM capacity and bandwidth, cache hierarchy, host memory, accelerator topology, collective communication, PCIe or fabric links, storage, power caps, cooling, and scheduler placement. Peak FLOPS or a single benchmark number cannot predict end-to-end behavior. Common failures include train-test leakage, duplicated or poisoned data, tokenizer drift, checkpoint incompatibility, unstable optimization, catastrophic forgetting, numerical overflow, router collapse, silent truncation, cache exhaustion, latency cliffs, evaluator bias, benchmark gaming, hallucination, unsafe tool calls, privacy leakage, model extraction, dependency compromise, and dashboards that average away the affected users. **Evaluation, governance, and lifecycle controls.** Compare logits and generated quality against full-precision cache over short and long contexts, needle retrieval, multi-turn instructions, code, multilingual text, repeated tokens, position boundaries, cancellations, mixed batches, paging churn, OOM recovery, and load tests. Bytes per token, compression ratio, maximum resident tokens, HBM and host traffic, dequantization time, attention latency, throughput, concurrency, fragmentation, retrieval accuracy, perplexity or task delta, energy, and p99 latency matter. Cached prompts and generated states can encode sensitive information; isolation, zeroization, tenant boundaries, retention, encryption for offload, crash dumps, and access-controlled telemetry remain required after compression. Validation combines schema and unit tests, small-run training checks, loss and gradient diagnostics, distributed-failure injection, golden-token tests, reference decoding, numerical comparisons, benchmark suites, adversarial and red-team evaluation, human review with calibrated rubrics, subgroup slices, load and soak testing, hardware profiling, canary deployment, rollback drills, and post-release monitoring. Independent test sets and frozen protocols protect the measurement boundary. Dataset snapshots, licenses and consent, filtering rules, tokenizer assets, source revision, configuration, seeds, optimizer state, checkpoints, adapter lineage, compiler and runtime, container, accelerator firmware, evaluation prompts, judge models, human labels, approvals, model cards, incidents, and deprecation remain linked. Reproducibility is a chain of custody rather than a saved weight file. Owners define data rights, privacy and retention, security classification, acceptable use, safety thresholds, model and supply-chain provenance, access control, secrets, export and regional obligations, environmental reporting, human escalation, vulnerability response, audit evidence, and final release authority. Automated scores inform but do not replace accountability for the deployed system. | Technique | What shrinks | Extra work | Strength | Primary risk | |---|---|---|---|---| | KV quantization | Bytes per element | Scale and conversion | Broad capacity gain | Outlier error | | Token eviction | Stored positions | Importance tracking | Bounded context memory | Lost critical history | | GQA or MQA | KV head count | Architectural training | Large native reduction | Possible quality tradeoff | | Low-rank encoding | Head dimension/state | Projection reconstruction | Structured compression | Approximation and kernels | | Host offload | HBM residency | Data transfer | Extends capacity | Tail latency bandwidth | ```svg ``` **Selection and practical application.** Use GQA or MQA when designing the model, quantization for broad capacity gains with calibrated error, bounded eviction for streaming tasks tolerant of forgotten detail, low-rank methods for compatible architectures, and offload only when transfer tails are acceptable. Long-context assistants, retrieval-augmented generation, code agents, multi-turn chat, document analysis, and high-concurrency inference use cache compression to fit more useful work per accelerator. Cache format interacts with attention architecture, tokenizer length, batching, paging, kernels, memory hierarchy, scheduler fairness, model quality, and privacy policy. The useful optimization boundary is the complete model-serving product. Improving loss, benchmark accuracy, tokens per second, compression ratio, or accelerator utilization can move the bottleneck or weaken robustness, fairness, security, recoverability, and user value elsewhere, so qualification follows representative workflows from source data through production outcomes. A production definition names the model family and release, parameter and active-parameter scale, vocabulary, context window, data cutoff and provenance, objective, precision, adaptation method, decoding policy, serving stack, target hardware, safety controls, evaluation protocol, and known limitations. Labels such as large, frontier, open, multimodal, efficient, or state of the art are not specifications; results must identify the exact artifact, prompt template, sampling settings, software version, hardware, and measurement date. Evaluation combines task quality with calibration, robustness, subgroup behavior, contamination resistance, factuality, safety, privacy, memorization, latency to first token, inter-token latency, throughput, concurrency, memory capacity and bandwidth, accelerator utilization, energy per useful output, availability, and cost. Means alone conceal tail behavior, prompt sensitivity, evaluator uncertainty, and failures on rare but consequential cases. CFS connects this topic to semiconductor architecture, implementation, verification, manufacturing, packaging, test, and deployed AI-system tradeoffs across the platform.