18/26
Part 4 of 4 · Prefill, decode and memoryLearn and do
Both phases are one loop
The two phases don't need two code paths.
class Block(nn.Module):
def forward(
self, x: torch.Tensor, cache: tuple[torch.Tensor, torch.Tensor] | None = None
) -> tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor]]:
"""x: (B, T_new, C). Returns the output and the grown cache."""
a, cache = self.attn(self.ln1(x), cache)
x = x + a
return x + self.mlp(self.ln2(x)), cache
@torch.no_grad()
def generate(model: nn.Module, idx: torch.Tensor, max_new_tokens: int) -> torch.Tensor:
"""idx: (B, T) prompt ids. Returns (B, T + max_new_tokens)."""
caches = [None] * len(model.blocks)
# the first pass is prefill: the whole prompt
x, past = idx, 0
for _ in range(max_new_tokens):
T = x.size(1)
h = model.embed(x, past)
for i, block in enumerate(model.blocks):
h, caches[i] = block(h, caches[i])
# every later pass: one token
x = model.lm_head(model.ln_f(h[:, -1:])).argmax(dim=-1)
idx = torch.cat([idx, x], dim=1)
past += T
return idx
model.embed(x, past) adds each token's row of tok_emb to the row of pos_emb for the position that token sits at. The first pass feeds the prompt, and every later pass feeds the one token just picked. Read the argmax line from the inside out:
| Piece | Shape | What it is |
|---|---|---|
h[:, -1:] | (B, 1, C) | the last position only |
ln_f, lm_head | (B, 1, V) | a score for every token |
argmax(dim=-1) | (B, 1) | the top token's id: the next input |
Picking the top-scoring token is greedy decoding. That (B, 1) tensor of ids is the next pass's whole input, so from the second pass on, T is 1.
Pass 3 feeds the, after the cat sat on. Which row of the position table does it read?
Pick an answer above to see the rest
Step 2 crops to cat sat on the. Which position is cat at now?
Pick an answer above to see the rest