Open models Guide 16 of 25
Serving LLMs yourself: batching, KV cache, and quantization
Downloading an open-weight model takes minutes. Serving it to many users at once, at a cost that beats an API, is a memory-management problem. Here is how modern inference engines solve it.
Key takeaways
- Decoding is limited by memory bandwidth, not arithmetic. Efficiency comes from batching many requests per read of the weights and fitting their key-value (KV) caches in memory.
- Memory left over for the KV cache, not compute, caps how many requests run at once. Paging it and reusing shared prompt prefixes recovers memory naive servers waste.
- Get continuous batching right first. With paged memory on top, Anyscale’s 2023 benchmark showed up to 23 times the throughput of a naive static-batching baseline.
- Across 500,000-plus evaluations of Llama 3.1 models, 8-bit floating point (FP8) was effectively lossless. 4-bit weights suit latency-bound serving; 8-bit formats suit heavy batching.
- Add speculative decoding and prefill–decode disaggregation only when measurements say you need them. Both pay off in specific regimes and add moving parts.
On this page 7 sections
Getting an open-weight model to answer a question on your own hardware takes an afternoon. Getting it to serve hundreds of concurrent users, at predictable latency and a cost per token that beats an application programming interface (API), is a different job. In a June 2023 benchmark, Anyscale measured up to 23 times more throughput from the same model on the same graphics processing unit (GPU), just by changing the serving software.
The techniques behind that gap — continuous batching, a paged key-value (KV) cache, quantization, and speculative decoding — now ship inside the leading open-source inference engines. You no longer implement them. You still have to understand them, because each one shifts the balance between latency, throughput, memory, and accuracy, and only you know which of those your product can spare.
This guide explains why large language model (LLM) inference is bound by memory rather than arithmetic, where that memory goes, and how each technique wins capacity back.
Why is LLM inference limited by memory, not compute?
Every request runs in two phases. Prefill reads the whole prompt in one parallel pass, which keeps the GPU’s arithmetic units busy. Decode then produces the answer one token at a time, and every step streams the model’s weights, plus that request’s cached attention state, from GPU memory to the compute cores.
Decode is the bottleneck. Google Research points out that accelerators can perform hundreds of operations per byte they read, while a Transformer at inference performs only a few. Databricks gives a worked example: a 7-billion-parameter model at 16-bit precision moves 14 GB of weights per step. Producing one token every 14 milliseconds therefore consumes 1 TB/s of memory bandwidth.
The way out is batching. Read the weights once, apply them to 64 sequences, and you get 64 tokens for roughly the price of one pass over the weights. On a single A100, Databricks found a batch of 64 lifted MPT-7B’s throughput 14-fold, while each request took about four times longer.
The metrics that matter
Users feel two numbers. Time to first token (TTFT) is driven by prefill and queuing; time per output token (TPOT) is the streaming speed. Total latency is roughly TTFT plus TPOT times the output length, and a TPOT of 100 milliseconds already outpaces a typical reader, per Databricks. Operators add a third number, throughput across all users, and batching trades it against the first two.
Where does GPU memory go? Inside the KV cache
To generate each token, attention needs the keys and values computed for every earlier token in the sequence. Recomputing them every step would be ruinous, so engines store them in the KV cache. It grows by one entry per token, per layer, for every sequence in flight, and it is freed when the request ends.
It is large. The UC Berkeley-led team behind vLLM measured about 800 KB of cache per token for the 13-billion-parameter OPT model — up to 1.6 GB for a single 2,048-token sequence (Kwon et al., 2023). Newer models share keys and values across groups of attention heads (grouped-query attention), which helps. Even so, Databricks’ figures for Llama 2 70B work out to about 0.33 MB per token, beside 140 GB of 16-bit weights.
Once the weights are loaded, the leftover memory decides how many requests can run at once. A rough budget:
# Two 80 GB GPUs, with ~10% left for runtime overhead.
usable_gb = 2 * 80 * 0.9
# Llama 2 70B-class model, 16-bit keys and values.
kv_mb_per_token = 0.33
def cache_tokens(bytes_per_weight):
# 70 billion parameters.
weights_gb = 70 * bytes_per_weight
free_mb = (usable_gb - weights_gb) * 1000
return free_mb / kv_mb_per_token
# 16-bit weights: ~12,000 tokens, one or two 8K-token chats.
cache_tokens(2)
# 8-bit weights: ~224,000 tokens, about 27 such chats.
cache_tokens(1)
Same GPUs, same model. Halving the bytes per weight turns room for one or two long conversations into room for about 27. That is why memory, more than raw compute, sets the economics of serving.
PagedAttention: virtual memory for the cache
Early servers reserved one contiguous slab per request, sized for the longest possible output, and most of it sat empty. Profiling existing systems, the vLLM team found just 20.4–38.2% of KV cache memory holding real token state (Kwon et al., 2023). Reservations and fragmentation consumed the rest.
PagedAttention borrows the operating system’s fix for the same problem. The cache is cut into small fixed-size blocks, 16 tokens by default in the original vLLM, which are allocated only as a sequence grows. A per-request block table maps logical positions to wherever the blocks physically live. Waste falls to near zero, and the paper reports 2–4 times the throughput of FasterTransformer and Orca at the same latency.
Blocks can also be shared. Requests that begin with the same tokens, such as a long system prompt, can point at the same physical blocks instead of computing and storing them twice; engines call this prefix caching. It should change how you write prompts: stable instructions, tool definitions, and examples first, per-request content last.
How does continuous batching keep GPUs busy?
Static batching groups requests, runs them together, and returns when the longest one finishes. A request needing 20 tokens holds its slot while a neighbor generates 2,000, and new arrivals queue until the whole batch drains.
Continuous batching schedules per decoding step instead. After every step, finished sequences leave and waiting ones join, so the batch stays full. Anyscale credits the idea to Orca, a system presented at the Operating Systems Design and Implementation (OSDI) conference in 2022. Its benchmark, serving OPT-13B on one 40 GB A100, found continuous batching alone gave 8 times naive throughput, rising to 23 times with vLLM’s memory management.
Read those multiples carefully: the baseline was Hugging Face’s simple pipeline, not a tuned server. The durable lesson is that a server without continuous batching leaves most of the GPU idle.
Chunked prefill and the long-prompt problem
Mixing prefill and decode on one GPU creates collisions. A 50,000-token prompt arriving mid-stream can stall token generation for everyone already being served. Chunked prefill splits long prompts into pieces that run alongside ongoing decode steps, and vLLM’s V1 engine enables it by default whenever possible (vLLM docs). It softens the problem rather than removing it: the DistServe authors report that, even with chunking, one large prefill can inflate TPOT 2–30 times, with bursty traffic the worst case (Hao AI Lab, 2025).
Quantization: what do you lose with fewer bits?
Quantization represents weights, and sometimes activations, with fewer bits. Because decode is limited by bytes moved, smaller weights mean faster tokens and more room for the KV cache. The open question is always accuracy.
One of the largest public studies comes from Red Hat AI and the Institute of Science and Technology Austria. The team ran more than 500,000 evaluations across the Llama 3.1 family, from 8B to 405B parameters (Kurtic et al., 2024). By format:
- 8-bit floating point (FP8) weights and activations were effectively lossless at every model size. The paper pairs FP8 with NVIDIA’s Hopper and Ada Lovelace GPUs, which support it natively.
- 8-bit integer (INT8) weights and activations, the route for older Ampere GPUs, cost roughly 1–3% accuracy per task, on average, once carefully tuned.
- W4A16, meaning 4-bit integer weights with activations kept at 16 bits, landed roughly level with INT8. Here a simple variant of GPTQ, a widely used post-training method, outscored the newer activation-aware weight quantization (AWQ) on real-world tasks.
Model size matters too. In the study’s comparisons of generated text, large quantized models stayed close to the original model’s wording and sentence structure. Small ones kept the meaning but drifted more in phrasing.
Which format wins depends on load, and the reason is mechanical. Served one query at a time, decode is bandwidth-bound and 4-bit weights help most: W4A16 cut cost per query 2–3 times for the 8B and 70B models. Under heavy continuous batching more of the work is arithmetic, and formats that quantize both weights and activations to 8 bits (W8A8) generally delivered the highest throughput, though W4A16 stayed competitive.
The KV cache can be quantized too. vLLM supports an FP8 KV cache (vLLM docs), which halves the per-token figure in the budget above. Test long-context quality before switching it on.
Speculative decoding: spending idle compute on speed
Decode leaves arithmetic units idle, and speculative decoding puts them to work. A small, fast draft model guesses the next several tokens. The large model checks all of them in one forward pass, keeps the guesses up to the first it rejects, and adds one token of its own. A rejection-sampling rule makes the output distribution identical to the large model’s, so quality is unchanged by construction.
Google Research introduced the method in 2022 and reported roughly 2–3 times faster generation on translation and summarization. In a December 2024 retrospective, it said speculative decoding helps AI Overviews in Google Search respond faster at the same quality.
The speedup depends on how often the draft is right, which favors predictable output such as code, structured extraction, and templated text. It also depends on idle compute. Our inference from the mechanism, not a published benchmark: on a heavily batched server the arithmetic units are already busy, so expect smaller gains at peak load and measure before relying on it.
Scaling out: when should prefill and decode split?
A model too big for one GPU is split across several, usually with tensor parallelism, which divides each layer’s matrices among GPUs joined by fast links. Latency returns diminish quickly. Doubling from four to eight 40 GB A100s cut Llama 2 70B’s time to first token only from 154 to 114 milliseconds, Databricks found.
Large fleets increasingly split the two phases: in disaggregated serving, prefill runs on one pool of GPUs, decode on another, and the KV cache travels between them. UC San Diego’s Hao AI Lab and collaborators introduced it as DistServe in early 2024, alongside concurrent work such as Splitwise. By late 2025, according to a retrospective by the DistServe authors, it was supported in NVIDIA Dynamo, llm-d, SGLang, and vLLM and had become, in their view, the standard design for large-scale serving. It removes prefill–decode interference and lets each phase scale to its own latency target.
The scale is telling. The SGLang test of DeepSeek-R1 that the retrospective cites used 96 H100 GPUs: 24 for prefill and 72 for decode. DeepSeek-R1 is a mixture-of-experts (MoE) model, which activates only part of its network per token but must keep all of it in memory. For a team running a handful of GPUs, our view is that disaggregation is premature; chunked prefill and sensible batch limits capture most of the benefit.
Before you self-host: a checklist
| Technique | What it fixes | What it costs | Reach for it when |
|---|---|---|---|
| Continuous batching | Idle slots; requests queuing behind long answers | Little; it is the norm in modern engines | Always |
| Paged KV cache and prefix caching | Wasted cache memory; recomputed shared prompts | Prompts must keep a stable prefix | Always; design prompts around it |
| Chunked prefill | Long prompts stalling everyone’s stream | The long prompt’s own first token may come later | Mixed short and long prompts |
| Weight quantization | Weights crowding out the cache; slow decode | Accuracy risk, higher at 4 bits and in small models | FP8 by default where supported; 4-bit when latency- or memory-bound |
| Speculative decoding | Slow per-user streaming at modest load | Extra compute; a draft model to maintain | Latency-critical, predictable outputs |
| Prefill–decode disaggregation | Interference; coupled scaling | KV transfer, more services, more GPUs | Multi-node fleets with strict TTFT and TPOT targets |
- Decide whether to self-host at all. It pays when traffic is steady enough to keep GPUs busy, when data must stay in your environment, or when you need a customized open model. For spiky, low-volume traffic, an idle GPU produces the most expensive tokens you can buy.
- Write latency targets as TTFT and TPOT. Set them at the 50th and 95th percentiles for your real prompt and output lengths, then benchmark at production-like concurrency. Uniform synthetic prompts flatter every engine.
- Size memory before you buy GPUs. Budget weights first, then KV cache per token times the context your concurrent users will hold, with headroom for the runtime.
- Start from a maintained engine and its defaults. Hugging Face put its Text Generation Inference (TGI) server into maintenance mode in December 2025, recommending vLLM and SGLang, and has since archived the repository (Hugging Face). As of October 2026, the vLLM V1 engine lists support for NVIDIA, AMD, and Intel GPUs, tensor processing units (TPUs), and central processing units (CPUs) (vLLM docs).
- Quantize, then prove it. FP8 is the low-risk default on hardware that supports it. Run your own evaluations before shipping 4-bit weights, especially for small models, code, and long contexts.
- Re-benchmark on every engine upgrade. Defaults, kernels, and schedulers change between releases, and so does your cost per token.
Memory budgets, scheduler settings, and an evaluation suite you trust decide whether self-hosting beats an API. When SurgeX Labs sizes a deployment of an open model, the KV-cache budget at real concurrency is the first number on the page.
Sources
-
Efficient Memory Management for Large Language Model Serving with PagedAttention (opens in new tab) — UC Berkeley et al. (SOSP 2023, arXiv), 2023 arxiv.org
-
How continuous batching enables 23x throughput in LLM inference while reducing p50 latency (opens in new tab) — Anyscale, 2023 anyscale.com
-
LLM Inference Performance Engineering: Best Practices (opens in new tab) — Databricks (MosaicML team), 2023 databricks.com
-
Looking back at speculative decoding (opens in new tab) — Google Research, 2024 research.google
-
“Give Me BF16 or Give Me Death”? Accuracy-Performance Trade-Offs in LLM Quantization (opens in new tab) — Red Hat AI and ISTA (ACL 2025, arXiv), 2024 arxiv.org
-
Disaggregated Inference: 18 Months Later (opens in new tab) — Hao AI Lab, UC San Diego, 2025 haoailab.com
-
vLLM V1 (opens in new tab) — vLLM project (documentation), 2026 docs.vllm.ai
-
text-generation-inference (repository README) (opens in new tab) — Hugging Face (GitHub), 2026 github.com
Where this shows up in our work
- Case study · client work Who said what, on messy real-world audio — Voiceprint speaker-diarization R&D