Lightning-AI / Lightning-AI/litgpt
Refactoring of `GPT.forward` when it comes to `input_pos` and KV cache usage
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 13.7k
- Forks
- 1.5k
- Avg merge
- 15h 37m
- Merged PRs (30d)
- 1
Description
The current GPT.forward in model.py essentially serves two use cases:
- Forward pass for training:
input_pos=None, KV cache not used. Implicitly,input_pos = arange(idx.shape[-1]), and causal masking is used. Could also be used for prefill with prompt in inference. - Inference.
input_posis notNone, KV cache is used. There seem two cases here, eitherinput_pos = arange(idx.shape[-1])(used for prefill), orinput_pos.shape[-1] == 1(generation of single next token, possibly batched).
I am interested in implementing KV cache strategies, such as H2O. In inference, we really only have prefill, and then single-token generation. Inference always works like this:
- Prefill with sequence length T (minimum of prompt size and max cache size)
- Generate token T
- Generate token T+1
- ...
Most KV cache strategies only support this protocol.
My proposal would be to refactor GPT.forward to support two cases only:
- Forward pass for training: With an additional flag, this can be used for prefill, in that this would initialize the KV cache with the K and V vectors obtained as part of the forward, just because
scaled_dot_product_attentionis called - Generate single token:
idx.shape[-1] == 1.input_posis not really needed, it would rather beinput_pos_maxp1. The KV cache tracks the position of the next token, and it would complain if asked to do anything else
This supports everything you have right now, plus it supports advanced KV caches like H2O.
I am happy to do this in a branch in my fork and show you how it would look like.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reading model.py and the current GPT.forward implementation, focusing on how input_pos, causal masking, and the KV cache are handled. Compare the training/prefill and single-token generation paths against the proposed two-case protocol. Done should preserve current behavior while allowing KV cache strategies such as H2O.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- ai, machine-learning
- Issue type
- Refactor
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 30/100