Prove that the cache changes the cost and nothing else
The KV cache is the last part of the round, and it needs its own proof.
with torch.no_grad():
# idx is (B, 12)
full, _ = model(idx)
# prefill
a, caches = model.forward_cached(idx[:, :7])
# one decode step
b, caches = model.forward_cached(idx[:, 7:8], caches)
# a chunk on top
c, caches = model.forward_cached(idx[:, 8:], caches)
assert torch.allclose(full, torch.cat([a, b, c], dim=1), atol=1e-4)
cached = generate(model, prompt, 80)
assert torch.equal(cached, generate_uncached(model, prompt, 80))
The contract is that caching changes the cost and nothing else. So test the model and the loop separately, and keep the old loop as generate_uncached.
| Test | Run | Must match |
|---|---|---|
| the model | one full pass on 12 tokens, against a prefill of 7, a decode step of 1 and a chunk of 4 | the same logits |
| the loop | the old loop and the cached loop, 80 new tokens each | the same tokens |
The first compares a prefill, a decode step and a chunk with one full pass, through the whole model. The atol, the absolute tolerance, has room because float noise grows with the logits: on a trained model the two differed by up to 8e-6.
The second runs both loops from one prompt on a trained model, far enough past block_size that the restart fires many times. On a model trained to memorize a short text, with a 32-token window and 80 new tokens, the cached loop matched the uncached one on every token. With the position offset left out, it went wrong at position 16. It didn't recover until the window filled and the restart re-embedded everything from position 0. Compare every token, not the last few.
You check a cached step against F.scaled_dot_product_attention(..., is_causal=True): one new query on 6 cached keys. What does is_causal=True let the query see?