Sub topic 2
The KV Cache and Why Context Length Costs Memory
Assume you know what model parameters, tokens, VRAM, system RAM, and bytes are. This chapter focuses on inference, the process of generating text from an already-loaded model.
The KV cache and context length
A transformer processes each token through attention. For earlier tokens, it stores intermediate key and value tensors. The KV cache is this stored data. During generation, the model reuses it instead of recomputing earlier tokens.
KV cache memory grows with the number of layers, KV heads, head size, context length, and bytes per value:
KV bytes = 2 × layers × KV heads × head size × context × bytes per valueThe factor 2 represents keys and values. An 8,192-token context needs twice as much KV memory as a 4,096-token context. The cache is separate from the model’s weight file, so a model can fit initially and still run out of memory as the conversation grows.
VRAM, system RAM, and unified memory
- VRAM is memory attached to a discrete GPU. It usually provides high bandwidth, but its capacity is fixed.
- System RAM is the computer’s main memory. A CPU can use it directly, and a GPU may access it more slowly through the system bus.
- Unified memory is shared by the CPU and GPU. It avoids copying between separate pools, but CPU and GPU workloads compete for the same bandwidth.
A model may fit in system RAM while being too large for VRAM. That can make generation possible but slower, especially when layers or the KV cache spill across memory tiers.
Checking whether a model fits
Estimate the total requirement as:
- quantised weights
- KV cache at the intended context length
- runtime workspace and temporary buffers
Leave headroom rather than using every available byte. A practical check is:
| Memory item | Grows with |
|---|---|
| Weights | Parameter count and bits per weight |
| KV cache | Context length and model shape |
| Workspace | Runtime, batch size, and prompt processing |
Why memory bandwidth matters
During token generation, the hardware often reads most model weights for each new token. Therefore, a rough upper bound is:
tokens per second ≈ memory bandwidth ÷ model size
This is an upper bound, not a promise. Kernel efficiency, CPU or GPU utilisation, KV-cache traffic, and partial offload reduce the measured speed.
Exercise
Why can doubling the context length make an otherwise working model run out of memory?
Show answer
The KV cache grows approximately linearly with context length, adding memory beyond the model weights.