AI infrastructure and systemsPart 2: Inference serving
Chapter 6Serving engines
The same model on the same GPU can deliver several times more tokens per second depending on the software that serves it. That software is the serving engine, and choosing one is the first real decision in any inference project. This chapter explains what engines do inside, compares the ones you will meet in late 2026, and has you benchmark two of them under identical load.
After this chapter you can
- Describe the components of a serving engine and the job of each.
- Explain how PagedAttention and continuous batching raise throughput.
- Compare vLLM, SGLang, llama.cpp, Ollama, TensorRT-LLM, NVIDIA Dynamo-Triton and Hugging Face TGI, including maintenance status.
- Use an OpenAI-compatible API with streaming and structured output.
- Choose a multi-GPU layout and an engine for a given workload, and defend the choice with a benchmark.
What a serving engine does
A serving engine wraps the model's forward pass in everything needed to share one accelerator among many users. Running model.generate() in a Flask app gives you one request at a time and wasted memory; an engine gives you hundreds of concurrent streams.
| Component | Job | What goes wrong without it |
|---|---|---|
| API server | Parses requests, validates parameters, streams responses | Every team writes its own incompatible wrapper |
| Scheduler | Decides each step which sequences run, which wait, which get preempted | GPU idles or memory overflows |
| KV cache manager | Allocates, shares and frees cache memory | Fragmentation caps concurrency |
| Model executor | Runs optimized kernels, possibly across several GPUs | Slow attention, no multi-GPU |
| Metrics | Exposes queue depth, cache use, latency histograms | You cannot autoscale or debug |
The scheduler and the cache manager are where engines really differ. The rest is engineering polish.
PagedAttention: virtual memory for the KV cache
Early servers reserved one contiguous chunk of cache per request, sized for the maximum possible length. A request that might reach 4,096 tokens but stopped at 300 wasted over 90 percent of its reservation. The vLLM paper measured existing systems using only 20 to 40 percent of KV memory for actual tokens.
PagedAttention borrows the operating system's answer. The cache is cut into fixed-size blocks (16 tokens is a common size), and each sequence keeps a block table mapping its logical token positions to physical blocks anywhere in GPU memory. Blocks are allocated only as tokens arrive, so waste is limited to the last, partly filled block.
The diagram shows a second benefit. Sequences A and B share a system prompt, so both tables point at physical block 7 and the prompt's cache is stored once. This sharing is what makes prefix caching cheap: vLLM hashes full blocks and reuses them across requests automatically, and SGLang keeps a radix tree of cached prefixes (RadixAttention) for the same purpose.
The engines in late 2026
The landscape changed noticeably in 2025. Hugging Face put TGI into maintenance mode, NVIDIA renamed Triton and built Dynamo around it, and vLLM and SGLang became the default open engines for GPU serving.
| Engine | Best at | Hardware | Status, late 2026 |
|---|---|---|---|
| vLLM | General-purpose high-throughput GPU serving, widest model support | NVIDIA, AMD, Google TPU, Intel, CPU | Very active; the reference open engine |
| SGLang | Prefix-heavy and structured workloads (agents, RAG, JSON), large MoE models | NVIDIA, AMD, TPU | Very active; sglang serve is the recommended entry point |
| TensorRT-LLM | Peak performance on NVIDIA GPUs | NVIDIA only | Active; PyTorch-based backend is the default in 1.x, served with trtllm-serve |
| NVIDIA Dynamo-Triton | Multi-framework model server (formerly Triton Inference Server) for mixed ML fleets | NVIDIA, CPU | Active under the Dynamo brand; Dynamo itself orchestrates vLLM, SGLang or TensorRT-LLM at datacenter scale |
| llama.cpp | CPUs, Apple silicon, consumer GPUs, edge; GGUF quantized models | Almost anything | Very active; llama-server is OpenAI-compatible |
| Ollama | Developer desktops: one command to pull and run a model | Mac, Linux, Windows, consumer GPUs | Active; built on the GGML ecosystem, tuned for simplicity over concurrency |
| Hugging Face TGI | Existing deployments only | NVIDIA, AMD, others | Maintenance mode since late 2025; Hugging Face points new users to vLLM or SGLang |
Two engines deserve a sentence on what makes them distinct. TensorRT-LLM gets its speed from NVIDIA-specific kernels and tight integration with new hardware features, at the cost of portability. Ollama sets OLLAMA_NUM_PARALLEL to 1 on most backends by default, so out of the box it serves one request at a time per model; it is a fine development server and a poor high-concurrency one.
OpenAI-compatible APIs
Almost every engine now speaks the OpenAI HTTP API, which means one client library can talk to all of them. Start a server, point the official SDK at it, and only the base URL and model name change.
vllm serve Qwen/Qwen2.5-7B-Instruct --port 8000 --max-model-len 8192
llama-server -hf Qwen/Qwen2.5-7B-Instruct-GGUF:Q4_K_M --port 8080
python -m sglang.launch_server --model-path Qwen/Qwen2.5-7B-Instruct --port 30000Recent SGLang releases also offer sglang serve as the preferred entry point; the module form above still works.
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="unused")
stream = client.chat.completions.create(
model="Qwen/Qwen2.5-7B-Instruct",
messages=[{"role": "user", "content": "Explain KV cache in one sentence."}],
stream=True, max_tokens=100)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)Compatible does not mean identical. Engines differ in how they treat the model field (vLLM checks it against the served name; llama-server in single-model mode largely ignores it), which extra sampling parameters they accept, whether they send token usage in the final streamed chunk, and how they parse tool calls for each model family. Test the exact features you depend on.
Structured output
Applications often need JSON that matches a schema, not prose. Asking nicely in the prompt fails some fraction of the time. Engines solve this with constrained decoding: the schema is compiled into a grammar, and at every step the sampler masks out tokens that would make the output invalid.
In vLLM, pass the schema through the standard response_format field or the engine-specific structured_outputs key. The older guided_json style parameters were removed, so older tutorials will fail.
from pydantic import BaseModel
from openai import OpenAI
class Ticket(BaseModel):
severity: str
component: str
summary: str
client = OpenAI(base_url="http://localhost:8000/v1", api_key="unused")
resp = client.chat.completions.create(
model="Qwen/Qwen2.5-7B-Instruct",
messages=[{"role": "user", "content": "Disk full on db-3, writes failing."}],
extra_body={"structured_outputs": {"json": Ticket.model_json_schema()}})
print(Ticket.model_validate_json(resp.choices[0].message.content))llama-server offers the same idea through GBNF grammars and a json_schema request field. Constrained decoding guarantees syntax, not truth: the JSON will parse, but the model can still put wrong values in it.
Multi-GPU serving
When a model does not fit on one GPU, or one GPU cannot meet the throughput target, you split the work. There are four basic layouts, and engines combine them.
| Layout | How it splits | Use when | vLLM flag |
|---|---|---|---|
| Tensor parallel (TP) | Each layer's matrices split across GPUs; all-reduce after every layer | Model too big for one GPU, GPUs linked by NVLink in one node | --tensor-parallel-size |
| Pipeline parallel (PP) | Consecutive layers on different GPUs or nodes | Model too big for one node | --pipeline-parallel-size |
| Data parallel (DP) | Full replicas, each serving different requests | Model fits; you need more throughput | --data-parallel-size or more replicas |
| Expert parallel (EP) | Mixture-of-experts layers spread across GPUs | Large MoE models | --enable-expert-parallel |
Tensor parallelism communicates at every layer, so it needs fast links; across a normal network it is slow. A common rule is TP within a node, PP across nodes, DP for everything beyond that.
A newer pattern is disaggregated serving: prefill runs on one pool of GPUs and decode on another, with the KV cache transferred between them. Because prefill is compute-bound and decode is memory-bound, separating them lets you size and tune each pool for its own bottleneck. NVIDIA Dynamo and the llm-d project build this on top of vLLM and SGLang; you will meet them again in the chapter on scaling and routing inference.
How to choose
Every branch that matters ends in "benchmark". Published comparisons use someone else's model, prompt lengths and hardware, and engine versions change monthly. Your benchmark, on your prompts, decides.
Key terms
- Serving engine
- Software that schedules, batches and runs model inference for many concurrent requests behind an API.
- PagedAttention
- Storing the KV cache in fixed-size blocks mapped through per-sequence block tables, like virtual memory pages.
- Prefix caching
- Reusing cached KV blocks for prompt prefixes already seen, skipping their prefill.
- RadixAttention
- SGLang's prefix cache, which indexes cached prefixes in a radix tree for reuse across requests.
- Constrained decoding
- Masking invalid tokens at each step so output always matches a grammar or JSON schema.
- Tensor parallelism
- Splitting each layer's weight matrices across GPUs that synchronise after every layer.
- Disaggregated serving
- Running prefill and decode on separate GPU pools and transferring the KV cache between them.
- GGUF
- The single-file model format used by llama.cpp and Ollama, holding quantized weights and metadata.
Benchmark two engines behind one OpenAI-compatible client
Goal: serve the identical quantized model with llama-server and Ollama, drive both with the same load generator, and report TTFT, inter-token latency and throughput at several concurrency levels.
You need: macOS or Linux (WSL2 on Windows), 8 GB RAM, Python 3.10+, llama.cpp (brew install llama.cpp) and Ollama (installer from ollama.com). Then pip install openai. If you have an NVIDIA GPU or a Colab GPU session, you can swap Ollama for vLLM (pip install vllm) as noted in step 2.
- Start llama-server with four slots of 4,096 tokens each, on port 8080.
llama-server -hf Qwen/Qwen2.5-0.5B-Instruct-GGUF:Q4_K_M \
--port 8080 -np 4 -c 16384 --metrics- Start Ollama with the same file and the same parallelism. Ollama can pull GGUF files straight from Hugging Face with an
hf.co/model name, so both engines run byte-identical weights.
OLLAMA_NUM_PARALLEL=4 OLLAMA_CONTEXT_LENGTH=4096 ollama serve
# in a second terminal
ollama pull hf.co/Qwen/Qwen2.5-0.5B-Instruct-GGUF:Q4_K_MGPU variant: replace Ollama with vllm serve Qwen/Qwen2.5-0.5B-Instruct --port 8000 --max-model-len 4096 and use base URL http://127.0.0.1:8000/v1. That compares different weight precisions, so note it in your write-up.
- Save the load generator. It keeps a fixed number of requests in flight for a set duration (a closed-loop test) and reports percentiles.
import argparse, asyncio, time, statistics, json
from openai import AsyncOpenAI
p = argparse.ArgumentParser()
p.add_argument("--base-url"); p.add_argument("--model")
p.add_argument("--concurrency", type=int, default=4)
p.add_argument("--duration", type=int, default=60)
p.add_argument("--prompt-words", type=int, default=400)
p.add_argument("--max-tokens", type=int, default=128)
a = p.parse_args()
client = AsyncOpenAI(base_url=a.base_url, api_key="none", timeout=300)
PROMPT = ("Log line: service started, cache warm, request ok. " * (a.prompt_words // 8)
+ "\nWrite a detailed incident summary of the log above.")
ttfts, itls, tokens, errors = [], [], 0, 0
async def worker(deadline):
global tokens, errors
while time.perf_counter() < deadline:
t0 = time.perf_counter(); stamps = []
try:
s = await client.chat.completions.create(model=a.model, stream=True,
max_tokens=a.max_tokens, temperature=0,
messages=[{"role": "user", "content": PROMPT}])
async for ch in s:
if ch.choices and ch.choices[0].delta.content:
stamps.append(time.perf_counter())
except Exception:
errors += 1; continue
if stamps:
ttfts.append(stamps[0] - t0); tokens += len(stamps)
itls.extend(b - x for x, b in zip(stamps, stamps[1:]))
async def main():
start = time.perf_counter()
await asyncio.gather(*[worker(start + a.duration) for _ in range(a.concurrency)])
wall = time.perf_counter() - start
q = lambda xs, n: statistics.quantiles(xs, n=100)[n - 1] if len(xs) > 1 else float("nan")
print(json.dumps({"base_url": a.base_url, "concurrency": a.concurrency,
"requests": len(ttfts), "errors": errors,
"ttft_p50_s": round(q(ttfts, 50), 3), "ttft_p95_s": round(q(ttfts, 95), 3),
"itl_p50_ms": round(q(itls, 50) * 1000, 1), "itl_p95_ms": round(q(itls, 95) * 1000, 1),
"throughput_tok_s": round(tokens / wall, 1)}))
asyncio.run(main())- Warm both servers with one short request each, then run the same sweep against each engine. Each run takes one minute.
for c in 1 2 4 8; do
python loadgen.py --base-url http://127.0.0.1:8080/v1 --model qwen --concurrency $c | tee -a llamacpp.jsonl
python loadgen.py --base-url http://127.0.0.1:11434/v1 \
--model hf.co/Qwen/Qwen2.5-0.5B-Instruct-GGUF:Q4_K_M --concurrency $c | tee -a ollama.jsonl
doneExpect one JSON line per run. On a laptop, both engines should land in the same broad range because they share the GGML kernels; differences come from scheduling, defaults and HTTP overhead. At concurrency 8 with 4 slots, p95 TTFT should jump on both, since half the requests wait for a slot.
- Write a short
RESULTS.mdwith a table per engine, your hardware, model file, engine versions (llama-server --version,ollama --version) and the exact commands. Note which engine won on p95 TTFT and which on throughput, and give one hypothesis for each difference.
Check your work: you have two JSONL files with four lines each, zero errors, and throughput that rises from concurrency 1 to 4 and then flattens. If Ollama's throughput stays flat from concurrency 1 onward, OLLAMA_NUM_PARALLEL did not take effect; restart ollama serve with the variable exported.
Stretch: add a structured-output test. Send 50 requests asking for a JSON object with three fields, once with a response_format JSON schema and once with only prompt instructions, and count how many responses parse and validate in each case on each engine.
Check yourself
A service reserves KV cache for the full 8,192-token context of every request, but average requests use 600 tokens. What does PagedAttention change?
A team runs Ollama with default settings in production and sees throughput that does not improve with more concurrent users. What is the most likely first fix?
You serve a 70B model across 8 GPUs in two nodes connected by ordinary Ethernet. Which layout is most sensible?
A new project needs an open-source GPU engine. A colleague proposes Hugging Face TGI because an old tutorial uses it. What is the strongest objection?
Constrained decoding with a JSON schema is enabled. Which failure can still happen?
Recap
- A serving engine is an API server, a per-step scheduler, a KV cache manager and an optimized executor.
- PagedAttention stores the cache in on-demand blocks, cutting waste and enabling prefix sharing.
- vLLM and SGLang lead open GPU serving, TensorRT-LLM targets peak NVIDIA performance, llama.cpp and Ollama own laptops and edge, and TGI is in maintenance mode.
- OpenAI compatibility makes engines swappable, but test the exact features you rely on.
- Use tensor parallelism inside a node, pipeline parallelism across nodes and replicas for throughput.
- Choose with your own benchmark on your own prompts, and pin versions.
Go deeper
- vLLM documentation: serving flags, parallelism, structured outputs and metrics.
- Efficient Memory Management for LLM Serving with PagedAttention: the paper behind paged KV caching.
- SGLang repository: RadixAttention, server arguments and benchmarks.
- Text Generation Inference documentation: the maintenance-mode notice and migration guidance.
- NVIDIA Dynamo: NVIDIA's distributed serving layer and the successor to Triton for LLMs.
- GuideLLM: a load generator for OpenAI-compatible servers when you outgrow the lab script.