18KV Cache — Reuse Instead of Recompute
k_cache = torch.cat([k_cache, k_new], dim=1) # append, don't recompute
v_cache = torch.cat([v_cache, v_new], dim=1)
wei = q_new @ k_cache.transpose(-2,-1) * head_size**-0.5
Why K/V cached but not Q: not about weights being fixed (all three are equally fixed after training) — it's reuse count. k[t],v[t] get read by every future step; q[t] is used exactly once, the step it's born, then discarded.
x_new.shape=(3,1,8) → k_cache.shape=(3,1,4) — at this exact moment the cache contains only the current position's own k (nothing earlier exists yet), and attention still runs successfully. That's only possible because the new position attends to itself too, not just strictly-earlier positions — if the rule were really "t' < t", step 1 would have nothing to attend to at all. In the "俯视" (T,head_size) view from step 6: q (1,head_size) attends against k (t+1,head_size) — t+1 rows, covering positions 0 through t inclusive. This is also precisely why the code comment below says "no causal mask needed": self-inclusion plus zero future in the cache together mean there is nothing left that would ever need masking.head_size, not n_embd. Cell 35 sets n_embd=8 (the input dimension) but every printed k_cache.shape is (B, t, 4) — 4 is head_size. Wk projects n_embd→head_size before anything gets cached; the cache only ever stores post-projection vectors, never the raw n_embd-dimensional input.x_new.shape=(3,1,8) at every single step, including step 1 — this implementation processes even the prompt one token at a time through the same loop, rather than batch-filling the cache with the whole prompt in one (B,P,n_embd) call. A production KV-cache system normally does the latter (a real parallel prefill over all P prompt tokens, filling the cache once), then switches to (B,1,n_embd) only for decode afterward. This notebook's demo doesn't show that distinction — worth knowing it's a simplification for teaching the append/evict mechanism, not the only correct way to implement this.self(idx_cond) scores every position, but logits[:, -1, :] keeps only the last one. That waste is real but small — one lm_head projection, once, at the very end. This step is the big one: without a cache, every one of those same wasted iterations was also recomputing Wq/Wk/Wv and q@k.T/wei@v for every position, in every head, in every layer — n_layer×n_head repetitions per step, not 1. That's the scale difference between "a detail worth noticing" (step 13) and "the actual reason this optimization exists" (here).class HeadWithSlidingCache(nn.Module):
def __init__(self):
super().__init__()
self.Wq = nn.Linear(n_embd, head_size, bias=False)
self.Wk = nn.Linear(n_embd, head_size, bias=False)
self.Wv = nn.Linear(n_embd, head_size, bias=False)
self.k_cache = None
self.v_cache = None
def forward(self, x_new): # x_new: (B, 1, n_embd) -- B not hardcoded to 1
q_new = self.Wq(x_new) # (B, 1, head_size)
k_new = self.Wk(x_new)
v_new = self.Wv(x_new)
self.k_cache = k_new if self.k_cache is None else torch.cat([self.k_cache, k_new], dim=1)
self.v_cache = v_new if self.v_cache is None else torch.cat([self.v_cache, v_new], dim=1)
if self.k_cache.shape[1] > block_size:
self.k_cache = self.k_cache[:, -block_size:, :]
self.v_cache = self.v_cache[:, -block_size:, :]
wei = q_new @ self.k_cache.transpose(-2, -1) * head_size**-0.5
wei = F.softmax(wei, dim=-1) # no causal mask needed: q_new is 1 row, k_cache is all history
return wei @ self.v_cache
self.k_cache = None in __init__ is a plain Python attribute, not a registered buffer — it isn't saved by state_dict() and won't move with .to(device) automatically (you'd manage that yourself in a production version). torch.cat([self.k_cache, k_new], dim=1) reallocates a new, slightly bigger tensor every single call — this is the literal, physical reason KV-cache memory keeps growing: it's not appended in place, it's copy-and-grow.📓 Jupyter source — live from gpt-dev.ipynb, not hand-copied
cell 155e8b0e
# NOTE (cleanup, no values/behavior changed): renamed the bare n_embd/n_head/vocab_size/block_size in this self-contained demo to *_demo below, so this illustration can't silently overwrite the REAL model's globals set earlier in the notebook. import torch import torch.nn as nn import torch.nn.functional as F # 用一个极简 Head 演示:无 KV Cache vs 有 KV Cache 的推理差异 torch.manual_seed(0) n_embd_demo, head_size = 8, 4 class HeadNoCache(nn.Module): def __init__(self, block_size_demo): super().__init__() self.Wq = nn.Linear(n_embd_demo, head_size, bias=False) self.Wk = nn.Linear(n_embd_demo, head_size, bias=False) self.Wv = nn.Linear(n_embd_demo, head_size, bias=False) self.register_buffer('tril', torch.tril(torch.ones(block_size_demo, block_size_demo))) def forward(self, x): # x: (B, T, n_embd_demo) B, T, _ = x.shape q = self.Wq(x) # (B, T, head_size) k = self.Wk(x) # 每次调用都重新计算所有 T 个 k v = self.Wv(x) # 每次调用都重新计算所有 T 个 v wei = q @ k.transpose(-2,-1) * head_size**-0.5 wei = wei.masked_fill(self.tril[:T,:T]==0, float('-inf')) wei = F.softmax(wei, dim=-1) return wei @ v # (B, T, head_size) class HeadWithCache(nn.Module): def __init__(self): super().__init__() self.Wq = nn.Linear(n_embd_demo, head_size, bias=False) self.Wk = nn.Linear(n_embd_demo, head_size, bias=False) self.Wv = nn.Linear(n_embd_demo, head_size, bias=False) self.k_cache = None # 存历史 k,shape: (B, past_T, head_size) self.v_cache = None def forward(self, x_new): # x_new: (B, 1, n_embd_demo) — 只传入新 token q = self.Wq(x_new) # (B, 1, head_size) k_new = self.Wk(x_new) # (B, 1, head_size) — 只计算新 token 的 k v_new = self.Wv(x_new) # (B, 1, head_size) # 追加到 cache self.k_cache = k_new if self.k_cache is None else torch.cat([self.k_cache, k_new], dim=1) self.v_cache = v_new if self.v_cache is None else torch.cat([self.v_cache, v_new], dim=1) # Q 是新 token,K/V 来自全部历史(含自身) wei = q @ self.k_cache.transpose(-2,-1) * head_size**-0.5 wei = F.softmax(wei, dim=-1) # 不需要 causal mask:q 只有 1 行,k_cache 都是历史 return wei @ self.v_cache # (B, 1, head_size) # 模拟:序列 [t0, t1, t2, t3, t4],逐步生成 B, T, C = 1, 5, n_embd_demo full_seq = torch.randn(B, T, C) # 无 KV Cache:每步都把全序列喂进去 head_no_cache = HeadNoCache(block_size_demo=T) print("=== 无 KV Cache:每步重新计算全部 K/V ===") for t in range(1, T+1): out = head_no_cache(full_seq[:, :t, :]) k_computed = t # 这一步计算了 t 个 k 向量 print(f" 步骤 {t}: 输入 {t} 个 token,计算了 {k_computed} 个 K 向量(重复计算前 {t-1} 个)") # 有 KV Cache:每步只喂新 token head_cache = HeadWithCache() # 手动对齐权重,确保数学等价 with torch.no_grad(): head_cache.Wq.weight.copy_(head_no_cache.Wq.weight) head_cache.Wk.weight.copy_(head_no_cache.Wk.weight) head_cache.Wv.weight.copy_(head_no_cache.Wv.weight) print("\n=== 有 KV Cache:每步只计算新 token 的 K/V ===") for t in range(T): out = head_cache(full_seq[:, t:t+1, :]) # 只传 1 个新 token cache_size = head_cache.k_cache.shape[1] print(f" 步骤 {t+1}: 输入 1 个新 token,cache 中 K/V 数量: {cache_size},节省了重算 {t} 个历史 K/V") print(f"\nKV Cache 的存储结构(此例单层单头):") print(f" k_cache shape: {head_cache.k_cache.shape} (B=1, 已见过的 T={T} 个位置, head_size={head_size})") print(f" v_cache shape: {head_cache.v_cache.shape}") print(f"\n 完整模型: n_layer 个 Block,每个 Block 存一份 (K_cache, V_cache)") print(f" K_cache shape per layer: (B, n_head_demo, T_so_far, head_size)")
cell 8deef03f
# NOTE (cleanup, no values/behavior changed): renamed the bare n_embd/n_head/vocab_size/block_size in this self-contained demo to *_demo below, so this illustration can't silently overwrite the REAL model's globals set earlier in the notebook. import torch import torch.nn as nn import torch.nn.functional as F # 验证两件事: # (1) cache 超过 block_size_demo 后必须淘汰最旧的一条 —— 滑动窗口作用在 K/V 上 # (2) batch 维度 B 在 KV Cache 生成过程中原样保留,不会被"一次前进一个"压缩成 1 torch.manual_seed(0) n_embd_demo, head_size, block_size_demo = 8, 4, 4 # block_size_demo 故意设小,方便观察淘汰 class HeadWithSlidingCache(nn.Module): def __init__(self): super().__init__() self.Wq = nn.Linear(n_embd_demo, head_size, bias=False) self.Wk = nn.Linear(n_embd_demo, head_size, bias=False) self.Wv = nn.Linear(n_embd_demo, head_size, bias=False) self.k_cache = None self.v_cache = None def forward(self, x_new): # x_new: (B, 1, n_embd_demo) —— B 不是写死的 1 q_new = self.Wq(x_new) # (B, 1, head_size) k_new = self.Wk(x_new) v_new = self.Wv(x_new) self.k_cache = k_new if self.k_cache is None else torch.cat([self.k_cache, k_new], dim=1) self.v_cache = v_new if self.v_cache is None else torch.cat([self.v_cache, v_new], dim=1) # 滑动窗口:cache 超过 block_size_demo 就砍掉最旧的一条,等价于 idx[:, -block_size_demo:] 但作用对象是 K/V if self.k_cache.shape[1] > block_size_demo: self.k_cache = self.k_cache[:, -block_size_demo:, :] self.v_cache = self.v_cache[:, -block_size_demo:, :] wei = q_new @ self.k_cache.transpose(-2, -1) * head_size**-0.5 wei = F.softmax(wei, dim=-1) return wei @ self.v_cache # (B, 1, head_size) B = 3 # 故意用 B>1,验证"批"这个维度在生成阶段并未消失 T_total = 7 # 总共前进 7 步,超过 block_size_demo=4,必然触发淘汰 x_seq = torch.randn(B, T_total, n_embd_demo) head = HeadWithSlidingCache() print(f"batch_size B={B},block_size_demo={block_size_demo}(cache 容量上限)\n") for t in range(T_total): x_new = x_seq[:, t:t+1, :] # 每步只喂 1 个新位置,batch 维度 B 原样保留 out_new = head(x_new) evicted = " ← 已触发淘汰,丢弃最旧一条" if (t + 1) > block_size_demo else "" print(f"步骤 {t+1}: x_new.shape={tuple(x_new.shape)} → out_new.shape={tuple(out_new.shape)} " f"| k_cache.shape={tuple(head.k_cache.shape)}{evicted}") print(f"\n结论1(滑动窗口 ↔ KV Cache):cache 的容量上限就是 block_size_demo,超出后淘汰最旧的一条,") print(f" 和朴素版 idx[:, -block_size_demo:] 的滑动窗口是同一个约束,只是作用对象从 token id 变成了 K/V。") print(f"结论2(batch vs token):k_cache.shape[0] 始终等于 {head.k_cache.shape[0]}(=B),") print(f" '一次前进一个' 消掉的是序列长度维度 T,batch 维度 B 完全不受影响。")
📝 笔记 Chinese notes — live from gpt-dev.ipynb, not hand-copied
note 40ff40f0
KV Cache 与训练/推理的关系
重要前提:KV Cache 只属于推理,训练不用它
训练时整个序列一次并行处理,不存在"重复计算"问题,所以不需要 cache。
KV Cache 解决的是推理时的冗余:每生成一个新 token 都要对整个历史序列重跑一遍 attention,而历史序列的 K 和 V 根本没变——cache 就是把它们存起来复用。
KV Cache 的最小单元:每个 Block(层)一份 (K_cache, V_cache)
模型结构:
Block 0 (MultiHeadAttention → FeedForward)
├── Head 0: W_q0, W_k0, W_v0
├── Head 1: W_q1, W_k1, W_v1
└── Head 2, Head 3 ...
Block 1 ...
Block 2 ...
Block 3 ...
KV Cache 存储结构(推理时,生成到第 t 步):
Block 0 → K_cache shape: (B, n_head, t, head_size)
→ V_cache shape: (B, n_head, t, head_size)
Block 1 → K_cache, V_cache (同上)
Block 2 → K_cache, V_cache
Block 3 → K_cache, V_cache
最小单元是每个 Block(层)的 (K_cache, V_cache),内部已经把所有 head 的 K/V 合并成了 (B, n_head, T, head_size) 的 4D 张量,不需要单独为每个 head 存一份。
训练 vs 推理:本质上只差 3 行
# ── 训练循环 ──────────────────────────────────
model.train()
xb, yb = get_batch('train') # 随机采样 (ix)
logits, loss = model(xb, yb) # 前向传播
loss.backward() # ← 训练独有
optimizer.step() # ← 训练独有
optimizer.zero_grad() # ← 训练独有
# ── 推理(generate 内部)────────────────────────
model.eval()
with torch.no_grad(): # ← 推理独有:不追踪梯度
logits, _ = model(idx_cond) # 前向传播(相同的 forward 函数!)
# 取最后一步的 logits → softmax → 采样下一个 token
forward() 函数完全相同,PyTorch 自动区分梯度追踪模式。
model.train() 开启 Dropout;model.eval() 关闭 Dropout,但 forward 的数学逻辑一字不差。
note 0ae0a325
精确修正:为什么只有 K/V 被缓存、Q 不需要——不是"权重新旧",而是"复用次数"
一个常见的偏差:把"K/V 被缓存"归因于"训练后 W_k、W_v 的权重已经固定",而 Q "是新的,真实来自 prompt input"。
需要澄清:W_q、W_k、W_v 训练后同样固定,三者在这一点上完全对称——
q = x @ W_q、k = x @ W_k、v = x @ W_v,公式形式、权重的"固定程度"没有任何区别,
推理时三者都是用同一套训练好的固定权重去做同样的线性投影。
真正决定"要不要缓存"的,不是权重是否固定,而是这个向量在后续生成过程中会被读取(复用)几次:
位置 t 的 k[t]、v[t]:
- 生成第 t 步时算一次
- 之后每一步(t+1, t+2, ..., T-1)的新 query 都要回头和 k[t] 算相似度、用 v[t] 加权
- 被读取次数 = 未来还会生成的步数(越早出现的 token,被复用次数越多)
- 不缓存 → 每一步都要把 0..t 全部重新过一遍 W_k、W_v → 造成 O(T) 级别的重复计算
位置 t 的 q[t]:
- 生成第 t 步时算一次
- 仅在这一步内部使用一次:q[t] @ k[0..t].T → 算出 wei[t, :]
- 算完这一步就再也不会被用到——没有任何未来步骤会"回头用旧的 q"
- 复用次数 = 1 次 → 缓存它没有意义,因为它天生只用一次即报废
一句话总结:q/k/v 权重的"固定"是三者共同的前提,不是区分点;真正的区分点是 k、v 会被未来所有位置反复读取,而 q 天生只在诞生的那一步被用一次。
再修正一处描述:out = wei @ v 严格来说不是"把标量逐个追加到矩阵元素上",而是加权求和——
每个标量 wei[t,t'] 缩放对应的向量 v[t'],再把这 T 个缩放后的向量按位相加,得到一个仍然是 head_size 维的输出向量 out[t]
(维度不会变大,也没有"新增元素")。而这个 out,才是真正通过残差连接 x = x + self.sa(...) 加回到带有 embedding+position 信息的 x 上的东西——
加回去的是"经相似度加权融合后的 v 内容",而不是相似度分数(wei)本身。