Pidoku

What an Inference Engine Is

Module 15 Lesson 15.a 45 min Difficulty 2/5

Prerequisites 12.d, 12.e, 12.j, 13.a


Before you start: words you need#

WordPlain meaning
Inference engineThe program that loads a model onto GPUs and generates tokens for many users at once. vLLM, SGLang, TensorRT-LLM and llama.cpp are engines.
CheckpointThe files a trained model ships as: weights (usually safetensors), a config file and a tokenizer.
StepOne pass of the engine’s main loop: one forward pass of the model over a batch, producing at most one new token per running request (more with speculative decoding).
KV cacheSaved attention keys and values for every token a request has seen, so they are never recomputed (12.e).
Continuous batchingRe-deciding the batch on every step, so requests join and leave at any moment (12.j).
SchedulerThe part of the engine that decides, each step, which requests run and how many of their tokens.
OpenAI-compatible APIAn HTTP API with the same paths and JSON shapes as OpenAI’s (/v1/chat/completions), so existing client libraries work unchanged.
KernelA function that runs on the GPU, such as one attention or one matrix multiply (5.b).

1. What is it?#

An inference engine is the program that turns a model checkpoint and a GPU into a service that generates tokens for many users at once.

Module 12 taught the mechanisms one at a time: the KV cache, continuous batching, paged attention, prefix caching, speculative decoding, sampling, streaming. An engine is all of them, built into one loop that runs hundreds of times a second. This lesson shows the parts every engine has, how they fit together, and how the main engines differ. Lessons 15.b–15.f cover individual engines and how to choose; Modules 16–19 take vLLM apart from its source code.

Facts checked on 12 November 2026.


2. Why does it exist?#

You can serve a model with a framework alone: load it in PyTorch and call model.generate() in a web handler. It works for one user. With ten users it fails in three ways (1.c, 12.i):

  1. No batching across requests. Each request reads every weight from GPU memory for every token. Ten users cost ten times the memory traffic of one, although one read could have served all ten.
  2. Wasted memory. Each request reserves KV cache for its maximum length up front, so the GPU is “full” after a handful of requests, most of them short.
  3. An idle GPU between steps. Python overhead, tokenising and HTTP handling run between kernel launches, and the GPU waits for them.

An engine fixes all three. On the same GPU the difference in throughput is routinely ten times or more.


3. Simple analogy#

A restaurant kitchen. The front of house (API server) takes orders and brings out dishes as they are ready (streaming). The expediter (scheduler) decides which orders go to the stove at each moment, so the stove is never idle and no table waits too long. The pantry manager (KV cache manager) tracks shelf space and reuses ingredients already prepared (prefix caching). The line cooks (model runner and kernels) do the cooking. A good kitchen is not one fast cook; it is all four working to one rhythm.


4. Tiny example: ten users, two servers#

An 8B model in BF16 is 16 GB of weights. On a GPU with 3.35 TB/s of memory bandwidth (an H100), reading the weights once takes about 4.8 ms.

model.generate() in a handler, 10 users, one at a time:
  each token for each user reads all 16 GB         = 4.8 ms
  10 users x 1 token each                          = 48 ms per "round"
  each user sees about 21 tokens/s

an engine, 10 users batched into one step:
  one read of 16 GB serves all 10                  ≈ 4.8 ms (plus a little for 10x the KV reads)
  each user sees about 200 tokens/s, total ≈ 2,000 tokens/s

The arithmetic is the same as 2.d and 12.j. The engine’s whole job is to keep that batch full, every step, without running out of KV memory.


5. Technical explanation: the parts every engine has#

flowchart LR
  C(("clients")) --> API
  subgraph FE["Frontend"]
    API["API server<br/><small>OpenAI-compatible HTTP / gRPC</small>"]
    TOK["Tokenizer and<br/>chat template"]
    DET["Detokenizer and<br/>streaming"]
  end
  subgraph CORE["Engine core: one loop"]
    SCH["Scheduler<br/><small>who runs this step</small>"]
    KV["KV cache manager<br/><small>blocks, prefix cache</small>"]
  end
  subgraph EXE["Executor"]
    RUN["Model runner<br/><small>builds the batch, CUDA graphs</small>"]
    KER["Kernels<br/><small>attention, GEMM, MoE</small>"]
    SMP["Sampler<br/><small>logits to token</small>"]
    COM["Parallelism<br/><small>NCCL across GPUs</small>"]
  end
  API --> TOK --> SCH
  SCH <--> KV
  SCH --> RUN --> KER --> SMP
  RUN <--> COM
  SMP --> SCH
  SCH --> DET --> API

  class API,TOK,DET io
  class SCH,KV queue
  class RUN,KER,SMP,COM compute
PartJobLesson on the mechanism
API serverAccept requests, validate them, stream tokens back. Almost always OpenAI-compatible (/v1/chat/completions, /v1/responses).20.b
Tokenizer, chat templateText to token IDs, with the model’s chat format applied.12.b
SchedulerEach step, pick which requests run and how many tokens each processes, within a token budget and the free KV memory. Handles chunked prefill, priorities and preemption.12.j, 12.k, 20.k
KV cache managerHand out fixed-size blocks, share them between requests with the same prefix, evict and offload.12.l, 12.m
Model runnerPack the scheduled tokens into GPU tensors, run the forward pass, replay CUDA graphs.13.k, 13.m
KernelsThe maths itself: attention backends (FlashAttention, FlashInfer), quantized matrix multiplies, fused mixture-of-experts (MoE).13.j, 13.l
SamplerTurn logits into the next token: temperature, top-p, penalties, structured output.12.o
Parallelism and communicationSplit the model across GPUs; all-reduce and all-to-all between them.14.c–14.e
Speculative decodingDraft several tokens cheaply, verify them in one pass.12.n, 13.n
ConnectorsMove KV cache to other engines, CPU memory, SSD or remote stores.9.e, 19.b
MetricsTime to first token, inter-token latency, queue depth, KV usage, prefix hit rate.19.c, 22.j

The loop#

Every engine, under all the detail, runs the same loop:

while running:
    new requests  → tokenize → add to the waiting queue
    scheduler     → choose this step's batch (running requests first, then new prefill chunks)
                    within the token budget and the free KV blocks
    KV manager    → allocate blocks; reuse cached prefixes
    model runner  → one forward pass for the whole batch
    sampler       → one new token per request that is ready for one
    outputs       → detokenize and stream; finished requests free their blocks

One pass of this loop is one step. A step takes from a few milliseconds (decode-heavy, small model) to a few hundred (large prefill chunks). Every engine is judged by how full it keeps the GPU in each step, and how little time it spends outside the GPU between steps.

Engines, servers and frameworks#

The words are used loosely. In this material:

Inference engine        runs one model on one group of GPUs: scheduler, KV cache, kernels.
                        vLLM, SGLang, TensorRT-LLM, llama.cpp.

Inference server        wraps engines (or any model) behind an API with model management,
                        ensembles and metrics. Triton Inference Server, KServe, Ray Serve.

Distributed serving     coordinates many engine instances as one service: routing,
framework               disaggregation, KV movement, autoscaling. NVIDIA Dynamo, llm-d.

Local runner            packages an engine for one user on one machine: model download,
                        a CLI, a desktop app. Ollama, LM Studio.

A production stack usually has one from each of the first three rows.


6. Under the hood: where engines differ#

All major engines implement the parts above. They differ in where they put their effort:

vLLMSGLangTensorRT-LLMllama.cpp
Release (12 Nov 2026)v0.32.0 stable (18 Oct), v0.33.0 in release candidatev0.5.23 (2 Nov)v1.2.1 stable (20 Apr); 1.3 never left release candidate; v1.4.0rc3 (6 Nov)continuous numbered builds (b12302 on 12 Nov)
Written inPython with C++/CUDA kernels; an optional Rust frontendPython with C++/CUDA kernels; a Rust router (the SGLang Model Gateway)Python on PyTorch with NVIDIA’s C++/CUDA kernels; PyTorch is the only backend since 1.2C/C++ (the ggml library)
StrengthWidest model and hardware support; the default for open modelsPrefix-heavy and structured workloads (RadixAttention), large-scale expert parallelismPeak performance on NVIDIA GPUs, NVFP4, tight integration with DynamoRuns anywhere: CPUs, Apple Silicon, consumer GPUs; GGUF quantization
HardwareNVIDIA, AMD, TPU, Intel, Apple (vllm-metal plugin), othersNVIDIA, AMD, TPU (plugin), othersNVIDIA onlyeverything
Typical homeany production clusterclusters with heavy prefix reuse or big MoE modelsNVIDIA-only fleets chasing the last 10–20%laptops, edge devices, single users
Lesson16–1915.b15.c15.e

Three observations that hold across versions:

  1. The gap between vLLM and SGLang is small and changes with every release. A benchmark that shows one ahead by 30% is usually measuring one model, one flag set and one workload. Run your own (15.f, 22.g).
  2. Features converge. A technique one engine ships first (prefix trees, chunked prefill, disaggregation, a new speculative method) appears in the others within months. Choose on maintenance, hardware support and operability, not on one feature.
  3. The engine is no longer the whole system. At scale, a distributed serving framework (Dynamo, llm-d) sits above many engine instances, routes between them and moves KV cache between them (21.j). Engines are increasingly built to be driven by such a layer.

What retired#

Hugging Face TGI (Text Generation Inference) was one of the first production LLM servers. It entered maintenance mode in December 2025 (last release v3.3.7, 19 December 2025) and its repository was archived in March 2026. Hugging Face directs new deployments to vLLM or SGLang. 15.d keeps a short description because you will meet it in existing systems.


7. Performance implications: reading an engine’s flags#

Every engine has hundreds of options. Almost all of them tune one of the parts in section 5. When you meet a flag, ask which part it tunes and what it trades:

Flag (vLLM name; others are similar)PartWhat it trades
--max-num-batched-tokensschedulerbigger steps (throughput) against smaller steps (latency)
--max-num-seqsschedulerconcurrency against KV memory per request
--gpu-memory-utilizationKV managerKV capacity against headroom for activations
--enable-prefix-cachingKV managerhit rate against memory held by cached blocks
--kv-cache-dtype fp8KV manager and kernelstwice the KV capacity against a small accuracy risk (13.h)
--tensor-parallel-sizeparallelismfits a bigger model, adds all-reduce cost
--speculative-configspeculative decodinglower latency at low load against wasted work at high load
--quantizationkernelsmemory and bandwidth against accuracy

If you cannot place a flag, read the engine’s code for it. Modules 17–19 do this for vLLM’s main ones.


8. Production implications#

  • Pin versions. Engines release every few weeks and change defaults. vLLM v0.32.0 alone restricted the default CORS origins, removed cascade attention, dropped Python 3.10 and stopped reserving max_tokens out of the context window. Upgrade deliberately, with a benchmark and an evaluation.
  • Read the security notes. Engines parse untrusted input (prompts, images, JSON schemas, chat templates) and fixed real vulnerabilities in 2026; v0.32.0 fixed three advisories, including chat-template resource exhaustion. Treat the engine as an internet-facing service (23.i).
  • Use the official container images for your hardware (CUDA, ROCm, CPU). A home-made build is a common source of slow kernels and missing features.
  • Give the frontend CPU. Tokenising, templating and streaming are CPU work. A server with too few cores leaves the GPU idle (3.e, 16.d).

9. Common mistakes#

  1. Choosing an engine from a blog benchmark. Benchmark your model, your prompt lengths and your latency target.
  2. Treating the engine as a black box. When latency spikes, you need to know whether the scheduler, the KV manager or a kernel is responsible. That is what Modules 16–19 are for.
  3. Running the API server, tokenizer and engine on too few CPU cores. The frontend is CPU work; starved, it leaves the GPU idle (22.i).
  4. Confusing the layers. Dynamo or llm-d does not replace an engine; Triton does not make a model faster by itself. Know which row of the table in section 5 each component is.
  5. Upgrading without reading release notes. A changed default can move latency or output quality without any code change on your side.

10. Hands-on exercise#

  1. Start vLLM with a small model (16.b shows how) and send it 50 concurrent requests. Watch the /metrics endpoint while it runs and say which part in section 5 each number belongs to.
  2. Do the same with SGLang. List three flags that have a direct equivalent in vLLM and one that does not.
  3. For one flag in section 7, change its value, rerun the load test, and explain the change in time to first token and throughput using the part it tunes.
  4. Redo the tiny example in section 4 for a 70B model in FP8 on a B200 (8 TB/s). How many users can one step serve before KV reads, not weight reads, dominate the step?

11. Interview questions#

  1. Name the parts of an LLM inference engine and what each one does.
  2. Why does an engine beat model.generate() in a web handler by an order of magnitude?
  3. What is the difference between an inference engine, an inference server and a distributed serving framework? Give one example of each.
  4. Why should you not choose between vLLM and SGLang on the strength of one published benchmark?
  5. What is one engine step, and what limits how short it can be?

12. Further reading#

Checked on 12 November 2026.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in