Careers Post-AI
AI infrastructure and systems: all chapters

AI infrastructure and systemsPart 2: Inference serving

Chapter 6Serving engines

30 min read, 1 lab, Intermediate

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.

ComponentJobWhat goes wrong without it
API serverParses requests, validates parameters, streams responsesEvery team writes its own incompatible wrapper
SchedulerDecides each step which sequences run, which wait, which get preemptedGPU idles or memory overflows
KV cache managerAllocates, shares and frees cache memoryFragmentation caps concurrency
Model executorRuns optimized kernels, possibly across several GPUsSlow attention, no multi-GPU
MetricsExposes queue depth, cache use, latency histogramsYou 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.

EngineBest atHardwareStatus, late 2026
vLLMGeneral-purpose high-throughput GPU serving, widest model supportNVIDIA, AMD, Google TPU, Intel, CPUVery active; the reference open engine
SGLangPrefix-heavy and structured workloads (agents, RAG, JSON), large MoE modelsNVIDIA, AMD, TPUVery active; sglang serve is the recommended entry point
TensorRT-LLMPeak performance on NVIDIA GPUsNVIDIA onlyActive; PyTorch-based backend is the default in 1.x, served with trtllm-serve
NVIDIA Dynamo-TritonMulti-framework model server (formerly Triton Inference Server) for mixed ML fleetsNVIDIA, CPUActive under the Dynamo brand; Dynamo itself orchestrates vLLM, SGLang or TensorRT-LLM at datacenter scale
llama.cppCPUs, Apple silicon, consumer GPUs, edge; GGUF quantized modelsAlmost anythingVery active; llama-server is OpenAI-compatible
OllamaDeveloper desktops: one command to pull and run a modelMac, Linux, Windows, consumer GPUsActive; built on the GGML ecosystem, tuned for simplicity over concurrency
Hugging Face TGIExisting deployments onlyNVIDIA, AMD, othersMaintenance 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 30000

Recent SGLang releases also offer sglang serve as the preferred entry point; the module form above still works.

client.py
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.

structured.py
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.

LayoutHow it splitsUse whenvLLM flag
Tensor parallel (TP)Each layer's matrices split across GPUs; all-reduce after every layerModel too big for one GPU, GPUs linked by NVLink in one node--tensor-parallel-size
Pipeline parallel (PP)Consecutive layers on different GPUs or nodesModel too big for one node--pipeline-parallel-size
Data parallel (DP)Full replicas, each serving different requestsModel fits; you need more throughput--data-parallel-size or more replicas
Expert parallel (EP)Mixture-of-experts layers spread across GPUsLarge 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.
Lab

Benchmark two engines behind one OpenAI-compatible client

Intermediate, 75 min

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.

  1. 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
  1. 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_M

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

  1. Save the load generator. It keeps a fixed number of requests in flight for a set duration (a closed-loop test) and reports percentiles.
loadgen.py
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())
  1. 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
done

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

  1. Write a short RESULTS.md with 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