Start by explaining the inefficiency of the greedy decode loop and how KV-cache eliminates redundant computation. Then walk through the necessary code changes: modifying the attention mechanism to use cached keys/values, updating the decode loop to pass and update the cache, and ensuring positional encodings are handled correctly. Finally, describe how to verify equivalence by comparing outputs and intermediate states.
Pro tip: Emphasize that the cache must be updated only with the new token's key/value at each step, and that positional encodings must reflect the absolute position to maintain correctness. Also, mention that you would test with varying sequence lengths and batch sizes to catch subtle bugs.
Review the greedy decode loop and the provided cache class to understand its API (e.g., methods to update and retrieve cached keys/values). Identify where the full sequence is currently passed to attention.
Change the attention function to accept cached keys/values, concatenate them with the new token's keys/values, and compute attention only over the cached plus new tokens. Ensure the cache is updated with the new keys/values.
In the generation loop, initialize the cache, pass it to the model at each step, and update it with the new token's keys/values. Avoid recomputing keys/values for previously processed tokens.
Ensure that positional encodings are applied based on the absolute position of each token, not just the current step. This may require passing the current position index to the model.
Run both implementations on the same inputs and compare outputs token-by-token. Also compare intermediate attention outputs and logits to catch any discrepancies. Test with different sequence lengths and batch sizes.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.