Original paper: https://arxiv.org/pdf/2309.06180
Motivation:
- KV cache uses most of the GPU memory space
- Batches of variable sequence length queries
- But fixed sized individual chunks of max sequence length allocated for each batch
- (Single token: 2 (K and V) x 2 (bf16) x number of layers x model size) x maximum output size allowed
- Cache is fragmented:
- Internal fragmentation due to difference between actual and maximum sequence length
- External fragmentation due to gaps between caches
- Cache is not shared across batches
- Beam search or parallel sampling do multiple outputs
Other solutions:
- GQA
- Use same head for multiple queries
- Lossy
- Reduced precision fp8/fp4
Paged attention vLLM:
- Divide KV cache into multiple blocks, each holding a fixed number of tokens
- No internal fragmentation as number of blocks increase with sequence iterations
- No external fragmentation as all block sizes are same
Block size:
- Too small means L2 thrash, poor GPU utilization
- Too large means fragmentation, less sharing
Prompt Phase:
- Generates the first token x_n+1 from x_1 to x_n
- Also computes and stores k_1 to k_n and v_1 to v_n in page table
Generation Phase:
- Sequence length 1
- All GEMM become GEMV
- One new key and value generated
- Stops when maximum length reached or <eos> token generated
Parallel sampling:
- Sharing happens for prompt phase
- Keeps a reference count for each block
Shared Prefix:
- More context added on top of the prompt
- Prompt engineering to achieve specific task
Beam Search:
- Keep top K choices of generated outputs
- Sharing of KV now has gone beyond the initial prompt
- No full copies needed for new candidates
