Inference & Self-Hosting
vLLM internals, quantization, speculative decoding and GPU economics.
Section 1.4 gave the rule for when self-hosting open-weight models makes sense, and section 28.8 the arithmetic of utilization. This chapter is about what happens inside the server once you have decided: why generating tokens is limited by memory and not by arithmetic, how serving engines pack many conversations onto one GPU, and which techniques, from quantization to speculative decoding, buy speed and at what price.
The experiments are computations from published hardware specifications, an H100-class GPU serving an 8-billion-parameter model shaped like Llama 3.1 8B, and a simulation of two batching policies. The numbers are upper bounds of the kind an engineer works out before buying hardware; real engines reach a good fraction of them, not all.
29.1Why decoding is memory-bound
Every new token reads every weight, so batching is nearly free throughput.
Generating one token means running the whole network once (section 2.7). For an 8-billion-parameter model in 16-bit precision, that is 16 GB of weights read from the GPU’s memory for a few billion multiply-adds per sequence. An H100-class GPU reads memory at about 3.35 TB/s and computes at nearly 1,000 trillion 16-bit operations a second. Reading the weights takes about 5 ms; the arithmetic for one sequence takes a few microseconds. The chip spends almost all of its time waiting for memory.
The way out is to do more work per read. If 64 conversations each need their next token, the weights are read once and used 64 times. Each conversation’s own context, its KV cache (section 29.2), still has to be read, so the gain is not unlimited.
- 16-bit weights
- 8-bit
- 4-bit
One conversation alone gets about 206 tokens a second, and that is all the GPU produces. With 128 conversations at 2,000 tokens of context each, the GPU produces about 8,650 tokens a second in total, 42 times as much, while each conversation slows to about 68 tokens a second, still faster than anyone reads. Smaller weights help most when batches are small, because there the weights are most of what is read. At the illustrative rental price of $3 an hour, that difference is the whole economics of self-hosting: about $4 per million output tokens at a batch of one, about 10 cents at 128.
Common take“A faster GPU means faster responses.”
Sharper take“Decoding is limited by memory bandwidth, not arithmetic. The lever is batch size: the same GPU produced 42 times more tokens serving 128 conversations than one, and the cost per token fell by the same factor.”
29.2The KV cache sets concurrency
Memory left after the weights decides how many conversations fit.
Each token of context keeps a key and a value vector in every layer, so that later tokens can attend to it without recomputing it. For the 8B model, with 32 layers and 8 key-value heads of dimension 128, that is 128 KiB per token at 16-bit. An 80 GB GPU holding 16 GB of weights, with some room for the runtime, has about 60 GB left for the cache.
| Each conversation’s context | Conversations that fit |
|---|---|
| 4,000 tokens, allocated as used | 114 |
| Space reserved for 32,000 tokens, whatever is used | 14 |
| 128,000 tokens | 3 |
The middle row is how early serving systems behaved: reserving contiguous memory for the longest possible output wasted most of it. The 2023 vLLM paper by Woosuk Kwon and colleagues measured 60 to 80% of cache memory wasted in existing systems, and introduced PagedAttention, which stores the cache in small fixed-size blocks allocated as a conversation grows, like pages of virtual memory. Waste fell to a few percent, and throughput rose two to four times, simply because more conversations fit.
The cache can also be made smaller. Grouped-query attention (section 5.7) shares keys and values across query heads, which is why this model needs 8 key-value heads rather than 32. Quantizing the cache to 8 bits halves it again, at a small cost in accuracy that grows with context length. Long contexts are expensive to serve for this reason: a 128,000-token conversation occupies the memory of thirty-two 4,000-token ones.
Common take“The model fits on one GPU, so we can serve it on one GPU.”
Sharper take“The weights fit. What matters is the memory left for the cache: at 128 KiB a token, it decides how many conversations run at once, and so the cost per token. Long contexts eat it fastest.”
29.3Continuous batching
Refill a slot the moment a conversation finishes.
Requests finish at different times, because outputs have different lengths. A server that collects a batch, runs it until every request has finished, and only then starts the next, leaves slots idle while it waits for the longest answer. Continuous batching schedules at the level of single steps: when a request finishes, a waiting one takes its slot at the next step.
I simulated both with 32 slots and 4,000 requests whose output lengths vary as real ones do, averaging 370 tokens with a long tail.
| Policy | Slots doing useful work | Steps to finish all requests |
|---|---|---|
| Fixed batches, each running until its longest request ends | 21% | 220,765 |
| Continuous batching | 98% | 47,228 |
The same hardware finished the same work 4.7 times sooner. Modern engines add two refinements. Chunked prefill splits the reading of a long new prompt into pieces interleaved with other conversations’ decoding steps, so one long document does not freeze everyone’s output. And when memory runs short, the scheduler pauses some conversations, either swapping their cache out or discarding it to recompute later, instead of failing.
Streaming and batching are not in tension. A continuously batched server streams each conversation’s tokens back as they are produced; batching is how the fleet stays busy, streaming is how each user sees progress.
Common take“We batch requests in groups of 32 to use the GPU well.”
Sharper take“Fixed groups wait for their longest answer; in simulation four-fifths of the slots sat idle. Continuous batching refills each slot as it frees, and finished the same work almost five times sooner.”
29.4Quantization
Fewer bits per weight mean less to read; measure what it costs on your task.
Because decoding is limited by reading weights, storing them in fewer bits speeds it up almost proportionally, and frees memory for the cache. Section 17.4 measured the quality cost of quantizing a small model; production formats are more careful about where the error goes.
| Format | What is quantized | Typical use |
|---|---|---|
| 8-bit floating point (FP8) | Weights and often activations, with scaling factors | The common default on H100-class and newer GPUs; quality usually close to 16-bit |
| 4-bit integer, weights only (GPTQ, AWQ) | Weights, using calibration data to protect the most important ones | Fitting larger models on fewer GPUs; strongest gain at small batch sizes |
| 4-bit floating point (NVFP4, MXFP4) | Weights and activations in small blocks with shared scales | Blackwell-generation GPUs, and some models released in this format |
| GGUF “k-quants” for llama.cpp | Weights, mixed 2 to 8 bits by layer | Laptops, CPUs and single consumer GPUs |
| KV-cache quantization | Cached keys and values, usually 8-bit | More conversations or longer contexts in the same memory |
Benchmarks of quantized models usually look reassuring, and the losses that matter often hide in particular slices: long contexts, arithmetic, code, less common languages, long chains of reasoning. Smaller models lose more than larger ones at the same bit width. Treat quantization as a model change: run the test set slice by slice (section 23.4) against the full-precision model before switching.
Common take“4-bit models are basically as good as the original.”
Sharper take“On averages, often. I run our test set by slice first, because the losses tend to sit in long contexts, numbers and rarer languages, and those may be exactly our users.”
29.5Speculative decoding
Guess several tokens cheaply, check them all in one pass.
Because a decoding step is dominated by reading weights, checking several proposed tokens in one pass costs little more than generating one. Speculative decoding exploits this. A cheap drafter proposes the next few tokens; the large model scores them all in a single pass and keeps the longest prefix it agrees with, plus one token of its own. With the acceptance rule introduced in 2023 by Yaniv Leviathan and colleagues, and independently by Charlie Chen and colleagues, the output has exactly the distribution the large model alone would produce. It is faster, not different.
The drafter can be a small model from the same family, extra prediction heads trained onto the large model (Medusa, EAGLE, and the multi-token prediction heads some models ship with), or simply text copied from the prompt, which works well for editing and extraction. The gain depends on how often drafts are accepted.
- 2 drafted tokens
- 4
- 8
With four drafted tokens and a drafter costing a twentieth of a large-model step, the expected speedup is about 1.9 times at 60% acceptance and 2.8 times at 80%. Longer drafts pay only when acceptance is high. The gains are largest at small batch sizes, where the GPU has spare arithmetic; at large batch sizes the GPU is already busier, and the benefit shrinks. Measure acceptance on your own traffic: code and structured output accept well, open-ended creative text less so.
Common take“Speculative decoding trades quality for speed.”
Sharper take“With the standard acceptance rule the output distribution is exactly the large model’s. The speedup depends on how often the drafts are accepted on our traffic, so I measure that, and expect less at high batch sizes.”
29.6Prefix caching
The provider’s prompt cache, run by you.
Section 28.4 treated prompt caching as a priced feature. On your own server it is a scheduling decision. Engines keep the KV cache of recent prompt prefixes, keyed by a hash of each block of tokens, and when a new request starts with the same blocks, they skip reading those tokens again. vLLM calls this automatic prefix caching; SGLang organizes cached prefixes in a tree, which it calls RadixAttention, so that conversations sharing a system prompt and then diverging still share what they can.
The design rules are those of section 28.4: fixed content first, changing content last. Two more apply when you run the servers. Cached prefixes compete with live conversations for the same memory, so the engine evicts the least recently used. And with several replicas, a request reuses a prefix only if it lands on the replica that holds it, so a router that sends requests with the same prefix to the same replica, which is called cache-aware routing, can raise the hit rate a great deal.
Common take“We turned on prefix caching, but the hit rate is low.”
Sharper take“With eight replicas behind a random load balancer, each prefix is warm on one replica in eight. I route by prefix, keep changing content at the end, and watch evictions when memory is tight.”
29.7Splitting a model across GPUs
Use the fewest GPUs that fit, then add copies.
| Split | How | When |
|---|---|---|
| Tensor parallelism | Each layer’s matrices are divided across GPUs, which exchange partial results at every layer | Within one server, over its fast links; the usual way to fit a model too large for one GPU |
| Pipeline parallelism | Consecutive groups of layers on different GPUs | Across servers, where links are slower; adds latency per token |
| Expert parallelism | The experts of a mixture-of-experts model on different GPUs (sections 2.8 and 5.8) | Large mixture-of-experts models; needs balanced routing to experts |
| Data parallelism | Complete copies of the model, each serving its own requests | Scaling throughput once one copy fits |
Splitting costs communication. The rule of thumb is to use the smallest group of GPUs that holds the weights with room for a useful cache, and to scale throughput by adding copies. A 70B model in 16-bit needs 140 GB for weights alone, so two 80 GB GPUs hold the weights but leave little cache; four leave room for many conversations; in 8-bit, two may do. The arithmetic of sections 29.1 and 29.2, done for each option, decides.
Common take“More GPUs per model means faster serving.”
Sharper take“Past the point where the weights and a healthy cache fit, more GPUs per copy mostly add communication. I use the smallest group that fits and scale by adding copies.”
29.8Separating prefill from decode
Reading prompts and writing tokens want different machines.
Prefill, reading the prompt, processes thousands of tokens at once and is limited by arithmetic. Decode, writing the answer, processes one token per conversation per step and is limited by memory. On one GPU they interfere: a long prompt arriving stalls everyone’s decoding, and decoding wastes arithmetic the prefill could use. Chunked prefill (section 29.3) softens this.
Disaggregation separates them: one pool of GPUs does prefill, another does decode, and the KV cache produced by prefill is transferred over fast links to a decode GPU. Studies in 2024, such as DistServe and Splitwise, showed large gains in throughput at a given latency target, and serving frameworks such as NVIDIA Dynamo, llm-d and SGLang now support it. Each pool can be sized and tuned for its own bottleneck, and time to first token and generation speed can be managed separately.
It pays at scale and with long prompts, as in retrieval and agents. For a few GPUs serving moderate traffic, the transfer and the extra operational parts usually cost more than they save.
Common take“Disaggregated serving is the modern architecture, so we should use it.”
Sharper take“It pays when long prompts and steady volume make prefill and decode fight over the same GPUs. On a handful of GPUs, chunked prefill gets most of the benefit with none of the transfer.”
29.9Choosing an engine and a GPU
Most of the choice follows from the arithmetic above.
| Engine | Strengths | Typical fit |
|---|---|---|
| vLLM | PagedAttention, continuous batching, broad model and hardware support, large community | The default for serving open models on GPUs |
| SGLang | Tree-structured prefix caching, a fast scheduler, strong on structured output and agent workloads | Workloads with much shared prefix, and large mixture-of-experts deployments |
| TensorRT-LLM | NVIDIA’s compiled engines, often the highest throughput on NVIDIA hardware | Teams that can invest in building and tuning engines per model |
| llama.cpp, and Ollama on top of it | Runs quantized models on CPUs, Apple silicon and consumer GPUs | Local development, laptops, edge devices, small single-user deployments |
For the GPU, three properties matter in order. Memory capacity: weights plus enough cache for the concurrency you need (section 29.2). Memory bandwidth: tokens per second per conversation (section 29.1). Supported formats: FP8 needs H100-class hardware or newer, and FP4 the Blackwell generation. Then compute the cost per million tokens at the batch size your traffic will actually sustain, not the vendor’s best case.
| Conversations in the batch | 1 | 8 | 32 | 128 |
|---|---|---|---|---|
| Output cost per million tokens, 8B model, 16-bit, at $3 per GPU-hour (upper bound) | $4.05 | $0.56 | $0.19 | $0.10 |
A forty-fold range from one variable. If your traffic cannot keep batches full, the hardware will be expensive per token, whatever its price per hour (section 28.8).
Common take“The newest GPU will give us the lowest cost per token.”
Sharper take“Only at the batch sizes our traffic sustains. I size memory for the concurrency we need, check bandwidth for per-user speed, and compute cost per token at realistic utilization before comparing price tags.”
29.10Hosted open models
The middle option: open weights, someone else’s servers.
Between a closed model’s API and your own GPUs sits a third option. Inference providers, such as Together, Fireworks, DeepInfra, Groq and Cerebras, and the model catalogs of the large clouds, serve open-weight models per token or on dedicated capacity. They run the engines of this chapter at scale, often with custom hardware or kernels, and keep batches full by pooling many customers’ traffic.
| Closed model API | Hosted open model | Self-hosted | |
|---|---|---|---|
| Capability ceiling | The frontier | The best open models | The best open models |
| Control of the model | None; it can change (section 1.6) | Pinned weights; your own fine-tunes often supported | Complete |
| Where data goes | The provider | The inference provider | Your infrastructure only |
| Operations | None | None to little | All of this chapter |
| Cost at low or bursty volume | Per token | Per token | Idle hardware |
| Cost at high steady volume | Per token | Per token or dedicated | Lowest, if utilization stays high |
For most teams that want open weights, for cost, control or a fine-tuned model, a hosted provider is the right first step. Self-hosting earns its operational cost when data cannot leave your infrastructure, or when steady volume keeps batches full enough that the arithmetic of section 29.9 beats the provider’s price.
Common take“We want to use open models, so we need our own GPUs.”
Sharper take“Open weights don’t require our own servers. A hosted provider gives us pinned weights and fine-tunes without the operations. We self-host only if data must stay in-house or our volume keeps batches full.”
Key takeaways
- Decoding reads every weight for every token, so it is limited by memory bandwidth. Batching reuses each read: in the computation, 128 conversations got 42 times the tokens of one.
- The KV cache, 128 KiB per token for an 8B model, decides how many conversations fit. PagedAttention stopped the waste; long contexts still consume it fastest.
- Continuous batching refills slots as requests finish. In simulation it kept 98% of slots busy against 21% for fixed batches.
- Quantization speeds decoding and frees memory. Its losses hide in slices; test by slice before switching.
- Speculative decoding drafts tokens cheaply and verifies them in one pass, with the same output distribution. Expect about 2 to 3 times at high acceptance and small batches.
- Prefix caching on your own servers needs cache-aware routing across replicas.
- Use the fewest GPUs that hold the weights and a healthy cache, then add copies. Separate prefill from decode only at scale.
- Choose GPUs by memory, bandwidth and formats, and price them per token at the batch size you can sustain: about $4 per million at a batch of one, 10 cents at 128, in the computation.
- Hosted open-model providers give open weights without the operations, and are the right first step for most teams.
Check your understanding
-
Your self-hosted 8B model on one 80 GB GPU serves 40 tokens a second per user at peak, and the GPU shows 30% compute utilization. A colleague concludes the GPU is underused and proposes doubling concurrency. What do you check, and what could happen?
Answer outline
Low compute utilization is expected: decoding is limited by memory bandwidth, not arithmetic (section 29.1). Check memory instead: how much of the KV cache is in use, whether requests are being preempted or queued, and the distribution of context lengths. Doubling concurrency adds cache reads to every step, so per-user speed falls further; and if cache memory is nearly full, the engine will start preempting conversations, which raises latency sharply. Options that help: 8-bit weights or 8-bit cache to free memory and reduce reads, prefix caching for shared prompts, shorter contexts, or another replica.
-
You are moving a support assistant from a closed API to a self-hosted open model to save money. Traffic is 2 million output tokens an hour at the daily peak and a tenth of that overnight. Outline the decision.
Answer outline
First, quality: run the open model, at the precision you would serve, on the test set by slice (sections 23.4 and 29.4). Then capacity: from the computation in section 29.1, one GPU serving an 8B model at large batch sizes produces several thousand tokens a second at best, around 30 million an hour as an upper bound, so the peak fits on a small number of GPUs for an 8B model and many more for a larger one. Then utilization: sized for the peak, the hardware idles overnight, so compute cost per token at the average utilization, not the peak (section 28.8). Compare that with a hosted open-model provider’s per-token price, which needs no operations (section 29.10). Self-host only if the numbers win clearly at realistic utilization, or if data must stay in-house.
-
After you enable speculative decoding with a small draft model, latency improves by 2.2 times in a load test with one user, but only by 1.1 times in production at peak. Explain, and say what you would measure.
Answer outline
Speculative decoding uses the spare arithmetic of a memory-bound step. At a batch of one there is plenty; at peak, with many conversations batched, the GPU does more useful work per step and has less to spare, and verifying drafts for every conversation adds work (section 29.5). Acceptance may also be lower on real traffic than on the test prompts. Measure the acceptance rate on production traffic, and speedup as a function of batch size; consider enabling speculation only below a load threshold, using shorter drafts at high load, or a drafter with higher acceptance on your traffic, such as prompt-copying for extraction tasks.
Further reading
- Philip Kiely, Inference Engineering (Baseten, 2026, free online): serving open models in production, from GPUs to engines to economics.
- Woosuk Kwon and others, “Efficient Memory Management for Large Language Model Serving with PagedAttention” (2023): the vLLM paper.
- Yaniv Leviathan, Matan Kalman and Yossi Matias, “Fast Inference from Transformers via Speculative Decoding” (2023).
- Yinmin Zhong and others, “DistServe” (2024): separating prefill from decode.
- Stanford CS336, Language Modeling from Scratch: the lecture on inference.