Mastering Long Contexts in LLMs with KVPress
KV cache memory grows linearly with context length: Llama 3-70B at 1M tokens in bfloat16 needs about 330GB of KV cache, roughly 70% of total memory. NVIDIA's KVPress is a Python toolkit of "presses" that prune low-importance KV pairs during prefill via forward hooks on attention layers. Examples include KnormPress, SnapKVPress and ExpectedAttentionPress, each tuned with a compression_ratio and usable through a custom transformers pipeline. On Llama 3.1 8B at 128k context, 50% compression cuts peak memory from 45GB to 37GB and raises decoding from 11 to 17 tokens/s on an A100, while RULER benchmarks show accuracy dropping as compression rises.
Related posts
- Unlocking Longer Generation with Key-Value Cache Quantization
Hugging Face mediumAdeptHugging Face Transformers adds KV cache quantization, inspired by the KIVI paper, that stores keys and values per-token in int2/int4/int8 via quanto or HQQ backends. A residual cache of the most recent tokens (128 by default) stays in full precision to avoid re-quantizing on every step and to preserve accuracy. On Llama-2-7B, int4 matches fp16 on PG-19 perplexity and LongBench, while int2 degrades noticeably. Int4 gives roughly 2.5x memory savings and, with FlashAttention on an 80GB A100, raises max context from 40k to 128k tokens, at the cost of slower generation at larger batch sizes and about 3x slowdown when combined with weight quantization.
- Serving DeepSeek-V4: why million-token context is an inference systems problem
Together AI hardMasterDeepSeek-V4's 1M-token context comes from compressing the token axis of the KV cache: Compressed Sparse Attention (stride 4, top-k selection), Heavily Compressed Attention (stride 128, dense over ~8K entries) and a 128-token Sliding Window Attention path. The model leaves the serving engine to juggle multiple cache layouts with different sizes and lifetimes. In Together's bring-up on NVIDIA HGX B200, SWA state handling dominated capacity, and keeping only SWA states likely to be reused raised per-node KV capacity from ~1.2M to ~3.7M tokens. Prefix caching becomes a per-cache-type storage policy (full SWA store, checkpoints, or recompute-on-hit). Gains appear first in long-context decode-heavy workloads, while short-context prefill depends on kernel maturity, so teams should benchmark in their own regime and use workload-specific endpoint profiles.
- Continuous batching from first principles
Hugging Face mediumAdeptContinuous batching falls out naturally once you optimize LLM serving for throughput, and the post derives it step by step from attention, causal masking, KV caching and chunked prefill. The KV cache cuts the cost of generating each new token from O(n²) to O(n) at O(n) memory, about 16 KB per token per layer for Llama-2-7B in float16. Chunked prefill splits long prompts across forward passes. Padded batched generation wastes compute when prompts finish at different times, and dynamic batching needs heavy padding because newly inserted prompts must prefill while others decode, which motivates continuous batching's mixing of prefill and decode tokens in one forward pass.
- KV Cache from scratch in nanoVLM
Hugging Face mediumAdeptKV caching avoids recomputing keys and values for earlier tokens during autoregressive generation, and implementing it from scratch in the pure-PyTorch nanoVLM codebase gave a 38% speedup in generation. The walkthrough shows the redundancy in self-attention with small PyTorch examples. It then makes three changes: the grouped attention block appends new K/V to a per-layer cache, the language model tracks the cache per layer and uses start_pos to keep rotary position embeddings correct, and generation is split into a prefill phase and a token-by-token decode phase. The tradeoff is memory for speed, plus more complex code that makes schemes like beam search harder.
- TurboQuant: Redefining AI efficiency with extreme compression
Google Research hardMasterTurboQuant is a data-oblivious vector quantization algorithm that removes the per-block quantization-constant overhead of traditional methods by combining PolarQuant (random rotation plus recursive polar-coordinate transforms with a fixed angle grid) and a 1-bit Quantized Johnson-Lindenstrauss residual stage that removes bias in inner-product estimates. On long-context benchmarks with Gemma, Mistral and Llama-3.1-8B, it quantizes the KV cache to 3 bits with no training and no measured accuracy loss, cutting KV memory by at least 6x. 4-bit TurboQuant computes attention logits up to 8x faster than 32-bit keys on H100s. For vector search it beats PQ and RabbiQ on 1@k recall on GloVe without large codebooks or dataset-specific tuning, and the methods come with proofs of near-optimal distortion.