20Loop Back to Decode

Back to step 14 — one more token, forever (or until max_new_tokens)
for _ in range(max_new_tokens): # steps 14 → 19 repeat, once per new token
the whole Phase 3 decode cycle repeats

Steps 14-19 repeat once per generated character: compute new token's Q/K/V → append to cache → slide if over capacity → softmax → sample → append to sequence → repeat. Batch size B never shrinks through any of this — B independent sequences advance together, one token each, every iteration.

full source — the outer driver loop, KV-cache version (gpt-dev.ipynb style)ties steps 14-19 together
for t in range(T_total):                    # once per new token, steps 14 -> 19
    x_new = x_seq[:, t:t+1, :]              # step 14: exactly 1 new position
    out_new = head(x_new)                   # runs HeadWithSlidingCache.forward()
                                             #   -> steps 15-16 happen inside your
                                             #      full generate(): softmax + sample
                                             #   -> step 17: idx = torch.cat(...)
                                             #   -> steps 18-19 happen inside forward():
                                             #      cache append + evict-if-over-capacity
Nothing new PyTorch-internally here — this is the same for loop mechanics as step 14's generate(), just annotated to show which earlier step each part of one iteration corresponds to. The loop itself is plain Python; every actual tensor operation inside it was already covered in steps 14-19.

📓 Jupyter source — live from gpt-dev.ipynb, not hand-copied

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 d815cbed

融会贯通:Embedding 固定 + Q/K/V 复用差异 + 滑动窗口 + Batch 维度

1)确认:两次查表(token_embedding_table、position_embedding_table)在推理时权重同样固定

nn.Embedding 的 .weight 本质就是一个可学习的查找表矩阵(形状分别是 (vocab_size, n_embd) 和 (block_size, n_embd))。 训练结束后这两个矩阵和 W_q/W_k/W_v 一样被固定;推理时 tokenizer → token_id → 查表 得到的 tok_emb、pos_emb, 用的都是训练好的固定权重,数学过程与训练时完全一致,只是不再有 loss.backward() / optimizer.step()。

2)再确认一次用词:"追加"应改成"加权求和"

wei @ v 不是把标量"追加"进 v,而是每个 wei[t,t'](标量)缩放对应的 v[t'](向量)后按位相加, 输出仍是 head_size 维——是加权融合,不是拼接/追加。

3)KV Cache 必须和滑动窗口(block_size)绑在一起理解

朴素版 generate()(idx_cond = idx[:, -block_size:])每一步都把窗口内全部 token 重新算一遍—— 滑动窗口在朴素版里只解决"模型能接受多长输入",不解决"重复计算"。

引入 KV Cache 后,滑动窗口的含义要多加一层:

朴素版滑动窗口:       idx     = idx[:, -block_size:]      → 砍掉最旧的 token id
KV Cache 版滑动窗口:  k_cache = k_cache[:, -block_size:]   → 砍掉最旧的 K
                       v_cache = v_cache[:, -block_size:]   → 砍掉最旧的 V(同理)

"一次前进一个" 指的是:每一步只对 1 个新 token 跑一次前向(只算它的 q_new/k_new/v_new), k_new/v_new 追加进 cache,cache 一旦超过 block_size 就砍掉最旧的一条—— 这就是为什么必须先理解滑动窗口,才能理解 KV Cache 的边界条件(cache 不是无限增长的)。

而 Q 不需要缓存的原因和滑动窗口无关(上一轮已确认过):q_new 只在诞生的这一步内部用一次,用完即弃, 根本不存在"要不要用滑动窗口保留它"这个问题——它从一开始就没打算被复用。

4)"一次前进一个"指的是 batch 里每条序列各前进一个 token,不是把 batch 折叠成 1

训练时:get_batch() 一次给出 (B, block_size) 个 token,B 条序列全部并行、每条序列内部 T 个位置也全部并行(teacher forcing)。

生成时(用 KV Cache):每一步的输入形状是 (B, 1, n_embd),不是 (1, 1, n_embd)—— B 这个维度原封不动地保留,因为完全可以同时生成 B 条独立序列(比如一次采样 4 个候选回答); "一次前进一个"消掉的是序列长度维度 T(从"一次处理多个位置"变成"一次只处理新增的 1 个位置"), 这和 batch 维度 B 是两件独立的事——B 条序列各自独立地、各前进 1 个 token,互不合并、互不影响。