โ† All posts

KV Cache

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 โ†’
KV Cache โ€” Postars