Without a cache, every step runs the whole text again
A model that writes text one token at a time repeats almost all of its work at every step. The KV cache removes that repeated work, and serving systems rely on it to run a model at speed.
This lesson follows one generation: the prompt the cat sat, then on, the and mat, one token per step.
@torch.no_grad()
def generate(model: nn.Module, idx: torch.Tensor, max_new_tokens: int) -> torch.Tensor:
"""idx: (B, T) token ids. Returns (B, T + max_new_tokens)."""
for _ in range(max_new_tokens):
# the whole window, every step
logits, _ = model(idx[:, -model.block_size:])
# keep the last row
next_id = logits[:, -1].argmax(dim=-1, keepdim=True)
idx = torch.cat([idx, next_id], dim=1)
return idx
This is the plain way to generate text. Each step runs every token through every layer, keeps the scores at the last position, and throws the rest away. To write mat, it runs the cat sat on the through every layer again, and all of it comes out exactly as on the step before.
A KV cache keeps the keys and values of the tokens already seen, so each step runs only the newest token.
Step through the generation and watch what each step computes. Then turn the cache off and watch the whole text so far get computed again at every step.
- Scores this step
- 6
- Total, with cache
- 6
- Total, without
- 6
Write runs_no_cache(prompt, new) and runs_cached(prompt, new): how many tokens go through the model to write new tokens after a prompt of prompt tokens, without a cache and with one.