⚙️ 15-AI-Infra · 05 KV Cache 与推理内存:为什么生成式推理要"缓存"¶
关键词:自回归 · prefill(预填充)/ decode(解码)· KV Cache · 推理显存公式 · 内存墙 · PagedAttention 分页
前置知识:04-LLM大模型 19-KV缓存(原理)、00-计算图与自动微分(激活显存)。
🧩 本讲定位:推理侧 AI Infra 的核心战场。为什么 decode 阶段"每步只出一个 token"却那么慢?KV Cache 给显存带来多大压力?PagedAttention 怎么"分页"救场?本讲用 numpy 手写带缓存的注意力解码并逐项计算显存。
本节要解决的问题¶
| 要解决的问题 | 对应内容 |
|---|---|
| 为什么要 KV Cache?省了什么算力? | 核心概念 (a) + 深入原理 1 + 实战 A |
| prefill 和 decode 为什么"两副面孔"? | 核心概念 (b) + 深入原理 2 + 实战 B |
| KV 内存公式怎么手算?多大算大? | 深入原理 3 + 实战 B |
| 手写带缓存的解码怎么保证一致? | 深入原理 4 + 实战 C |
| PagedAttention 分页解决什么碎片问题? | 深入原理 5 + 实战 D |
故事引入¶
小钱第一次部署 7B 模型:单卡 80GB,模型权重 14GB,看起来绰绰有余。结果并发一上来就 OOM。查了发现:KV Cache 是隐形的内存黑洞——batch 32、上下文 2048,KV 就要 34GB+,比权重还多。
更诡异的是"明明每秒只生成 20 个 token,GPU 利用率却只有 3%"。导师一句话点破:"decode 阶段每步要把全部权重 + 全部 KV 读一遍,就为了算一个新 token——这是内存带宽瓶颈,不是算力瓶颈。"小钱从此背下了 KV 公式和"推理两阶段画像",再去面试推理优化岗,张口就来。
核心概念¶
(a) 🔑 KV Cache 干什么¶
自回归解码第 $t$ 步:新 token 的注意力要和前面所有位置的 K/V 做点积。若没有缓存,每步都重算整个前缀的 K/V,前 $T$ 步累计 $O(T^2 d)$;有缓存则每步只算新位置的 K/V 并追加进缓存,累计 $O(T d)$:
$$ \text{Key}_t = X_t W_K,\quad \text{Value}_t = X_t W_V \quad\Rightarrow\quad \text{cache} \gets [\text{cache};\, K_t;\, V_t] $$
($K_t,V_t$ 形状 $(1,\,h_{kv}d_h)$,$h_{kv}$ 为 KV 头数:MHA 时 = 全部 Q 头数,GQA/MQA 时更小,见深入原理 3。)以 O(显存) 换 O(算力)(省下重复计算),是解码器推理的标配。
(b) ⚡ 两个阶段画像¶
| prefill 预填充(首 token) | decode 解码(后续 token) | |
|---|---|---|
| 每次处理 | 整条 prompt(并行度高) | 1 个 token(串行) |
| 瓶颈 | 算力(GEMM 打满) | 带宽(每步读全权重+KV) |
| 时延主导 | TTFT | TPOT / ITL |
(c) 💾 推理显存两大块¶
推理显存 ≈ 权重($2N$ 字节 BF16)+ KV Cache(随上下文/并发增长,可反超权重)+ 激活/临时。KV 公式见下。

图示:无缓存每步重算整个前缀的 K/V(累计 O(T²));有缓存把历史 K/V 存下来只追加新位置(累计 O(T))——以显存换算力。

图示:连续预分配每条请求占满 max_len(实际只用到 20~40%,长尾碎片);PagedAttention 按固定块分页、按需分配、物理不连续逻辑连续,显存利用率近 100%。
深入原理¶
1. 无缓存累计 O(T²) → 有缓存累计 O(T)¶
第 $t$ 步:无缓存时注意力要与前 $t$ 个位置交互,前向总计算量:
$$ \sum_{t=1}^{T} O(t \cdot d) = O(T^2 d)\xrightarrow{\text{带 cache}}\ \sum_{t=1}^{T} O(d) = O(T d) $$
省下的正是"重算历史 K/V"的部分——长 prompt/长生成场景收益巨大。(prefill 一次性算整条序列的注意力 $QK^\top$ 也是 $O(T^2 d)$,与这里 decode 的累计同阶。)
2. decode 是带宽受限:每步耗时与并发上界¶
每步 decode 需要:读全部权重 $2N$ 字节 + 全部 KV $M_{KV}$ 字节(batch 内所有请求的缓存),只产生每请求 1 个新 token 的输出。算术强度 $\approx \frac{\text{少量 FLOPs}}{\text{巨大 Bytes}}$ 极低 → 内存带宽打满、GPU 算力闲置(利用率常 <10%)。
带宽模型($\beta_{mem}$ = 内存带宽):
$$ t_{\text{step}} \approx \frac{2N + M_{KV}}{\beta_{mem}} \qquad\Rightarrow\qquad \text{吞吐} \approx \frac{B\cdot\beta_{mem}}{2N + M_{KV}}\ \text{tokens/s} $$
并发上界由 KV 内存决定($M_{mem}$ = 可用显存,$b$ = 每字节数):
$$ C_{\max} \approx \frac{M_{mem} - 2N}{M_{KV}(B{=}1)} = \frac{M_{mem} - 2N}{2\,L\,h_{kv}\,d_h\,T\,b} $$
例:7B(权重 14GB)、80GB 卡、$T=2048$、MHA FP16 → $C_{\max}\approx(80-14)/1.1\approx 60$ 路并发。长上下文/大并发下 KV 吃掉容量,decode 变慢的本质是每步读的字节更多,而非算力不足。
3. KV 内存公式(必背):M_KV = 2·L·B·T·h_kv·d_h·bytes¶
每层每个位置要存 K、V 各一份;每头维度 $d_h$,KV 头数 $h_{kv}$:
$$ M_{KV} = 2 \times L \times B \times T \times h_{kv} \times d_h \times \text{bytes} $$
MHA / GQA / MQA 的 KV 比例($h$ = 全部 Q 头数,$g$ = 每组 Q 头数):
| 变体 | Q 头数 | KV 头数 $h_{kv}$ | KV 相对 MHA | 例(LLaMA-7B:$h=32$) |
|---|---|---|---|---|
| MHA | $h$ | $h$ | $1$ | $h_{kv}=32$,KV 最大 |
| GQA | $h$ | $h/g$ | $1/g$ | $g=4$ → $h_{kv}=8$,KV 省 75% |
| MQA | $h$ | $1$ | $1/h$ | $h_{kv}=1$,KV 省 32 倍 |
以 LLaMA-7B($L=32,\ h=32,\ d_h=128$,FP16 2B):$B=1,\ T=2048$:
$$ M_{KV}=2\times32\times2048\times32\times128\times2\ \approx 1.1\,\text{GB}\ (B{=}1),\qquad B{=}32 \Rightarrow \approx 34\,\text{GB} $$
好记版:KV = 2 × 层数 × 批次 × 序列长 × KV 头数 × 头维 × 字节(K、V 各一份);GQA/MQA 通过缩小 $h_{kv}$ 让 KV 同比例下降。
4. 缓存一致性¶
带缓存的注意力 = 无缓存注意力的严格重排(把历史 Q·Kᵀ 的结果存住),数学完全等价;实现上只差"K/V 从哪里来"。
5. PagedAttention:分页解决"碎片 + 预分配浪费"¶
朴素实现给每条请求预分配连续 max-len 的 KV 空间 → 预留浪费(平均只用 20-40%)+ 长尾碎片。PagedAttention 把 KV 切成固定大小块(如 16 个 token/块),按需分配、物理不连续、逻辑连续。
两类碎片:
- 预留浪费 / 外碎片:连续预分配按 max_len 给每条请求,短请求用不满;分页按需给块,只在最后一块留块内碎片(internal fragmentation,平均半块 ≈ 8 token);
- 物理碎片:请求完成释放的页可立即被别处复用(页表把逻辑页重映射到任意空闲物理页),无需连续内存那样的搬移(compaction)。
额外红利:前缀共享(prefix sharing)——beam search / 并行采样时多条请求共享同一 prompt 前缀,页表把这些请求的相同前缀映射到同一物理页,公共前缀的 KV 只占一份,显存用量除以共享数。碎片近零 + 前缀共享 → 显存利用率接近 100%,配合连续批处理大幅提升吞吐。
代码实战 A:无缓存 vs 有缓存的累计计算量¶
先运行环境设置单元:
# 环境设置:中文字符输出 + matplotlib 中文(本单元必须先运行)
import sys, io
try:
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
except Exception:
try:
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", errors="replace")
except Exception:
pass
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
plt.rcParams["font.sans-serif"] = ["Microsoft YaHei", "SimHei"]
plt.rcParams["axes.unicode_minus"] = False
np.random.seed(0)
print("环境就绪")
plt.show()
环境就绪
T = np.arange(1, 513)
work_nocache = T * (T + 1) / 2 # O(T^2):每步重算前 t 个位置的注意力
work_cache = T.copy() # O(T):每步只算新位置
fig, ax = plt.subplots(figsize=(8.5, 4.5))
ax.plot(T, work_nocache, "-", label="无缓存:每步重算历史(O(T²) 累计)", color="#D32F2F")
ax.plot(T, work_cache, "-", label="有缓存:每步只要新位置(O(T) 累计)", color="#1976D2")
ax.set_xlabel("累计生成长度 T"); ax.set_ylabel("累计注意力工作量(相对)")
ax.set_title("KV Cache:以显存换算力,长生成收益巨大")
ax.legend(); ax.grid(alpha=0.3); plt.tight_layout(); plt.show()
print("T=512 时 无缓存/有缓存 ≈ %.0fx" % (work_nocache[-1] / work_cache[-1]))
T=512 时 无缓存/有缓存 ≈ 256x
C:\Users\24260\AppData\Local\Temp\ipykernel_34976\1186021564.py:9: UserWarning: FigureCanvasAgg is non-interactive, and thus cannot be shown ax.legend(); ax.grid(alpha=0.3); plt.tight_layout(); plt.show()
代码实战 B:KV 内存公式(M_KV = 2·L·B·T·h_kv·d_h·bytes)手算与曲线¶
MHA/GQA/MQA 只差 $h_{kv}$:Q 头共享后 KV 缓存按比例缩小(GQA g=4 → 省 75%,MQA → 1/h)。
def kv_mem_gb(L, h_kv, d_h, B, T, bytes_per=2):
"""M_KV = 2 × L × B × T × h_kv × d_h × bytes(K、V 各一份)。
h_kv:KV 头数(MHA=h,GQA=h/g,MQA=1);d_h:每头维度。"""
return 2 * L * h_kv * d_h * B * T * bytes_per / 1e9
L, h, d_h = 32, 32, 128 # LLaMA-7B:32 层、32 头、head_dim=128(h·d_h=4096)
w_mem = 7e9 * 2 / 1e9 # 权重 14 GB
print("7B 权重(BF16): %.0f GB" % w_mem)
print("MHA (h_kv=32) : KV@B=1 T=2048=%.1f GB | KV@B=32 T=2048=%.1f GB" %
(kv_mem_gb(L, h, d_h, 1, 2048), kv_mem_gb(L, h, d_h, 32, 2048)))
print("GQA (g=4, h_kv=8): KV@B=32 T=2048=%.1f GB(省 75%%)" % kv_mem_gb(L, h // 4, d_h, 32, 2048))
print("MQA (h_kv=1) : KV@B=32 T=2048=%.1f GB(省 %d 倍)" % (kv_mem_gb(L, 1, d_h, 32, 2048), h))
print("MHA KV@B=32 T=8192: %.1f GB(超权重!)" % kv_mem_gb(L, h, d_h, 32, 8192))
# --- decode 带宽模型与并发上界(数值演示) ---
mem_gb, beta_gbs = 80, 1.5e12 # 80GB 卡、HBM 带宽 1.5 TB/s
kv_b1 = kv_mem_gb(L, h, d_h, 1, 2048) # MHA:单请求 T=2048 的 KV
c_max = int((mem_gb - w_mem) // 1.1) # (80-14)/1.1 ≈ 60 路并发
bytes_step = (w_mem + 1.1 * c_max) * 1e9 # 每步读 权重+全部 KV
print("并发上界 C_max ≈ (80-14)/1.1 = %d 路请求" % c_max)
print("每步读 %.0f GB → 带宽受限吞吐 ≈ %d×1.5TB/s/%.0fGB ≈ %.0f tokens/s" %
(bytes_step / 1e9, c_max, bytes_step / 1e9, c_max * 1.5e12 / bytes_step))
Ts = np.array([128, 512, 2048, 8192])
fig, ax = plt.subplots(figsize=(8.5, 4.5))
for B, c in zip((1, 8, 32), ("#388E3C", "#FFB74D", "#D32F2F")):
ax.plot(Ts, [kv_mem_gb(L, h, d_h, B, t) for t in Ts], "o-", label="MHA B=%d" % B, color=c)
ax.plot(Ts, [kv_mem_gb(L, h // 4, d_h, 32, t) for t in Ts], "s--", label="GQA(g=4) B=32", color="#7B1FA2")
ax.axhline(w_mem, color="gray", ls="--", label="权重 14GB")
ax.set_xlabel("上下文长度 T"); ax.set_ylabel("KV Cache (GB)")
ax.set_title("KV 随 batch×序列长线性增长;GQA 把 h_kv 缩小 4 倍,KV 同比例下降")
ax.legend(); ax.grid(alpha=0.3); plt.tight_layout(); plt.show()
7B 权重(BF16): 14 GB MHA (h_kv=32) : KV@B=1 T=2048=1.1 GB | KV@B=32 T=2048=34.4 GB GQA (g=4, h_kv=8): KV@B=32 T=2048=8.6 GB(省 75%) MQA (h_kv=1) : KV@B=32 T=2048=1.1 GB(省 32 倍) MHA KV@B=32 T=8192: 137.4 GB(超权重!) 并发上界 C_max ≈ (80-14)/1.1 = 59 路请求 每步读 79 GB → 带宽受限吞吐 ≈ 59×1.5TB/s/79GB ≈ 1122 tokens/s
C:\Users\24260\AppData\Local\Temp\ipykernel_34976\1529576370.py:32: UserWarning: FigureCanvasAgg is non-interactive, and thus cannot be shown ax.legend(); ax.grid(alpha=0.3); plt.tight_layout(); plt.show()
代码实战 C:手写带 KV Cache 的解码(√d_h scale + causal mask + GQA)¶
先验证标准缩放注意力(除以 $\sqrt{d_h}$)下单头缓存的严格一致;再验证因果掩码整批解码与逐步缓存一致;最后测 GQA:多个 Q 头共享同一 K/V 头时缓存解码仍与全量一致(KV 量降为 MHA 的 $1/g$)。
def softmax(x, axis=-1):
"""按 axis 归一化的 softmax:1D(逐步) 与 2D(整批按行) 都正确。"""
e = np.exp(x - x.max(axis=axis, keepdims=True))
return e / e.sum(axis=axis, keepdims=True)
def attn(q, K, V, scale):
"""标准缩放点积注意力:softmax(q·Kᵀ / √d_h)·V(历史位置由调用方给定,天然因果)。"""
w = softmax((q @ K.T) * scale)
return w @ V
T_tot, d = 8, 4
np.random.seed(3)
X = np.random.randn(T_tot, d)
WK = np.random.randn(d, d); WV = np.random.randn(d, d); WQ = np.random.randn(d, d)
scale = 1.0 / np.sqrt(d) # √d_h scale:防止点积随维度增大而饱和(softmax 梯度消失)
# 参考(无缓存,因果):第 t 步只看 ≤t 的位置
def ref_step(t):
q = X[t] @ WQ
keys = X[:t + 1] @ WK
vals = X[:t + 1] @ WV
return attn(q, keys, vals, scale)
# 带缓存:逐步追加 K/V
K_cache = np.zeros((0, d)); V_cache = np.zeros((0, d))
outs = []
for t in range(T_tot):
K_cache = np.vstack([K_cache, X[t] @ WK]); V_cache = np.vstack([V_cache, X[t] @ WV])
outs.append(attn(X[t] @ WQ, K_cache, V_cache, scale))
err = max(np.abs(outs[t] - ref_step(t)).max() for t in range(T_tot))
print("√d_h 缩放 + 因果缓存解码 vs 全量重算 最大误差: %.2e" % err)
assert err < 1e-9
# --- 因果掩码测试:整批一次算(初始两两可见)再加 causal mask,应与逐步缓存完全一致 ---
Q_all = X @ WQ; K_all = X @ WK; V_all = X @ WV
S = Q_all @ K_all.T * scale
mask = np.triu(np.ones((T_tot, T_tot)), k=1) * (-1e9) # 上三角 → -∞(只看历史)
w_all = softmax(S + mask)
out_all = w_all @ V_all
err2 = max(np.abs(out_all[t] - outs[t]).max() for t in range(T_tot))
print("causal mask 整批解码 vs 逐步缓存 最大误差: %.2e" % err2)
assert err2 < 1e-9
print("✅ √d_h scale + causal mask 下:缓存解码 = 全量重算 = 掩码整批,三者严格一致")
# --- GQA 测试:h_q 个 Q 头共享 h_kv 个 K/V 头(每组 g 个 Q 头),缓存解码 vs 全量 ---
h_q, h_kv, g = 8, 2, 4
T_gqa, hdim = 8, 4
np.random.seed(5)
Xg = np.random.randn(T_gqa, hdim)
WQ = np.random.randn(h_q, hdim, hdim)
WK = np.random.randn(h_kv, hdim, hdim); WV = np.random.randn(h_kv, hdim, hdim)
scale = 1.0 / np.sqrt(hdim)
def gqa_forward(q, K, V):
"""q:(h_q,hdim) K/V:(t+1,h_kv,hdim) → 每 Q 头用其所在组的 K/V 头。"""
out = np.zeros((h_q, hdim))
for hq in range(h_q):
hk = hq // g
w = softmax((q[hq] @ K[:, hk, :].T) * scale)
out[hq] = w @ V[:, hk, :]
return out
def gqa_ref(t):
return gqa_forward(Xg[t] @ WQ,
np.einsum('tj,hjm->thm', Xg[:t + 1], WK), # 收缩 j:与 Xg[t]@WK[h] 等价
np.einsum('tj,hjm->thm', Xg[:t + 1], WV))
Kc = np.zeros((0, h_kv, hdim)); Vc = np.zeros((0, h_kv, hdim)); outs_gqa = []
for t in range(T_gqa):
Kc = np.concatenate([Kc, (Xg[t] @ WK)[None]], axis=0)
Vc = np.concatenate([Vc, (Xg[t] @ WV)[None]], axis=0)
outs_gqa.append(gqa_forward(Xg[t] @ WQ, Kc, Vc))
err3 = max(np.abs(outs_gqa[t] - gqa_ref(t)).max() for t in range(T_gqa))
print("GQA(h_q=%d, h_kv=%d, g=%d) 缓存解码 vs 全量: 最大误差 %.2e" % (h_q, h_kv, g, err3))
assert err3 < 1e-9
print("✅ GQA 一致:同组 Q 头共享同一 K/V 头,缓存解码与全量严格等价")
print("MHA KV vs GQA KV (B=16,T=2048,FP16): %.2f GB → %.2f GB(省 75%%)" % (
kv_mem_gb(L, h, d_h, 16, 2048), kv_mem_gb(L, h // g, d_h, 16, 2048)))
√d_h 缩放 + 因果缓存解码 vs 全量重算 最大误差: 1.33e-15 causal mask 整批解码 vs 逐步缓存 最大误差: 1.78e-15 ✅ √d_h scale + causal mask 下:缓存解码 = 全量重算 = 掩码整批,三者严格一致 GQA(h_q=8, h_kv=2, g=4) 缓存解码 vs 全量: 最大误差 1.33e-15 ✅ GQA 一致:同组 Q 头共享同一 K/V 头,缓存解码与全量严格等价 MHA KV vs GQA KV (B=16,T=2048,FP16): 17.18 GB → 4.29 GB(省 75%)
代码实战 D:PagedAttention 分页 vs 连续预分配(含块内碎片与前缀共享)¶
模拟 10 条请求:实际生成长度服从分布;对比"每条预分配 max_len 连续空间"与"按需分块"的显存占用与碎片,并量化**块内碎片(internal fragmentation)与前缀共享(prefix sharing)**的节省。
rng = np.random.default_rng(4)
n_req, max_len = 10, 1024
L, hd = 32, 4096
b2 = 2 # FP16
gen_lens = rng.integers(100, max_len, n_req) # 实际长度
def block_bytes(l, block_tokens=16):
return 2 * L * hd * b2 * l / 1e9 # KV 字节(GB)
# 连续预分配:每条固定 max_len
contig = n_req * block_bytes(max_len)
# 分页:按需给足整块(向上取整到 block_tokens 的倍数)
blk_tok = 16
pages = sum(int(np.ceil(l / blk_tok)) * blk_tok for l in gen_lens)
paged = block_bytes(pages)
# 实际使用
used = block_bytes(int(gen_lens.sum()))
print("连续预分配: %.1f GB | 分页按需: %.1f GB | 实际使用: %.1f GB" % (contig, paged, used))
print("利用率: 连续=%.0f%%,分页=%.0f%%" % (100 * used / contig, 100 * used / paged))
fig, ax = plt.subplots(figsize=(8, 4.2))
ax.bar(["连续预分配", "PagedAttention 分页", "实际使用"], [contig, paged, used], color=["#D32F2F", "#388E3C", "#1976D2"])
ax.set_ylabel("KV 显存 (GB)")
ax.set_title("10 条并发请求(长尾分布):分页近零浪费")
ax.grid(alpha=0.3, axis="y"); plt.tight_layout(); plt.show()
print("✅ 分页把 KV 利用率从 %.0f%% 提到 %.0f%%" % (100 * used / contig, 100 * used / paged))
# --- 块内碎片(internal fragmentation):每请求最后一块平均半块 ---
wasted = sum(int(np.ceil(l / blk_tok)) * blk_tok - l for l in gen_lens)
print("块内碎片: %.2f GB(占分页分配的 %.1f%%,平均每请求 ~半块=%d token)" %
(block_bytes(wasted), 100 * wasted / pages, blk_tok // 2))
# --- 前缀共享(prefix sharing):假设 10 条请求共享同一 256-token prompt 前缀 ---
prefix = 256
pp = int(np.ceil(prefix / blk_tok)) * blk_tok # 前缀按块对齐
saved = (n_req - 1) * pp # 公共前缀只存 1 份,省下 (n-1) 份
paged_shared = max(pages - saved, used) # 共享后分配至少等于实际使用
print("前缀共享(公共前缀 %d token): 省 %.2f GB" % (prefix, block_bytes(saved)))
print("分配(GB): 连续预分配 %.1f → 分页 %.1f → 分页+前缀共享 %.1f(实际使用 %.1f)" %
(contig, block_bytes(pages), block_bytes(paged_shared), used))
print("✅ 外碎片消失;只剩块内碎片(平均半块);公共前缀被多条请求共享,只存一份")
连续预分配: 5.4 GB | 分页按需: 4.0 GB | 实际使用: 4.0 GB 利用率: 连续=74%,分页=99% ✅ 分页把 KV 利用率从 74% 提到 99% 块内碎片: 0.04 GB(占分页分配的 1.1%,平均每请求 ~半块=8 token) 前缀共享(公共前缀 256 token): 省 1.21 GB 分配(GB): 连续预分配 5.4 → 分页 4.0 → 分页+前缀共享 2.8(实际使用 4.0) ✅ 外碎片消失;只剩块内碎片(平均半块);公共前缀被多条请求共享,只存一份
C:\Users\24260\AppData\Local\Temp\ipykernel_34976\334628135.py:25: UserWarning: FigureCanvasAgg is non-interactive, and thus cannot be shown ax.grid(alpha=0.3, axis="y"); plt.tight_layout(); plt.show()
面试考点¶
Q1 为什么要 KV Cache?¶
A:自回归解码每步注意力要跟全部历史位置交互;缓存 K/V 免去每步重算前缀,把 O(T²) 累计工作量降到 O(T)——以显存换算力,长生成收益巨大。
Q2 decode 为什么慢?¶
A:每步只产 1 个 token,却要读全部权重 + 全部 KV,算术强度极低 → 内存带宽受限、算力闲置(利用率常 <10%);优化方向是减少读权重(如 MQA/GQA、量化)与读 KV(稀疏注意力、KV 压缩)。
Q3 KV 内存公式?¶
A:$M_{KV}=2\times L\times B\times T\times h_{kv}\times d_h\times$ 字节($h_{kv}$ 为 KV 头数:MHA=$h$、GQA=$h/g$、MQA=1;MHA 时 $h_{kv}d_h$ = 隐藏维);7B、T=2048、B=32、MHA FP16 约 34GB,超过权重 14GB;GQA(g=4) 只要 8.6GB;长上下文或大并发时内存墙是主瓶颈。
Q4 prefill 和 decode 有什么区别?¶
A:prefill 并行处理整条 prompt、算力受限、决定 TTFT;decode 逐 token 串行、带宽受限、决定 TPOT/ITL;两者对批处理/量化的敏感度不同,调度时要分开优化。
Q5 PagedAttention 解决什么?¶
A:连续预分配的空间浪费与碎片(平均利用率 20-40%);按固定块分页、按需分配、物理不连续逻辑连续——外碎片消失,只剩每请求最后一块的块内碎片(平均半块);页表还支持前缀共享(beam/并行采样同一 prompt 的公共页只映射一次)→ 显存利用率近 100%,配合连续批处理吞吐大幅提升。
小结与自测清单¶
本讲要点:KV Cache 以显存换算力(累计 O(T²)→O(T));prefill 算力受限 vs decode 带宽受限(每步读 权重+KV,吞吐与并发上界由带宽/内存决定);KV 内存公式 M_KV = 2×L×B×T×h_kv×d_h×bytes(MHA/GQA/MQA 只差 h_kv,KV 按 1/g、1/h 缩小);√d_h scale + causal mask 下缓存解码与全量严格一致;PagedAttention 分页只剩块内碎片 + 前缀共享。
自测清单:
- 能默写 KV 内存公式并手算 7B B=32 T=2048 场景
- 能解释 decode 带宽受限与 MQA/GQA 的作用
- 能手写带 KV cache 的解码循环
- 能说明 PagedAttention 的块/页/前缀共享机制
下一讲预告:06-推理引擎:vLLM 连续批处理与投机解码(规划中)——缓存有了,怎么"调度"才能让 GPU 一直忙。