0%
LLM Inference and Serving: GPUs, Batching, and Cost
How Inference Works
Hardware and Memory
Making Inference Fast
Inference Engines
An inference engine is the software that turns a model checkpoint and a stream of requests into generated tokens, efficiently. It combines everything covered so far, batching, KV cache management, kernels, quantization, parallelism and speculation, into one system behind an API. This lesson explains what engines do, compares the major open engines, covers vendor and managed stacks, gives a framework for choosing one and describes how to run engines in production. This first section opens the box.
From checkpoint to tokens
A model checkpoint is a set of weight files plus a configuration describing the architecture and a tokenizer. On its own, it does nothing. A minimal inference script could load the weights into a framework, tokenize a prompt, run forward passes in a loop and sample tokens, but it would serve one request at a time, waste most of the GPU and lack the features production needs. An engine wraps the model in a runtime that accepts many concurrent requests, schedules them onto the GPU in batches, manages cache memory, uses optimized kernels and streams results back through an API.
The main components
Most engines share a similar structure. An API server accepts requests, usually through an OpenAI compatible HTTP interface, handles tokenization and streams responses. A scheduler decides each step which sequences run, how much prefill to include and when to preempt. A KV cache manager allocates and frees cache blocks, tracks prefix sharing and handles offloading. A model runner executes the forward pass with optimized kernels, CUDA graphs and parallelism across GPUs. A sampler turns logits into tokens, applying temperature, penalties, grammars and stop conditions. These components run in a loop, one engine step at a time.
Why engines matter so much
The same model on the same GPU can differ in throughput by five to twenty times depending on whether it runs under a naive loop or a mature engine. The difference comes from continuous batching, paged caches, fused kernels, CUDA graphs and good scheduling, each contributing a multiple. For a team serving a model at scale, the engine choice and configuration can matter as much for cost as the choice of GPU. This is why engine development has become one of the most active areas of open source machine learning infrastructure.
Features engines provide
Beyond raw speed, engines provide features applications rely on: streaming output, OpenAI compatible endpoints for chat and completions, structured output with JSON schemas or grammars, tool calling formats, log probabilities, multiple sampling options, LoRA adapters, multimodal inputs for vision language models, embeddings and reranking endpoints, prefix caching, speculative decoding, quantized formats and metrics for monitoring. Feature coverage differs between engines and versions, and the set of features a product needs often narrows the choice.
Model support
Each engine must implement every model architecture it serves, because kernels, cache layouts and parallelism depend on the architecture. Popular open models are usually supported within days of release by the major engines, sometimes on release day through collaboration with the model authors. Less common architectures may lag or be missing. Checking that your exact model, including variants such as mixture of experts or new attention types, is supported and optimized in an engine is the first filter in any selection.
Engines versus frameworks
Training frameworks such as PyTorch provide the building blocks but are not engines. Hugging Face Transformers provides model implementations and a simple generate function that is excellent for experimentation, but it lacks continuous batching and paged caches by default, so it is not suited to high throughput serving on its own. Engines build on these frameworks, often using PyTorch for tensors and custom kernels, and add the serving machinery. Understanding this layering helps when a model works in a notebook but performs poorly in production.
A request through the engine, step by step
Following one request makes the components concrete. A client sends a chat request with a system prompt, a short conversation and a user question. The API server applies the model chat template, which wraps each message in the special tokens the model was trained with, then tokenizes the result into perhaps two thousand token IDs. It validates the request against limits on prompt length and requested output length, assigns a request ID and hands the sequence to the scheduler, which places it in the waiting queue.
On the next engine step, the scheduler sees free capacity in its token budget and admits the request. The cache manager checks whether any prefix of the prompt is already cached, finds that the system prompt matches blocks from earlier requests, and allocates new blocks only for the rest. The scheduler schedules a prefill chunk covering the uncached tokens, possibly split over several steps if the chunk budget is small. Once prefill completes, the sampler produces the first token, which the API server streams back immediately. From then on, the sequence contributes one decode token per step until it emits a stop token or reaches its length limit, at which point its blocks are released, apart from any that remain useful as cached prefix.
The CPU side of the engine
It is easy to think of inference as purely GPU work, but the CPU does a surprising amount. Tokenization and detokenization, request parsing, scheduling decisions, building the input tensors for each step, applying sampling rules and grammar masks, and streaming responses all run on the CPU. At high request rates with small models, the GPU can finish a step faster than the CPU prepares the next one, leaving the GPU idle. Much recent engine work, such as vLLM V1 and the SGLang scheduler design, focuses on cutting this overhead by overlapping CPU preparation with GPU execution, moving work into separate processes and avoiding Python in the hottest paths.
Offline and online modes
Engines usually support two modes of use. In online mode, they run as servers that accept requests over the network and stream results, which is how interactive products use them. In offline mode, a program passes a large list of prompts directly to the engine as a library, and the engine processes them as fast as possible with no latency objectives. Offline mode is common for batch jobs such as generating synthetic data, evaluating models on benchmarks, or classifying large document collections. Because there are no latency constraints, offline runs can use very large batches and reach much higher throughput per GPU than online serving.
What engines do not do
An engine serves one model deployment on a set of GPUs. It does not decide how many replicas to run, route traffic across replicas, authenticate users, enforce per customer quotas, bill usage or manage fleets across regions. These responsibilities belong to the gateway, router, autoscaler and platform around the engine, covered in later lessons. Knowing this boundary helps assign problems to the right layer: a slow TPOT under load is usually an engine or capacity issue, while uneven load across replicas is usually a routing issue.
Reading engine logs at start up
When an engine starts, its logs describe many of the decisions covered in this course: the model architecture detected, the data types chosen for weights and cache, the parallelism layout, the GPU memory reserved for weights, the number of KV cache blocks allocated and therefore the maximum number of tokens the cache can hold, the CUDA graph batch sizes captured and the attention backend selected. Reading these lines is one of the fastest ways to understand a deployment. If the cache can hold only a few thousand tokens, for example, the engine will never reach high concurrency on long prompts, no matter how traffic is routed.
Engines as moving targets
Engines improve so quickly that a deployment configured a year ago may be leaving large gains unused. New attention backends, better scheduling, faster grammar libraries and support for newer quantization formats arrive every few releases. Treating the engine as a component to revisit on a schedule, rather than a fixed dependency, keeps serving cost falling over time.
The same GPU running the same model can deliver many times more throughput under a mature engine. Engine choice and configuration are first class cost decisions.