Skip to Content
Chapter 11

Serving: Making it fast and cheap

Tomas Reimers 14 minute read

Between “we trained a great model” and “an API that serves a planet” sits systems engineering most engineers never get to see: a shame, because it’s the part of the stack built from ideas you already know: virtual memory, batch schedulers, caches, compression. This chapter reverse-engineers the price-per-million-tokens on the invoice.

The physics from last chapter, restated as the serving problem: decode is memory-bound — the GPU reads ~all active weights to emit each token, using a fraction of a percent of its compute. Every technique below is one of three moves, and they’re the chapter’s arc:

  1. Share the bytes — batch many conversations onto each read of the weights (continuous batching), and stop wasting the memory that limits the batch (PagedAttention, prefix caching).
  2. Shrink the bytes — quantization, and at the limit, distillation: shrink the model itself.
  3. Read the bytes less often — speculative decoding: multiple tokens per weight-read.

Continuous batching: share the bytes

The waste in serving one user is that a 70B model’s 140 GB of weights (70B parameters × 2 bytes each) get read to produce one token. Serve 100 conversations in a single batch, and the same read produces 100 tokens; per-token cost falls ~100× before any cleverness. Throughput providers live and die on batch size (and this is why per-token API prices can sit so far below what a dedicated GPU would cost you).

Before the scheduling trick, pin down the plumbing: a generated token lands in two places, in two forms. The decode loop is GPU-resident: the weights, every conversation’s KV cache, and the step itself all live in HBM (Chapter 10), and the newly sampled token never leaves. It’s appended on-GPU as the next step’s input, and its K/V join the cache. What crosses back over PCIe each step is just the sampled token ID (a few bytes per live request), which the CPU-side engine detokenizes, streams to the user, checks against stop conditions, and feeds to its scheduler. The GPU does the arithmetic; the CPU runs the airport:

usersstreamCPU — serving enginerequest queuescheduler: picks eachstep's batchtokenizer / detokenizerholds no weights, no cache —just bookkeepingprompt token IDs inPCIe1 token ID per requestper step — bytesGPU — HBM + coresweights — residentKV caches — one per requestdecode step: read weightsonce → one new tokenper live requestthe new token never leaves: it becomes thenext step's input; its K/V join the cacheweights and caches never cross the bus — the loop lives on the GPU; the CPU decides who's in it
Anatomy of a serving engine. The decode loop never leaves the GPU: weights and KV caches are resident, and each new token is appended on-GPU as the next step's input. What crosses PCIe per step is one sampled token ID per live request — bytes, not tensors — which the CPU-side engine detokenizes, streams to the user, and feeds to its scheduler to decide who is in the next step's batch. The GPU does the arithmetic; the CPU runs the airport.

The wrinkle is that requests don’t arrive in lockstep: one user’s answer is 10 tokens, another’s is 3,000. Naive batching waits for the longest member to finish — like an elevator that won’t open until every rider’s floor is reached. Continuous batching (also “in-flight batching”) schedules at the granularity of a single token step: finished requests exit the batch and queued ones enter, immediately. It’s a job scheduler where the quantum is one forward pass, and every serving engine ships it:

slot 1slot 2slot 3slot 4token steps →AAAA········BBBBBBBBBBBBCCCCCC······DDD·········
naive batching: four requests enter together, and the batch holds until the longest finishes — 25 of 48 slot-steps do work (52%)
Continuous batching, with the occupancy computed from the drawn requests: naive batching holds all four slots until the longest request finishes (52% of slot-steps do useful work); scheduling at the granularity of a single token step refills each slot the moment it frees (92%). Every empty cell is a full read of the weights that produced nothing.

The tradeoff it navigates is the classic one: throughput vs. latency. Bigger batches amortize better but make everyone wait a bit longer per token. The two numbers on every serving dashboard: TTFT (time to first token) and tokens/sec thereafter. TTFT is queueing plus prefill (Chapter 10), which must finish before the first output token can exist (all input tokens in parallel, so compute-bound and fast, but a 100K-token prompt is still real work). Tokens/sec thereafter is decode, the memory-bound crawl this chapter is about. Batch APIs at half price are this tradeoff sold explicitly: your overnight jobs are the ballast that fills the batches.

Continuous batching also retires a myth: temperature 0 (Chapter 3’s greedy setting) does not make an API deterministic. Your request shares its batch with strangers’ traffic, batch composition changes floating-point reduction orders, and floating-point addition isn’t associative. That last claim, in two lines of 32-bit floats: (224+1)+1=224(2^{24} + 1) + 1 = 2^{24}, because adding 1 to 2242^{24} falls below the format’s resolution and rounds away — twice — while 224+(1+1)=224+22^{24} + (1 + 1) = 2^{24} + 2, which is representable. Same three numbers, different grouping, different answer. Now scale it up: every logit is a sum over thousands of products, and the GPU splits that sum across cores differently depending on how many strangers share your batch — so the result wobbles in its last digits. Run the same prompt alone at 3 a.m. and batched at noon: a logit comes back 12.4327814 instead of 12.4327829, and if the runner-up token sat inside that sliver, the argmax flips. One flipped token enters the context and conditions everything after it (Chapter 3’s compounding) — two “greedy, deterministic” runs, two different answers. Bit-identical reruns are something you engineer at the systems level; no sampling setting provides them.

PagedAttention: stop wasting the memory

Batching’s limiter is memory: every concurrent conversation carries its KV cache (Chapter 5: hundreds of kilobytes per token even with GQA, growing every turn), and the caches compete with the weights for HBM. Early servers allocated each request a contiguous max-length buffer, and that’s catastrophic twice over:

  • Internal fragmentation. A response’s length is unknown when it starts, so a contiguous allocation must reserve for the worst case: a request that will turn out to emit 50 tokens books a 4,096-token slab up front, and the unwritten tail sits idle for the request’s entire life.
  • External fragmentation. Requests finish at unpredictable times, punching holes of unpredictable sizes into memory — and because the next arrival needs its slab contiguous, free memory accumulates in gaps individually too small to use even when they sum to plenty.

The vLLM team measured production servers holding actual KV entries in as little as 20–40% of the memory nominally “used” for caches: a museum-quality reproduction of pre-virtual-memory operating systems.

The fix, from the vLLM paper , is called PagedAttention and it is exactly what its name promises: chop KV caches into fixed-size blocks (~16 tokens), allocate on demand from a shared pool, and translate through a per-request block table. Virtual memory, reinvented for attention: fragmentation vanishes, effective batch size jumps, and (just as page tables enabled shared memory) two requests with the same prefix can map the same physical blocks.

Why the GPU never reaches back into system RAM

“Paging” here borrows the bookkeeping, not the disk. The entire block pool is carved out of HBM at startup (whatever’s left once the weights move in). The “page table” is just a small array of block indices per request. And the attention kernel is written to gather each block through that one extra indirection — pointer-chasing the GPU does itself, inside HBM, at full bandwidth. The CPU-side scheduler (the anatomy figure above) updates the tables as it allocates and frees, but the hot path never crosses PCIe, and there is no page fault: a request that can’t get a block simply waits. (The analogy does extend one level further, deliberately: under real memory pressure, vLLM can swap a preempted request’s blocks out to CPU RAM, or drop them and recompute later. That’s an eviction tier for the queue, never the serving path.)

Real traffic is wildly prefix-heavy:

  • every request from your app shares the same long system prompt;
  • chats carry all their previous turns;
  • agent loops (next chapter) re-send a growing transcript at every step.

Prefix caching (keeping hot prefixes’ KV blocks resident and skipping their prefill entirely) is why providers bill “cached input tokens” at a steep discount, and why you should structure prompts with the stable parts first (so put the variable parts of your prompt at the end).

weights
KV cache
weights 140 GBKV 343.6 GBtotal 484 GB ≈ 7 × H100
Where inference memory actually goes, for a 70B-class GQA model. Drag the sliders: context length and concurrency inflate the KV cache until it dwarfs the weights — and precision shrinks both.

At the frontier, serving splits further: prefill/decode disaggregation runs the compute-bound prefill and memory-bound decode on separate GPU pools, so neither workload’s utilization profile poisons the other’s.

Quantization: shrink the bytes

If decode speed is bytes-of-weights ÷ bandwidth, then halving the bytes doubles the ceiling. Quantization stores numbers in fewer bits — 16-bit floats down to 8-bit or 4-bit integers — by mapping each weight group’s range onto a small grid (plus per-group scale factors, and care for outlier values, which is where methods like GPTQ  and AWQ  earn their citations).

The empirical miracle: weights at 8-bit cost essentially nothing in quality, and 4-bit costs remarkably little. Most weights simply don’t need the precision (that a 70B model works at 4 bits/weight is itself a clue about how diffusely information is stored; Chapter 6 again). The exception proves the rule: heavily over-trained models (Chapter 4’s 8B on 15T tokens) pack more into each weight, and degrade sooner  when you round them. Here is the measured curve:

5.96.26.56.8481216bits per weight (file size ÷ parameter count)perplexity (worse ↑)fp16 baseline — ppl 5.907~4 bits: the knee3.3-bit: +15%3.8-bit: +4%4.7-bit: +0.9%5.5 / 6.3-bit: +0.2% / +0.1%fp16
The quantization quality curve, measured (llama.cpp k-quants, LLaMA-7B, WikiText-2 perplexity; bits per weight computed from actual file sizes). From 16 bits down to ~5, quality is flat to within a quarter percent; ~4.7 bits costs 0.9%; then the knee — 3.8 bits costs 4%, and 3.3 bits costs 15%. Model quality is remarkably indifferent to precision, until just below 4 bits it suddenly isn't.

The knee just below 4 bits is no accident of one codebase. Dettmers & Zettlemoyer  measured the tradeoff across model families and scales and found 4-bit at the optimum. For a fixed memory budget, a bigger model at 4 bits beats a smaller one at 8; below 4 bits, the quality cost finally outruns the size savings. A 70B model at 4 bits is ~35 GB: one GPU instead of two, double the decode ceiling, or a frontier-class model on a MacBook — the entire local-LLM scene is downstream of this one technique.

Quantizing the KV cache pays the same dividend to context length. And there’s a third thing to quantize: the activations flowing through the network. That target matters for a different reason: weight-only quantization helps the memory-bound decode (fewer bytes to move), but prefill is compute-bound, and the arithmetic only gets cheaper if both operands of each multiply shrink — quantize the activations too (fp8) and the tensor cores themselves run at roughly double rate. The costs of all of it are workload-dependent and show up in the tails, so the eval discipline of Chapter 9 applies to your quantized deployment as much as to any model swap.

Speculative decoding: read the bytes less often

The most conceptually delightful trick, from Leviathan et al.  (and Chen et al. ): most tokens are easy — finishing “the United States of” doesn’t need a trillion parameters. But decoding makes the big model pay full price for every token.

So: let a small, fast draft model race ahead and propose several tokens, then have the big model check them all in one forward pass.

Why is checking cheap when generating isn’t? Recall why decode is serial in the first place: token n+1 can’t be computed until token n exists, because token n is its input. But once the draft has written down four candidate tokens, that dependency is gone — the sequence is just text now, and the big model can process existing text the way it processes a prompt or a training batch (Chapter 3’s causal-mask trick): every position at once, one read of the weights. That single pass hands back the big model’s next-token prediction at every position — what it would have said after the context, after the context plus the first draft token, after the first two, and so on — and verification is nothing more than comparing those predictions against the draft’s proposals. The draft model has converted a generation problem (serial, one weight-read per token) into a reading problem (parallel, one weight-read total) — and Chapter 10’s roofline puts those on opposite sides:

…Solar System isdraft (1B): Jupiter✓,✓ which✓ orbits✗target (70B): Jupiter, which is← one passcommitted: Jupiter, which is
a small, fast draft model races ahead and proposes four tokens — cheap, but not to be trusted
Speculative decoding: the draft model proposes, the target model verifies the whole proposal in a single parallel pass (checking is prefill-shaped, generating is decode-shaped), and the agreeing prefix is committed along with the target's own token at the first disagreement. Here, one read of the big weights yields four tokens — arithmetic intensity, raised again.

Accept the longest agreeing prefix — where “agreeing” is probabilistic, not exact-match: each draft token is kept with a probability that depends on how strongly the big model also favors it — and where a token is rejected, the big model’s own prediction takes over. That careful accept/reject rule makes the output distribution provably identical to the big model’s — this is a lossless speedup, pure latency win, typically 2–3×. When the models agree, you’ve paid one weight-read for several tokens: arithmetic intensity, raised again.

Variants abound, in two directions. Self-drafting removes the second model: Medusa-style setups bolt extra prediction heads onto the big model itself — head k learns to predict the token k steps ahead, so one forward pass proposes its own candidates. And n-gram lookahead (prompt lookup) needs no model at all: draft by string-matching against text already in the context — free, and strongest exactly where output quotes input at length, like editing and coding.

Then there’s the radical version of the same instinct: diffusion. Diffusion models, the architecture behind the image generators, work by iterative refinement. Start from pure noise and sculpt it toward a sample over a few dozen denoising steps. Diffusion language models (LLaDA  is the open demonstration) port this to text. Start with a block of, say, 1,000 masked tokens, and at each step let the model fill in and revise every position in parallel, conditioned on the whole current draft — closer to BERT’s cloze objective (Chapter 3’s other lineage) than to GPT’s next-token game, run repeatedly until the block settles. The serving arithmetic is the attraction: an autoregressive model reads its weights 1,000 times to emit 1,000 tokens. A diffusion model reads them once per refinement pass — a few dozen times total — and every pass is a big, parallel, prefill-shaped operation on the compute-bound side of Chapter 10’s roofline. Gemini Diffusion  demos low-thousands of tokens per second on exactly this math. The open questions are just as real:

  • quality at frontier scale is unproven;
  • each refinement re-reads the whole block, so the KV cache’s append-only economics don’t transfer;
  • and text, unlike pixels, is consumed left-to-right — by readers streaming an answer and by agents acting mid-generation.

The honest summary: a bet on breaking the one-token-at-a-time bottleneck entirely rather than speculating past it. Watch that space; don’t reorganize around it.

Distillation: shrink the model itself

The endgame move is older than everything above (Hinton et al., 2015 ). Distillation: use a big teacher model to train a small student — and mechanically, it’s Chapter 1’s training loop with one substitution. Ordinary training grades the student against a one-hot target: the next token is “mat”; every alternative is equally, maximally wrong. Distillation grades it against the teacher’s entire output distribution at that position — mat 60%, sofa 25%, rug 10%, carburetor ~0 — with a loss that asks the student’s distribution to match the teacher’s. (The same KL divergence that leashed RLHF in Chapter 8, now promoted from guardrail to objective). Hinton called what this transfers dark knowledge: the teacher’s carefully ranked wrong answers encode how concepts relate, so every single token delivers a vocabulary-wide training signal instead of one bit of right/wrong — which is why a student can reach a quality its size could never have reached from raw text alone.

In practice the commonest form is cruder, because you usually can’t get a teacher’s distributions (APIs return sampled tokens, not logits): generate millions of teacher transcripts and run SFT on them (Chapter 8), with the teacher as the annotator: distilling through samples rather than soft targets. The mini/flash/lite tier of every model family is some blend of distillation and Chapter 4’s over-training; DeepSeek R1’s distilled small models are how reasoning reached laptops within weeks of that model’s release.

Distillation is why “capability lag” keeps shrinking: whatever the frontier does expensively this quarter, a distilled model does cheaply next quarter. It’s also, notoriously, how competitors bootstrap from each other’s APIs — every lab’s terms of service forbid it, and every lab is suspected of it.

The stack, assembled

Trace a request through everything at once:

requestsystem promptquestionprefix cacheKV already hot —no prefillprefill poolsuffix only ·compute-bounddecode poolcontinuous batch ·4-bit weights ·draft +4 / readtokens stream outshared prefix blocksthis requestother conversationsPagedAttention block pool — one shared physical HBM
a request arrives: a long system prompt every request shares, plus a short novel question
One request, end to end. The shared system prompt costs nothing — its KV blocks are already resident (prefix cache). Only the novel suffix prefills. Decode then shares every 4-bit weight-read with the whole continuous batch while a draft model turns each read into several tokens — and PagedAttention maps everyone's logical tokens onto one shared pool of physical blocks. None of it knows anything about language.

None of these techniques knows anything about language. It’s caches, pages, schedulers, and compression — your field, aimed at one workload. The invoice line “per million tokens” is the price of bytes moved through HBM, divided by how cleverly they’re shared.

After everything, notice what the serving stack actually delivers: a probability distribution, not text — fresh from the softmax, a hundred thousand candidates wide, every few milliseconds. Chapter 3 taught you the knobs that turn it into tokens. What’s left is everything a product wraps around that loop — the scratch space, the tools, the retrieval, the agent — and the uncomfortable fact that the wrapper, not the model, is the part you’ll actually build. One chapter left.

Further reading

Last updated on