KV-Cache

分类: 高效推理与部署

KV-Cache

定义

Transformer 自回归推理中缓存已计算的 Key 和 Value 矩阵,避免重复计算的加速技术

数学形式

Attention(Q,Kcache,Vcache)=softmax(QKcachedk)Vcache\text{Attention}(Q, K_{\text{cache}}, V_{\text{cache}}) = \text{softmax}\left(\frac{Q K_{\text{cache}}^\top}{\sqrt{d_k}}\right) V_{\text{cache}}

核心要点

每个新 token 生成时只需计算当前 token 的 Q,复用之前所有 token 的 K/V

内存占用随序列长度线性增长:O(nLd)O(n \cdot L \cdot d)nn 层,LL 序列长度,dd 维度)

在 LVLM 中,视觉 token 剪枝直接减少 KV-Cache 大小

压缩策略:量化(如 INT8)、稀疏化(如 SnapKV)、token 剪枝

代表工作

SnapKV: 基于注意力模式的 KV-Cache 压缩

PyramidKV: 金字塔式 KV-Cache 分配

StreamingLLM: 流式推理中的 KV-Cache 管理

ResPrune: 通过视觉 token 剪枝减少 KV-Cache(88.9% pruning → 88.9% KV-Cache 降低)

相关概念

Self-Attention

FlashAttention

Visual Token Pruning