AI Skills AI技能 4h ago Updated 1h ago 更新于 1小时前 45

The KV Cache Explained: Why Long Conversations Get Expensive KV缓存详解:为什么长对话成本高昂

The KV cache stores precomputed keys and values from every token in a sequence, eliminating the need to reprocess the entire context for each new token generated during inference. Cache memory routinely exceeds model weights in production deployments, making it the primary bottleneck for GPU concurrency rather than compute capacity. PagedAttention (introduced by vLLM) eliminates severe memory waste from contiguous allocation by using fixed-size blocks allocated on demand, dramatically increasing KV Cache是LLM推理的核心优化机制,存储已计算token的Keys和Values,避免每步重复计算整个上下文 Cache内存消耗随context length和并发数双重增长,实际部署中常超过模型权重本身 PagedAttention通过分页分配替代预分配,消除外部碎片,显著提升GPU内存利用率和吞吐量 并发上限由内存而非算力决定,内存耗尽时通过preemption+recompute/swap机制处理

58
Hot 热度
72
Quality 质量
65
Impact 影响力

Analysis 深度分析

TL;DR

  • The KV cache stores precomputed keys and values from every token in a sequence, eliminating the need to reprocess the entire context for each new token generated during inference.
  • Cache memory routinely exceeds model weights in production deployments, making it the primary bottleneck for GPU concurrency rather than compute capacity.
  • PagedAttention (introduced by vLLM) eliminates severe memory waste from contiguous allocation by using fixed-size blocks allocated on demand, dramatically increasing serving throughput.
  • When the cache pool is exhausted, the engine preempts running requests via recomputation or CPU swap, causing mid-generation stalls that signal overcommitment.
  • GQA, KV cache quantization, and context limits are the main levers for reducing cache footprint, while prefix caching across requests remains an open optimization frontier.

Why It Matters

LLM serving systems are fundamentally constrained by memory, not compute—understanding the KV cache is essential for anyone deploying models at scale, as it directly determines how many concurrent users a GPU can serve. The shift from contiguous to paged allocation represents one of the most impactful engineering advances in inference infrastructure, and the emerging challenge of cross-request prefix caching points to the next frontier in reducing inference costs.

Technical Details

  • KV cache composition: For each token, the model computes Query (Q), Key (K), and Value (V) vectors. Q is transient (computed fresh per token and discarded), while K and V are immutable once computed and must be retained for all subsequent attention operations across all layers.
  • Memory formula: Per-token cache size = 2 × layers × KV heads × head dimension × bytes per value. A 70B-class model (80 layers, 8 KV heads, 128 head dim, FP16) consumes ~320 KB per token, meaning 8,000 tokens per user requires ~2.5 GB—exceeding the model's 140 GB weight footprint when serving ~100 users.
  • PagedAttention: Replaces contiguous pre-allocation with fixed-size blocks (commonly 16 tokens each), managed via a per-sequence block table. This eliminates over-reservation, external fragmentation, and bounds internal fragmentation to at most one partial block per sequence.
  • Eviction strategies: When the block pool is exhausted, the engine either recomputes (discards cache, rebuilds on resume via prefill) or swaps (copies blocks to/from CPU RAM over PCIe), both visible as mid-generation stalls to the user.
  • Optimization levers: Grouped-query attention (GQA) reduces KV heads (e.g., 8 vs. 64), cutting cache proportionally; KV cache quantization to 8-bit halves memory at some quality cost; context length caps bound per-request consumption; and architectural research into sliding-window, sparse, and linear attention aims to change the growth curve itself.

Industry Insight

  • Concurrency planning must account for context length distribution, not just model size—deployments that handle hundreds of short conversations may collapse under dozens of long-context ones on identical hardware.
  • PagedAttention has become a de facto standard in modern serving engines (vLLM, TGI, etc.); any production LLM deployment should verify its use, as naive contiguous allocators waste the majority of available VRAM.
  • Prefix caching across requests (reusing KV cache for shared system prompts and document contexts) represents the next major cost-reduction opportunity, as production traffic patterns reveal massive redundancy that current per-request isolation ignores.

TL;DR

  • KV Cache是LLM推理的核心优化机制,存储已计算token的Keys和Values,避免每步重复计算整个上下文
  • Cache内存消耗随context length和并发数双重增长,实际部署中常超过模型权重本身
  • PagedAttention通过分页分配替代预分配,消除外部碎片,显著提升GPU内存利用率和吞吐量
  • 并发上限由内存而非算力决定,内存耗尽时通过preemption+recompute/swap机制处理

为什么值得看

本文系统拆解了LLM推理服务的内存瓶颈本质,揭示了"cache管理即服务容量"的核心洞察。对AI工程师理解vLLM等现代推理框架的设计哲学至关重要,也为生产环境容量规划提供了量化依据。

技术解析

  • KV Cache计算成本:每token内存 = 2 × layers × KV heads × head_dim × bytes。70B模型约320KB/token,8K context单用户需2.5GB,100用户并发达250GB,超过140GB模型权重。
  • PagedAttention机制:将cache分割为固定大小block(通常16 token),按需分配而非预分配,通过block table实现逻辑到物理地址映射,消除外部碎片,仅尾部block存在内部碎片。
  • 内存满时的eviction策略:两种选择——recompute(丢弃cache,恢复时重算prefill)或swap(PCIe往返拷贝到CPU内存)。频繁preemption是部署超内存容量的明确信号。
  • 减小cache的三种杠杆:GQA(多query head共享KV,如8 vs 64 KV heads差异8倍)、KV quantization(FP16→INT8减半)、context length限制(最直接可控)。

行业启示

  • 容量规划必须绑定context长度:"单GPU能服务多少用户"无抽象答案,需结合典型对话长度评估,短对话稳定不代表长对话安全。
  • 内存管理是推理服务的核心竞争点:vLLM等框架的吞吐量优势本质来自更高效的cache分配算法,而非硬件优化。
  • 跨请求prefix重复计算是下一优化 frontier:相同system prompt和文档在每次请求中重复计算,request-level cache共享是潜在突破方向。

Disclaimer: The above content is generated by AI and is for reference only. 免责声明:以上内容由 AI 生成,仅供参考。

LLM 大模型 Inference 推理 Deployment 部署