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.
- 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.
- 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.
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.
- 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.
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.
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 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.
- 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.
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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
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.
- "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."