KV Cache

Serving LLMs is as much a memory problem as a compute problem.
Here is why:
๐ญ. ๐๐๐ ๐ ๐ด๐ฒ๐ป๐ฒ๐ฟ๐ฎ๐๐ฒ ๐ผ๐ป๐ฒ ๐๐ผ๐ธ๐ฒ๐ป ๐ฎ๐ ๐ฎ ๐๐ถ๐บ๐ฒ
An LLM does not produce a full answer in one pass.
It predicts the next token, appends it, then runs again.
So a 500-token response means 500 forward passes through the model.
That is why latency climbs so quickly.
๐ฎ. ๐ง๐ต๐ฒ ๐๐ฉ ๐ฐ๐ฎ๐ฐ๐ต๐ฒ ๐ถ๐ ๐๐ต๐ฒ ๐บ๐ฒ๐บ๐ผ๐ฟ๐ ๐บ๐ผ๐ป๐๐๐ฒ๐ฟ
To generate the next token, the model needs the Key and Value vectors from every previous token.
Those vectors are stored in GPU memory as the KV cache.
On Llama 3 70B, that works out to roughly 320 KB per token in FP16.
So:
- 2,000 tokens is about 640 MB
- 32,000 tokens is about 10 GB
- 128,000 tokens is about 40 GB for one user
That is why long-context serving gets expensive fast.
๐ฏ. ๐๐ฃ๐จ๐ ๐ฎ๐ฟ๐ฒ ๐น๐ถ๐บ๐ถ๐๐ฒ๐ฑ ๐ฏ๐ ๐ฏ๐ฎ๐ป๐ฑ๐๐ถ๐ฑ๐๐ต, ๐ป๐ผ๐ ๐ท๐๐๐ ๐ฐ๐ผ๐บ๐ฝ๐๐๐ฒ
A GPU has different memory layers:
- CPU memory: large, but slow
- HBM / VRAM: fast, but limited
- SRAM: extremely fast, but tiny
During inference, the GPU keeps moving weights and KV cache data from HBM into SRAM so the tensor cores can do the maths.
That means performance is often limited by how fast data can move, not how fast the compute units are.
๐ง๐ต๐ฒ ๐ฟ๐ฒ๐ฎ๐น ๐น๐ฒ๐๐๐ผ๐ป
Most LLM inference optimisations do one of two things:
- move less data
- use GPU memory more efficiently
That is why quantisation helps.
That is why PagedAttention helps.
Originally published on LinkedIn.
Turn your expertise into LinkedIn posts like this one.
Try Postars free โ