13Prefill — Process the Whole Prompt in Parallel

WIDE — the whole prompt goes in at once, exactly like Phase 1's forward pass. Same table as step 3, now FROZEN — real row-gather arrow, not a fragile front→top guess
idx_cond = idx[:, -block_size:] logits, _ = self(idx_cond) # SAME forward() as training, no targets
(B, P, n_embd) — T=P here, NOT 1

This is exactly Phase 1's forward pass, reused unchanged, just with model.eval() + torch.no_grad() and no loss. The prompt's P tokens are processed in parallel, same as any training batch.

Important correctness note: this literal generate() has no KV cache — idx_cond = idx[:, -block_size:] takes the whole recent window every single iteration, and self(idx_cond) reprocesses all of it from scratch, every time. "Prefill" here just means: the first time through this loop, that window happens to equal your original prompt. Step 18's KV Cache is a genuine optimization on top of this naive code, not something already present in it.
The diff: what actually changes between iteration 1 and every iteration after. The loop body's code is identical every single pass — only idx's content grows:
iteration 1:  idx = [18,47,56,57,58,1]                (T=6=P)   ← idx_cond IS the prompt, unchanged
iteration 2:  idx = [18,47,56,57,58,1, 43]            (T=7)     ← +1 generated token appended (illustrative id)
iteration 3:  idx = [18,47,56,57,58,1,43, 12]         (T=8)     ← +1 more
   ...
iteration 27: idx now holds 32 tokens (P=6 + 26 generated)      ← window exactly full (block_size=32)
iteration 28: idx_cond = idx[:, -block_size:] now DROPS the oldest token — sliding window starts here
This is the concrete version of the code's own comment, "1st time through: idx IS the prompt" — and it's only true for iteration 1. From iteration 2 onward this is conceptually "decode," even though, as the note above says, nothing in the code distinguishes them — it's the exact same self(idx_cond) call regardless of iteration number. That code-level distinction only starts to exist once KV Cache (step 18) is introduced: first call fills the cache from P tokens, every call after appends exactly 1.
A real, visible waste you can already see here — and how it connects to step 18, precisely. self(idx_cond) computes logits for every position in the window, shape (B,T,vocab_size) — but logits = logits[:, -1, :] keeps only the last position (the one predicting the actual next token) and discards the other T−1 positions' scores, unused. Real and worth noticing — but it's the small example of naive recompute, not the main one: this waste only touches lm_head, one projection, once, at the very end of the whole forward pass. The much larger waste — the one KV Cache actually exists to fix — is every layer's Wq/Wk/Wv projection plus q@k.T/wei@v, recomputed n_layer×n_head times, every single iteration. That's precisely why step 18's cache is stored per Block, not at lm_head — the waste is concentrated deep in attention, not the final vocabulary projection.
max_new_tokens — a caller-supplied hyperparameter, not part of the architecture. It's simply "how many new tokens should this call to generate() produce" — e.g. the 100 in model.generate(context, max_new_tokens=100). Unrelated to block_size or n_embd: you can set it far larger than block_size safely, since idx_cond = idx[:, -block_size:] keeps clipping the window every iteration regardless of how long idx has grown.
full source — BigramLanguageModel.generate() (gpt-dev.ipynb)the very first loop iteration
def generate(self, idx, max_new_tokens):
        # idx is (B, T) array of indices in the current context
        for _ in range(max_new_tokens):
            idx_cond = idx[:, -block_size:]   # 1st time through: idx IS the prompt
            logits, loss = self(idx_cond)     # same forward() as steps 3-10, no targets
            logits = logits[:, -1, :]
            probs = F.softmax(logits, dim=-1)
            idx_next = torch.multinomial(probs, num_samples=1)
            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 2a5d5d0b

推理全流程 + 上下文窗口

Pre-trained 模型(权重全部固定)
  ↓
prompt 文本 → tokenizer → token IDs (整数序列,长度 P)
  ↓
Step 0  第一次前向传播(处理整个 prompt):
  - prompt 的 P 个 token 一次并行喂入
  - 走 embedding → n_layer 个 Block(attention + FFN)
  - 每个 Block 的 K/V 全部 cache(shape: B, n_head, P, head_size)
  - 取最后一个位置的 logits → 采样 → 得到第一个输出 token t₁
  ↓
Step 1  只喂入 t₁(1 个 token):
  - 计算 t₁ 的 Q、K_new、V_new
  - K_new 追加到 cache → cache size = P+1
  - Q 对整个 cache 做 attention → 得到 t₁ 位置的输出 → 采样 t₂
  ↓
Step 2  只喂入 t₂ ...(重复)

当 cache size 达到 block_size(最大上下文长度):
  - 丢掉最旧的那条 cache(向左滑动)
  - 模型"忘记"最早的 token
  - 窗口始终保持 block_size 大小

关键:prompt 处理是一次并行,后续 token 生成是逐步串行 + 窗口滑动

note b75ba165

追问核实:朴素 generate() 里,prefill/decode 到底浪费在哪、max_new_tokens 是什么、prefill 是不是"预热"

1)max_new_tokens 是调用方传入的超参数,跟模型架构无关

它不是模型内部固定的东西,就是"这次调用 generate(),你想让它再生成多少个新 token",由调用方决定, 比如 model.generate(context, max_new_tokens=100) 里的 100。它和 block_size(架构上限)没有绑定关系—— 可以设成比 block_size 大得多的数,因为 idx_cond = idx[:, -block_size:] 会不断裁剪窗口,保证喂进模型的永远不超过 block_size。

2)朴素版 generate() 里,logits 也有一部分被白算——补充在"K/V 重复计算"之外的另一处浪费

logits, loss = self(idx_cond)     # (B, T, vocab_size) —— 当前窗口每一个位置的 logits 全部被算出来
logits = logits[:, -1, :]         # 只取最后一个位置的结果去采样,前面 T-1 个位置的 logits 直接丢弃

self(idx_cond) 内部把当前窗口每一个位置的 logits 都算出来了,但只有最后一个位置(即将预测"下一个 token"的那个位置)会被用来采样,前面 T-1 个位置的 lm_head 投影结果被白白算出来又直接丢弃。

这处浪费和"K/V 被重复计算"是同一个"朴素重算"问题的两个症状,但量级不同:lm_head 投影只发生一次(在整个前向传播的最后一步),而 Wq/Wk/Wv 投影和 q@k.T/wei@v 是在 每一层 Block、每一个 head 上都重复一遍——如果模型有 n_layer 层、每层 n_head 个头,attention 部分的重复计算量是 lm_head 这一次投影浪费的很多倍。KV Cache 真正要解决的大头是深埋在每一层 attention 里被反复重算的 K/V,不是最后这一次词表投影,这也是为什么 KV Cache 设计成"每层 Block 各存一份 (K_cache, V_cache)",而不是在 lm_head 那里做缓存。

3)"prefill 阶段"精确到只有第一次循环,这份朴素代码其实分不清 prefill/decode

for _ in range(max_new_tokens): 会循环 max_new_tokens 次。只有第一次循环,idx_cond 恰好等于 prompt 本身(T=P); 从第二次循环开始,idx 已经把上一步生成的新 token 拼接进去了,概念上已经进入 decode 阶段,不再是 prefill。

但因为这份 generate() 完全没有 KV Cache,第 1 次循环和第 100 次循环走的是一模一样的代码路径(都是"整窗口重新算一遍"), 没有任何代码层面的区别对待——prefill/decode 只是我们事后概念上贴的标签,代码本身分不出来。 真正让 prefill/decode 产生代码级别差异的,是引入 KV Cache 之后:第一次调用变成"处理 P 个 token、把 cache 填满", 之后每次调用变成"只处理 1 个新 token、往 cache 里追加"——这时候两者才是真正不同的两段逻辑。

4)prefill 不是"预热模型"——模型权重全程冻结,prefill 真正的作用是"为后续解码建立可复用的 K/V"

"预热"暗示了"模型内部有什么东西被调整/准备好了",但这里模型权重是冻结不变的,prefill 并不会改变模型任何状态。 prefill 真正的作用(在有 KV Cache 的系统里)是"把 prompt 对应的 K/V 算出来存进 cache,供后面每一步解码复用"; 而在朴素/无 cache 的实现里,第一次循环并没有"准备"什么东西留给后面用——后面每一步都是重新算的,跟第一次是否发生过没有任何关系。 更准确的说法是:prefill 是生成开始前必须先做的第一次前向传播,用来算出"prompt 最后一个位置"的预测分布,而不是"预热模型"。