AI ENGINEERING · LLMS IN PRODUCTION · INFRASTRUCTURE · 33 OF 35

LLM Inference Explained: KV Cache, Batching, Quantization

What happens on the GPU when a model answers: compute-bound prefill versus memory-bound decode, the KV cache with a worked memory estimate, batching, continuous batching and paged attention, quantization from 16 to 4 bits for a 7 billion parameter model, speculative decoding, tensor parallelism, throughput versus latency, and self-hosting versus an API.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
1 / 19

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • Prefill is compute bound
  • decode is memory bound
  • KV cache
  • continuous batching
  • paging
  • quantize
  • speculate
  • split

Notes

The idea

Here is the idea. Every request runs in two phases. First, prefill. The model reads the whole prompt in one big parallel pass and produces the first output token. That sets your time to first token. Then decode. The model generates one token, appends it, and runs again, over and over until it stops. That sets how fast text streams. The two phases stress the hardware very differently, and most serving tricks target one of them.

Two phases
  • prefill read the whole prompt in one big parallel pass sets time to first token
  • decode generate one token, append it, run again, repeat sets tokens per second

Prefill

Prefill is the efficient phase. Every prompt token is known up front, so all of them pass through each layer together as one large matrix multiplication. The weights are read from memory once and used for thousands of tokens of work. That keeps the GPU's math units busy, so we call prefill compute bound. A long prompt still takes longer, which is why a huge document makes the first token slow.

Why prefill is fast
  • all prompt tokens are known
  • up front, so they go through
  • each layer together as one big matrix multiply
  • one read of the weights, thousands of tokens of work → GPU math units are busy
  • cost grows with prompt length

Decode

Decode is the slow phase. To produce one token for one user, the GPU must stream every weight through its chips. For a seven billion parameter model at sixteen bits, that is fourteen gigabytes per token. At about two terabytes per second, that takes around seven milliseconds, so at most about one hundred and forty tokens per second. The math units sit mostly idle, waiting on memory. Decode is memory bandwidth bound.

Worked: one user, 7B model
weights at 16-bit      ~14 GB
GPU memory bandwidth   ~2 TB/s

per token: read 14 GB
  14 GB / 2 TB/s     ≈ 7 ms
  1 s / 7 ms         ≈ 140 tok/s

that is a ceiling for one
stream; the math units sit
mostly idle, waiting on memory

The KV cache

Attention lets each new token look back at every earlier token, using that token's key and value vectors in every layer. Without a cache, each step would recompute those vectors for the whole conversation. So we compute them once, store them, and reuse them. That store is the KV cache. Prefill fills it, and each decode step appends one token. It trades compute for memory, and the memory bill is large.

What the KV cache holds
  • attention needs, for every past token, its key and value vectors in every layer
  • without a cache: recompute
  • them all on every new token
  • with a cache: compute once, store, reuse on every step
  • trade: compute saved, GPU memory spent

KV cache memory

Let us size it for a seven billion parameter model with thirty two layers and a width of four thousand and ninety six. Per token, we store a key and a value, in each layer, four thousand and ninety six numbers each, at two bytes. That is about half a megabyte per token. An eight thousand token chat needs about four gigabytes. Thirty two thousand tokens needs sixteen, more than the weights. Grouped query attention shares keys and values across heads, cutting this about four times.

Worked: 7B, 32 layers
per token = 2 (K and V)
  × 32 layers × 4,096 dims
  × 2 bytes      ≈ 0.5 MB

8,000-token chat   ≈ 4 GB
32,000-token chat  ≈ 16 GB
  > the 14 GB of weights!

grouped-query attention
(8 KV heads, not 32) → ÷4
32,000 tokens      ≈ 4 GB

Batching

Here is the key to cheap serving. Read the weights once and do the work for many users in the same step. With thirty two users in a batch, a step takes a little longer, maybe twelve milliseconds instead of seven, because each user's KV cache must be read too. But it produces thirty two tokens. Each user gets about eighty five tokens per second, and total throughput rises about twenty times. The limit becomes KV cache memory.

Worked: batch 1 vs batch 32
batch 1
  ~7 ms per step, 1 token
  ≈ 140 tok/s total

batch 32
  weights read once, + each
  user's KV: ~12 ms per step
  32 tokens per step
  ≈ 85 tok/s each
  ≈ 2,700 tok/s total (~20×)

Continuous batching

Simple batching starts eight requests together and waits for all of them to finish. If one reply is five hundred tokens and the rest are twenty, most slots sit idle while new users wait. Continuous batching schedules at every single step instead. The moment a request finishes, it leaves, and a waiting request takes its slot on the next step. The GPU stays full, and throughput often rises several times.

Static vs continuous
  • static batching start 8 requests together wait for the longest reply (500 tokens) while the 20-token ones sit done
  • continuous batching schedule every step: a finished request leaves, a queued one takes its slot

Paged attention

Paged attention fixes how the KV cache is stored. The naive way reserves one big slab per request, sized for the longest possible reply, and most of it is never used. Paged attention borrows the idea of virtual memory. The cache lives in small fixed blocks of around sixteen tokens, handed out as a reply grows, with a table mapping each request to its blocks. Waste drops to a partial block, so far more users fit, and requests can share blocks for a common prompt prefix.

Paged KV cache
  • naive: reserve one big contiguous slab per request for its max length, mostly unused → few users fit
  • paged: fixed blocks of ~16 tokens, allocated as the reply grows; a block table maps request → blocks
  • bonus: share prefix blocks

Quantization

Quantization stores each weight in fewer bits. At sixteen bits a weight takes two bytes, so seven billion parameters need about fourteen gigabytes. At eight bits, seven gigabytes. At four bits, half a byte each, about three and a half gigabytes, plus a little for scale factors. A seventy billion model drops from one hundred and forty gigabytes to thirty five. And because decode is limited by bytes read, fewer bytes also means faster tokens.

Worked: 7B parameters
bits   bytes/param   weights
16     2             ~14 GB
8      1             ~7 GB
4      0.5           ~3.5 GB
         (+ a little for scales)

70B at 16-bit ≈ 140 GB
70B at 4-bit  ≈ 35 GB
  → fits on one 80 GB GPU
decode reads fewer bytes
  → more tokens per second

Quantization cost

Fewer bits means rounding, and rounding loses information. Eight bit weights are usually within the noise of your evals. Four bits usually costs a little quality, and more on small models and on hard tasks like maths, code and long reasoning. Good methods round in small groups, each with its own scale, and calibrate on sample data. You can quantize the KV cache too. Either way, never ship a quantized model without running your eval set.

What you give up
  • 8-bit weights: usually within eval noise
  • 4-bit weights: small drop, bigger on small models, maths, code, long reasoning
  • good methods calibrate on sample data, group weights
  • with their own scales
  • rule: run your evals first

Speculative decoding

Speculative decoding attacks the one token per step limit. A small draft model guesses the next four tokens. The big model then checks all four in a single pass, which costs about the same as one normal step, because checking known tokens works like a tiny prefill. It keeps the guesses it agrees with, plus one token of its own. The output is exactly what the big model would have written, often two to three times faster.

Draft, then verify
  • 1 small draft model writes 4 tokens quickly
  • 2 big model scores all 4 in one pass, like a mini prefill
  • 3 keep the matching prefix, plus one token of its own
  • output = what the big model
  • would have written anyway
  • often ~2-3× faster decode

Tensor parallelism

Some models do not fit on one GPU at all. Seventy billion parameters at sixteen bits is one hundred and forty gigabytes. Tensor parallelism splits every weight matrix into slices across, say, four GPUs. Each holds a quarter of the weights, computes its slice, and the GPUs combine results after every layer. That chatter needs very fast links, so it stays inside one server. Across servers, you split by layers instead, called pipeline parallelism.

70B at 16-bit
  • 140 GB of weights, 80 GB GPU
  • tensor parallel over 4 GPUs each holds a quarter of every weight matrix, ~35 GB each computes its slice, then they combine results after every layer
  • needs fast GPU-to-GPU links
  • across servers: split layers

Throughput vs latency

Every server sits on a curve. Bigger batches give more total tokens per second and a lower cost per token. But each user's stream slows, new requests queue longer, and a big prefill can stall everyone decoding. Chunked prefill helps by mixing slices of prompt work into decode steps. In practice, set targets for time to first token and tokens per second at the ninety fifth percentile, then run the biggest batch that still meets them.

Pick a point on the curve
  • bigger batch → + total tokens/s, lower cost − slower stream per user − new prompts queue, and prefill stalls decoders
  • chat: smaller batches
  • offline jobs: huge batches
  • run the biggest batch that still meets your p95 SLO

Self-host or API

Should you run your own open weight model? With an API you pay per token, nothing when idle, and someone else runs it. Self hosting means paying for GPU hours whether they are busy or not. At ten percent utilisation, each token costs about ten times what it would at full load. You also own the engine, upgrades, on call, and autoscaling that takes minutes to load weights. You win data control, a pinned version and your own fine tunes.

Self-host an open model?
  • API: pay per token, nothing when idle, no ops
  • self-host: pay per GPU hour, busy or idle; at 10% busy each token costs ~10× more ops: engine, upgrades, on-call, minutes to load weights
  • wins: data stays inside, pinned version, own fine-tunes

Common mistakes

A few classic mistakes. Sizing GPU memory for the weights alone, then running out of KV cache on the first busy afternoon. Benchmarking with one user and assuming it holds at fifty. Watching average latency instead of ninety fifth percentile time to first token. Shipping a four bit model because it fit, without checking quality. And self hosting traffic that is spiky and small, where idle GPUs eat any savings.

Avoid these
  • sizing memory for weights only; KV cache runs out under real load
  • benchmarking one user and assuming it scales
  • watching average latency, not p95 time-to-first-token
  • 4-bit without evals
  • self-hosting spiky, low traffic

Numbers worth knowing

Numbers worth knowing. Sixteen bit weights take two bytes per parameter, so seven billion parameters is about fourteen gigabytes, and seventy billion is about one hundred and forty. Four bits cuts that by four. The KV cache costs a tenth of a megabyte to one megabyte per token at that size. A single user typically streams thirty to one hundred and fifty tokens per second. Batching often multiplies throughput ten times or more.

Ballpark numbers
16-bit weights   2 bytes per param
7B model         ~14 GB (4-bit ~3.5)
70B model        ~140 GB (4-bit ~35)
KV per token     ~0.1-1 MB (7B class)
GPU memory       ~24 GB desk, 80+ DC
bandwidth        ~1-8 TB/s
decode per user  ~30-150 tok/s
batching gain    often 10×+ total
speculative      often ~2-3× decode

Say it like this

How to say it. Decode is memory bandwidth bound, so we batch many users per step. The engine uses continuous batching and a paged KV cache. We size memory as the weights, plus KV cache per token times the number of live tokens across all users. Weights are eight bit, checked on our evals. We run the biggest batch that still meets our ninety fifth percentile time to first token. That shows you know where time and memory go.

In the interview
  • "Decode is memory-bandwidth bound, so we batch. We use continuous batching with a paged KV cache. Memory = weights + KV per token × live tokens. 8-bit weights, checked on evals. We run the biggest batch that meets p95 time-to-first-token."

Interview questions

Q1What is the difference between prefill and decode?

Prefill processes the whole prompt in one parallel pass and is compute bound; it determines time to first token. Decode generates one token per forward pass and is memory-bandwidth bound, because every step rereads all the weights; it determines tokens per second.

Q2What is the KV cache and why does it matter?

It stores the key and value vectors of every past token in every layer so they are not recomputed at each decode step. It saves a lot of compute but grows linearly with context length and batch size, and is often what limits how many users a GPU can serve.

Q3Estimate the KV cache for a 7B model with 32 layers and width 4,096.

Per token: 2 (key and value) × 32 layers × 4,096 × 2 bytes ≈ 0.5 MB at 16-bit. An 8,000-token conversation needs about 4 GB; grouped-query attention with 8 KV heads instead of 32 cuts that about four times.

Q4Why does batching raise throughput, and what is continuous batching?

Decode is limited by reading weights, so serving many users in one step reads the weights once for all of them and total tokens per second rises many times. Continuous batching schedules at every step: a finished request leaves at once and a queued one takes its slot, so the GPU never waits for the longest reply.

Q5What does paged attention solve?

Memory waste in the KV cache. Instead of reserving one contiguous slab per request for its maximum length, the cache is split into small fixed-size blocks allocated on demand and tracked by a block table, so more requests fit and common prefixes can share blocks.

Q6How much memory does quantization save for a 7B model, and what does it cost?

About 14 GB at 16-bit, 7 GB at 8-bit and 3.5 GB at 4-bit, and decode gets faster because fewer bytes are read. 8-bit is usually near lossless; 4-bit loses a little quality, more on small models and hard reasoning, so it must be checked with evals.

Q7How does speculative decoding work, and does it change the output?

A small draft model proposes several tokens, and the large model verifies them all in one forward pass, keeping the agreed prefix plus one token of its own. With the correct acceptance rule the output matches the large model, and decode is often 2-3 times faster.

Q8When would you self-host an open-weight model instead of using an API?

When traffic is steady enough to keep GPUs highly utilised, when data must stay in your own network, or when you need a pinned version or your own fine-tune. Otherwise an API is usually cheaper and avoids the operational burden.