14Incremental Decode — One New Token at a Time
for _ in range(max_new_tokens):
idx_cond = idx[:, -block_size:]
logits, _ = self(idx_cond)
This "1" is forced by the autoregressive causal chain itself, not implementation laziness: token t+1's embedding depends on which exact token got sampled at step t, which depends on step t's model output — a serial dependency you cannot precompute around. forward()'s matmuls don't care whether T_new is 1 or 5; it's the calling loop that enforces 1.
HeadWithSlidingCache), where only the genuinely-new token gets a fresh forward pass. In this literal naive generate(), only one new token id is produced per iteration (highlighted above) — but the model still reprocesses the full window to get it. The "1" that's truly architecturally locked in either way is num_samples=1: you can only sample the next token once you know this step's output.- The "1" in
(B,1,n_embd)— how many tokens' embeddings get fed intoforward()this step. Only true for the KV-cache version (step 18). In THIS literal naivegenerate(), the fed shape is(B,T,n_embd)where T is the whole current window — not 1. - The "1" in
num_samples=1— how many new token IDs get sampled this step. IDENTICAL in both the naive and cache versions, no exceptions. Locked by the autoregressive causal chain — you must know step t's actual sampled token before step t+1 can even be called — completely unrelated to whether a cache exists. - One more precision worth having: what a loop iteration actually produces is
idx_next, shape(B,1)— a raw integer token id, not yet passed through any embedding table.(B,1,n_embd)is a further, downstream shape that only exists in the cache version, appearing after that new id gets embedded (x_new = token_embedding_table(idx_next)).
def generate(self, idx, max_new_tokens):
for _ in range(max_new_tokens):
idx_cond = idx[:, -block_size:] # window slides once idx > block_size
logits, loss = self(idx_cond) # STILL reprocesses the whole window!
logits = logits[:, -1, :]
probs = F.softmax(logits, dim=-1)
idx_next = torch.multinomial(probs, num_samples=1) # <- this 1 new token
idx = torch.cat((idx, idx_next), dim=1)
return idx
📓 Jupyter source — live from gpt-dev.ipynb, not hand-copied
cell 8119b626
class BigramLanguageModel(nn.Module): def __init__(self): super().__init__() # each token directly reads off the logits for the next token from a lookup table # 将vocab_size个字符映射到n_embd维的向量空间中 # 输入xb和yb是形状为(B,T)的整数张量,输出是形状为(B,T,C)的浮点数张量,其中C是内部的维度n_embd self.token_embedding_table = nn.Embedding(vocab_size, n_embd) # 位置向量的计算基于sequence的长度T,所以输入是一个长度为T的整数张量,输出是一个形状为(T,C)的浮点数张量 self.position_embedding_table = nn.Embedding(block_size, n_embd) # 因为作为基本transformer单元的Block输出形状是B,T,n_embd,所以输入也是B,T,n_embd,输出也是B,T,n_embd self.blocks = nn.Sequential(*[Block(n_embd, n_head=n_head) for _ in range(n_layer)]) self.ln_f = nn.LayerNorm(n_embd) # final layer norm # 将B,T,n_embd维的表示映射回vocab_size维的空间中,得到每个位置上每个字符的预测分数,变成B,T,vocab_size的形状 self.lm_head = nn.Linear(n_embd, vocab_size) def forward(self, idx, targets=None): B, T = idx.shape # idx and targets are both (B,T) tensor of integers,we pass them through the model to produce logits, which are (B,T,vocab_size) tensor of floats # 输入来自xb和yb是形状为(B,T)的整数张量 tok_emb = self.token_embedding_table(idx) # (B,T,C) pos_emb = self.position_embedding_table(torch.arange(T, device=device)) # (T,C) # 这里的广播机制会将pos_emb从(T,C)扩展到(B,T,C),使得每个序列位置都有一个对应的嵌入向量 x = tok_emb + pos_emb # (B,T,C) x = self.blocks(x) # (B,T,C) 之前被误注释掉,导致 attention/FFN 完全不生效,这里改正 x = self.ln_f(x) # (B,T,C) logits = self.lm_head(x) # (B,T,vocab_size) if targets is None: loss = None else: B, T, C = logits.shape logits = logits.view(B*T, C) targets = targets.view(B*T) loss = F.cross_entropy(logits, targets) return logits, loss # generate def generate(self, idx, max_new_tokens): # idx is (B, T) array of indices in the current context for _ in range(max_new_tokens): # crop idx to the last block_size tokens idx_cond = idx[:, -block_size:] # get the predictions logits, loss = self(idx_cond) # focus only on the last time step logits = logits[:, -1, :] # becomes (B, C) # apply softmax to get probabilities probs = F.softmax(logits, dim=-1) # (B, C) # sample from the distribution idx_next = torch.multinomial(probs, num_samples=1) # (B, 1) # append sampled index to the running sequence idx = torch.cat((idx, idx_next), dim=1) # (B, T+1) return idx
📝 笔记 Chinese notes — live from gpt-dev.ipynb, not hand-copied
note d8d6b1d8
追问核实:1-step 限制在哪里生效 + 训练/推理显存差异的真正原因
1)确认:x_new = x_seq[:, t:t+1, :] 说得对——"1"是调用方式决定的,不是 forward() 内部写死的
forward()(不管是 HeadNoCache 还是 HeadWithSlidingCache)内部的矩阵运算完全不关心传进来的 T_new 是 1 还是 5——
Wq(x_new)、q @ k_cache.T、wei @ v_cache 这些操作对任意 T_new 都成立,forward() 本身没有任何地方强制 T=1。
"每步只新增 1 个 token"是外层循环的调用方式决定的,跟 nanoGPT 真实的 generate() 一模一样:
for _ in range(max_new_tokens):
...
idx_next = torch.multinomial(probs, num_samples=1) # 这一步只能采出 1 个 token
idx = torch.cat((idx, idx_next), dim=1) # 追加 1 个,循环重新开始
本质原因还是自回归因果链:必须先采样出第 t 个 token,才能知道第 t+1 步喂什么, 所以调用方一次只能"喂 1 个"——不是 forward() 强制的,是这条因果链决定了调用方只能这么调用。
2)需要修正一处:不用 1-step 限制,走的是"朴素/无 cache 推理",不是"训练"
如果把 x_new = x_seq[:, t:t+1, :] 换成每步直接喂整个 (B,T,C) 窗口(就是本 notebook 前面的 HeadNoCache 演示,
也是 nanoGPT 真实 generate() 朴素版的做法:idx_cond = idx[:, -block_size:]),
确实会导致每一步都重新做一次"全窗口并行矩阵运算"——计算的形状和训练时的一次前向传播相同。
但这仍然是推理,不是训练——训练和推理的本质区别是"要不要 loss.backward() + optimizer.step()",
朴素版 generate() 全程都在 torch.no_grad() 下跑,没有反向传播、没有梯度、没有优化器状态,
只是计算的"形状"恰好和训练一次前向传播相同(都是整窗口并行),仅此而已。
3)关键修正:KV Cache 是"花显存换算力",方向和直觉相反
不用 cache(朴素重算):
每步都重新算整个窗口的 q/k/v → 计算量随步数近似 O(T²) 累积增长(浪费大量重复计算)
但没有"持续常驻"的显存开销——每步算完的 q/k/v 用完即丢,不需要跨步保留
用 cache:
每步只算新 token 的 q/k/v,计算量随步数只是 O(T) 累积增长 → 省下大量重复计算
但 k_cache/v_cache 必须在整个生成过程中持续占用显存,且随生成长度不断增长
→ 这正是大模型服务中"KV Cache 显存爆炸"是主要瓶颈之一的原因(vLLM 的 PagedAttention 就是为了管理它)
标准说法是:KV Cache 用增加且持续增长的显存占用,换取减少重复计算(节省推理算力/时间),是"以存换算",不是"省显存"。
4)训练比推理更吃 GPU 的真正主因,和 KV Cache 无关
即使完全不用 KV Cache(对比朴素推理 vs 训练),推理依然远比训练省显存,原因是:
训练额外需要(推理完全不需要):
- 反向传播要保留每一层的中间激活值,直到反向传播算完梯度才能释放
- 每个参数都需要一份同尺寸的梯度 buffer
- 优化器状态(如 Adam 需要额外 2 份动量 buffer)→ 仅优化器状态就约等于 3~4 倍参数量的显存
这几项加起来,通常是模型参数本身显存占用的数倍——这才是"训练没有强力 GPU 不太行"的主因, 跟是否使用 KV Cache、是否 1-step 限制完全无关(训练本身从来不用 KV Cache)。
5)量化(Quantization)是另一条独立的显存优化手段,同样和 KV Cache 无关
量化把模型权重(有时也包括 KV Cache 本身)压缩成更低精度(int8/int4),进一步降低显存占用, 这是叠加在"推理本来就比训练省显存"这个基础上的额外优化,几乎只用在推理阶段—— 训练阶段用低精度直接更新梯度容易导致数值不稳定、难以收敛(虽有 QAT 等专门技术,但那是另一套更复杂的方案)。
一句话总结:推理比训练省显存的主因是"没有反向传播和优化器状态";KV Cache 是推理内部"用显存换算力"的技巧;量化是在此基础上进一步压缩权重体积的独立手段——三者是三个不同层面的问题,不能相互替代解释。
note 53be4247
交叉验证:(B,1,n_embd) 和 num_samples=1,是两个不同的"1",容易被合并混淆
1)(B,1,n_embd) 只属于 KV Cache 版本,不属于朴素 generate()
朴素版 generate() 里,self(idx_cond) 喂进去的是整个窗口,形状是 (B, T, n_embd)(T 随 idx 增长,直到被 idx[:, -block_size:] 顶满),不是 (B,1,n_embd)——朴素版本每一步依然"STILL reprocesses the whole window"。(B,1,n_embd) 这个窄形状,只出现在有 KV Cache 的版本里(比如 HeadWithSlidingCache),因为那里每一步真的只把"新 token 的 embedding"喂进去。
2)真正在两个版本里都"锁死"的,是 num_samples=1,原因是自回归因果链,不是 KV Cache
(B,1,n_embd) 的 "1" —— "这一步前向传播喂进去几个 token 的 embedding"
只有 cache 版本是 1,朴素版本这里是整个窗口的长度,不是 1
num_samples=1 的 "1" —— "这一步采样出几个新 token id"
朴素版本、cache 版本都是 1,两者完全一样,跟有没有 cache 无关
num_samples=1 锁死的原因是自回归因果链:必须先知道第 t 步真实采样出的是哪个 token,才能确定第 t+1 步该喂什么。这个约束在训练阶段体现为"用 t 位置的预测去比对 t+1 位置的真实 target 算 loss"(教师强制、T 个位置并行);在推理阶段体现为"每次只能往前走一步,因为下一步的输入依赖这一步真实采出来的结果"(没有真实的未来 token 可用,只能靠自己采样的结果串行推进)——两者是同一条因果链在不同阶段的两种表现。
3)需要精确一处:generate() 每步真正"产出"的是 (B,1) 的 token id,不是 (B,1,n_embd)
idx_next = torch.multinomial(probs, num_samples=1) 产出的形状是 (B,1)——原始 token ID(整数),还没经过 embedding 查表。(B,1,n_embd) 是这个新 token 过完 embedding 之后、且只在 cache 版本里才会出现的中间形状(对应 token_embedding_table(idx_next) 之后的结果)。两个形状描述的是流程里不同的两个环节:朴素版本每步产出一个 (B,1) 的 token id;cache 版本额外多做一步,把这个新 token id 查表变成 (B,1,n_embd) 的 embedding,再单独喂进带 cache 的 forward()。