AI & Data
Serve AI models fast and cheaply: GPUs, inference engines, quantization, caching, parallelism and production ops.
A path for engineers who deploy and optimise model serving. It starts with latency and throughput metrics and how transformers and diffusion models run, then covers bottleneck analysis, GPU hardware, CUDA, inference engines, quantization, speculative decoding, caching, parallelism and disaggregation, non-LLM workloads, and running it all in production. It assumes you know Python and basic machine learning. Each subject links official documentation or the original paper.
The subjects follow the roadmap.sh Inference Engineering roadmap.
Inference engineering is the work of serving trained models fast, reliably and cheaply: choosing hardware, runtimes and optimisations, then operating them under real traffic. Unlike training, it runs forever, so small per-token savings compound into most of a model’s lifetime cost.
Closed models are reached only through a vendor API; open-weight models such as Llama, Qwen or DeepSeek can be downloaded and served on your own hardware, which is where inference engineering really applies.
Training runs forward and backward passes over huge batches to update weights; inference runs forward passes only, often at small batch sizes under latency targets, so it tends to be memory-bandwidth bound rather than compute bound.
Shared, per-token endpoints are cheap to start but have noisy neighbours and rate limits; dedicated GPUs give predictable latency and custom models but you pay for idle capacity.
From bottom to top: accelerators and interconnects, drivers and CUDA, kernels and frameworks, an inference engine such as vLLM, then the serving layer with routing, batching, autoscaling and observability.
The vocabulary every inference conversation uses. These metrics describe what a user feels (how fast the answer starts and streams) and what the operator pays for (how many tokens a GPU produces per second).
TTFT is the delay from sending a request to receiving the first output token. It is dominated by queueing and the prefill pass over the prompt, so long prompts and busy servers raise it.
Measured per request (how fast one stream generates) or per system (total output across all concurrent requests). Always state which one you mean, since batching trades one for the other.
The gap between successive output tokens during decoding, also called time per output token. Under about 50 ms reads as smooth streaming; it rises as batch size grows.
Bigger batches use the GPU better and raise total throughput but slow every individual request. Serving is about picking the point on that curve that meets your latency target at the lowest cost.
Averages hide the experience of your unluckiest users, so latency is reported as distributions and measured end to end. Different workloads also need different units, such as speed relative to real time for audio.
Report p50, p90 and p99 rather than means. Tail latency drives SLOs and user complaints, and it grows sharply as utilisation approaches saturation.
Total request latency as the client sees it, including network, queueing, pre-processing, prefill, decode and post-processing. Engine-only numbers often look far better than this.
For speech, processing time divided by audio duration. An RTF below 1 means faster than real time, which streaming speech recognition and text-to-speech both require.
A neural network is layers of matrix multiplications and nonlinearities whose weights were learned in training. For inference, what matters is how many parameters must be read from memory and how many floating-point operations each token or image costs.
An encoder reads the whole input once into representations and a decoder generates output attending to them, as in T5 and Whisper. Most chat LLMs are decoder-only; embedding models are encoder-only.
LLMs are decoder-only transformers that generate one token at a time, each step conditioned on everything before it. That autoregressive loop is why memory bandwidth, the KV cache and batching dominate LLM serving.
Each layer is attention plus a feed-forward MLP, with residual connections and normalisation. The MLP holds most parameters; attention cost grows with sequence length.
Each token builds a query and compares it against the keys of all previous tokens to weight their values. Cost is quadratic in sequence length during prefill and linear per step during decode.
Keys and values of past tokens are stored so each new token only computes its own. The cache grows with layers, heads, context length and batch size and often uses more GPU memory than spare weights allow.
A router sends each token to a few of many expert MLPs, so only a fraction of parameters run per token. Compute per token drops, but all experts must still fit in memory.
How a request is processed and when its result is needed. The prefill and decode phases have opposite hardware profiles, and whether a user is waiting decides how much batching and delay you can afford.
Prefill processes the whole prompt in parallel and is compute bound; decode produces one token per step and is memory-bandwidth bound. Schedulers mix or separate them to keep both efficient.
Online serving answers live users under latency targets; offline batch jobs such as evaluations or data labelling maximise throughput and can run on cheaper or preemptible capacity.
Requests go into a queue and results are delivered later by polling or webhook. Suits long generations and batch APIs, and lets you smooth load instead of scaling for peaks.
Most image and video generators are diffusion models that iteratively denoise a latent over many steps. Each step is a full network pass over the whole image, so inference is compute bound and step count dominates cost.
Trained to reverse a gradual noising process; at inference they start from noise and remove it step by step, guided by a text prompt through classifier-free guidance.
A text encoder, a denoiser (a U-Net in older models, a diffusion transformer in newer ones) working in a VAE’s compressed latent space, and a VAE decoder back to pixels.
Distillation methods such as latent consistency models and adversarial distillation cut sampling from dozens of steps to between one and four, with some loss in quality or diversity.
Diffusion transformers over spatio-temporal latents; token counts reach hundreds of thousands, so attention dominates and a few seconds of video can take minutes on one GPU.
The product decides the engineering targets. A coding agent, a consumer chat app and an overnight document pipeline need very different latency, cost and reliability trade-offs from the same model.
Products such as agents, copilots and voice assistants built around model calls, often chaining many per user action. Latency compounds across steps, so per-call TTFT and caching matter a lot.
Consumer apps have spiky, unpredictable traffic and thin margins per user; B2B workloads are steadier, contract-bound to SLAs and often need data residency or dedicated deployments.
Models that generate long hidden chains of thought before answering, multiplying output tokens by ten or more. Decode throughput and long-context KV cache capacity become the main costs.
Before optimising, find out whether a workload is limited by compute, memory bandwidth, memory capacity or communication. A few lines of arithmetic about FLOPs and bytes moved usually predict performance surprisingly well.
FLOPs performed per byte moved from memory for an operation. Matrix multiplies at large batch are high; decoding one token at batch size one is very low.
A GPU’s peak FLOPs divided by its memory bandwidth. If an operation’s arithmetic intensity is below this ratio, it is memory bound and more FLOPs will not help.
A plot of attainable performance against arithmetic intensity, capped by bandwidth on the left and peak compute on the right. Shows at a glance which limit an operation hits.
Decode is bound by reading weights and KV cache every step, prefill by compute, and long contexts by KV memory capacity. Batching, quantisation and attention kernels each attack a different one.
Diffusion is compute bound: many denoising steps over large latents, with attention cost exploding for video. Fewer steps, caching between steps and lower precision help most.
The cheapest optimisation is serving a smaller model that is good enough. Pick models against your own evaluation set, then adapt or compress them for your task.
Weigh quality on your task against parameter count, context length, licence, architecture support in your engine and hardware fit. A well-tuned 8B model often beats a generic 70B on a narrow task.
Build a task-specific test set and score candidates automatically, with an LLM judge or exact checks, plus public benchmarks for sanity. Re-run it after every quantisation or engine change.
Adapting a base model to your data. LoRA adapters train a small number of extra weights and can be served many-at-once on one base model.
Train a smaller student to imitate a larger teacher’s outputs or logits, keeping much of the quality at a fraction of the inference cost.
Attention is where long contexts become expensive in both compute and memory. Fused kernels, better memory management for the KV cache, and architectural variants with fewer KV heads all reduce that cost.
An exact attention kernel that tiles the computation in on-chip SRAM so the full attention matrix is never written to HBM. Faster and far more memory efficient; versions track new GPU generations.
Stores the KV cache in fixed-size blocks like virtual memory pages, removing fragmentation and enabling prefix sharing. The core idea behind vLLM’s high batch sizes.
Multi-query and grouped-query attention share keys and values across heads; multi-head latent attention compresses them; sliding-window attention bounds context. All shrink the KV cache.
GPUs are throughput machines: thousands of cores, tensor cores for matrix maths and high-bandwidth memory. Knowing compute, memory and interconnect numbers for a chip lets you predict how a model will run on it.
Streaming multiprocessors with tensor cores deliver dense matrix FLOPs at FP16, BF16, FP8 and FP4. Lower precision roughly doubles peak throughput per step down.
HBM capacity limits model size plus KV cache per GPU; HBM bandwidth limits decode speed. On-chip SRAM and L2 are tiny but much faster, which is what fused kernels exploit.
GPUs inside a node talk over NVLink at hundreds of GB/s; nodes talk over InfiniBand or RoCE at much less. Tensor parallelism should stay inside the NVLink domain.
Estimate memory for weights plus KV cache at target concurrency, then throughput per GPU, to get GPU counts. Compare on-demand, reserved and spot pricing across providers.
NVIDIA’s H100 and H200 generation: FP8 tensor cores with the Transformer Engine, 80 to 141 GB of HBM, and fourth-generation NVLink. The current baseline for LLM serving.
The B200 and GB200 generation adds FP4 tensor cores, more HBM and rack-scale NVLink domains of up to 72 GPUs, which favours large MoE models with wide expert parallelism.
NVIDIA’s Arm data-centre CPUs, paired with GPUs over a coherent high-bandwidth link in Grace Hopper and Grace Blackwell superchips; Vera is the successor CPU. Useful for offloading KV cache to CPU memory.
Which accelerator to rent or buy depends on memory per chip, bandwidth, low-precision support and software maturity. NVIDIA dominates the software ecosystem, but alternatives can win on price or availability.
From L4 and L40S for small models and diffusion, through A100 and H100, to B200. Match memory and bandwidth to model size, and check which precisions each generation accelerates.
AMD Instinct with ROCm, Google TPUs, AWS Inferentia and Trainium, and specialised chips from Groq or Cerebras. Check your engine and model support before chasing lower prices.
Running models on laptops, phones and devices gives privacy, offline use and zero per-request cost, within tight memory and power budgets. Aggressive quantisation and small models make it practical.
llama.cpp with GGUF quantised models, Ollama on top of it, and MLX on Apple silicon run multi-billion parameter models locally, limited mostly by unified or VRAM memory.
Core ML on iOS and LiteRT or ExecuTorch on Android run small quantised models on the phone’s NPU or GPU. Watch battery, heat and app download size.
CUDA is NVIDIA’s programming model for GPUs: kernels run across a grid of thread blocks with explicit control of shared memory. Most inference engineers read and choose kernels more than write them, but knowing the model explains every performance trick.
Fusing operations such as normalisation, activation and quantisation into one kernel avoids round trips to HBM. torch.compile, CUDA graphs and engine-specific kernels do much of this automatically.
When no library kernel fits, Triton lets you write fast GPU kernels in Python-like code; CUTLASS and raw CUDA give full control for matrix maths at the cost of complexity.
Models are defined and loaded with deep learning frameworks before an inference engine takes over. Even when you serve with a dedicated engine, you will prototype, debug and verify outputs in these libraries.
The dominant framework for model code. For inference, know torch.inference_mode, mixed precision, torch.compile and CUDA graphs, and how to profile a forward pass.
Hugging Face’s reference implementations for language and diffusion models. Easy to run any checkpoint, but not optimised for high-throughput serving.
How weights are stored and which runtime executes them. Portable formats and compiled runtimes trade flexibility for load speed, safety or raw performance on specific hardware.
A simple, safe tensor file format that cannot execute code on load, unlike pickle, and supports zero-copy memory mapping for fast startup. The default on Hugging Face Hub.
Runs models exported to the ONNX graph format across CPUs, GPUs and NPUs through execution providers. Strong for classic, encoder and edge models.
NVIDIA’s compiler that builds an optimised engine for a specific GPU, with layer fusion, kernel auto-tuning and INT8 or FP8 precision. Engines must be rebuilt per GPU type.
Serving engines implement continuous batching, paged KV cache, quantised kernels and an OpenAI-compatible API, so you rarely build these yourself. Benchmark the engines on your own model and traffic, since rankings change with every release.
Popular open-source engine with broad model and hardware support, PagedAttention, prefix caching, speculative decoding and LoRA serving. vllm serve <model> gives an OpenAI-compatible server.
High-performance engine with RadixAttention for automatic prefix reuse, fast structured output and strong support for large MoE models across many GPUs.
NVIDIA’s LLM engine with heavily tuned kernels, FP8 and FP4 support and in-flight batching. Often fastest on NVIDIA hardware, with more setup than vLLM.
Benchmarks tell you whether a change helped; profiles tell you why. Use realistic prompt and output length distributions and concurrency levels, and sweep load until latency targets break.
Measure TTFT, inter-token latency and throughput across a sweep of concurrency, and plot latency against throughput. Fix input and output lengths, warm up, and repeat runs.
PyTorch Profiler and Nsight Systems show where time goes per kernel and between kernels; gaps often reveal CPU overhead, synchronisation or tiny unfused ops.
NVIDIA’s open-source load generator for OpenAI-compatible endpoints, reporting TTFT, inter-token latency and throughput under configurable concurrency and request rates.
General-purpose Python load-testing tool. Write user behaviour as code to test the full service, including auth, routing and autoscaling, not just the engine.
A benchmarking tool from the SGLang project for token-level serving metrics across scenarios, with reports and plots for comparing engines and settings.
Storing weights, activations or KV cache in fewer bits shrinks memory and speeds up memory-bound decoding. FP8 is nearly free in quality on modern GPUs; INT4 and FP4 need careful calibration and evaluation.
Quantise a finished model using a small calibration set, with methods such as GPTQ, AWQ or SmoothQuant. Fast and cheap, and the default approach for serving.
Simulate low precision during training or fine-tuning so the model learns to tolerate it. Recovers quality at very low bit widths, at the cost of a training run.
Compare the quantised model with the original on your task evals and on perplexity, not just a demo prompt. Damage often shows up first in maths, code and long contexts.
NVIDIA Model Optimizer applies FP8, FP4 and INT4 quantisation, sparsity and distillation, and exports checkpoints for TensorRT-LLM, vLLM and SGLang.
Decoding leaves the GPU underused, so a cheap method proposes several tokens and the big model verifies them in one pass. Accepted tokens are guaranteed identical to normal sampling; speed-ups depend on the acceptance rate.
A small draft model from the same family generates candidate tokens that the target model checks. Works best when the draft agrees often and shares a tokenizer.
Trains a lightweight head on the target model’s hidden states to predict future tokens, giving higher acceptance than a separate draft model with little extra memory.
Proposes tokens by matching recent n-grams against the prompt, with no extra model. Very effective when outputs copy from inputs, as in code editing or summarisation.
Forcing output to match a JSON schema, regex or grammar so it always parses. Engines expose it as response_format or guided decoding parameters.
The mechanism behind structured outputs: mask invalid tokens at each step using a grammar automaton. Fast backends like XGrammar keep the overhead to a few percent.
Many requests share long prefixes such as system prompts, documents or chat history. Reusing their KV cache instead of recomputing prefill cuts TTFT and cost dramatically.
Prefix caching reuses KV blocks for identical prompt starts; RadixAttention organises them in a tree. Put stable content first in prompts so caches hit.
Offload KV cache from GPU memory to CPU RAM, local SSD or a shared store so more context survives between turns. LMCache and Mooncake implement tiered stores.
Send a request to the replica that already holds its prefix in cache, balancing hit rate against load. Round-robin routing throws most prefix reuse away.
Long contexts need large KV memory and quadratic prefill. Chunked prefill, context parallelism, KV quantisation and RoPE scaling methods such as YaRN keep them workable.
When a model or its KV cache does not fit on one GPU, or one GPU is too slow, the model is split across several. Each split has a different communication pattern and should match your interconnect.
Split each layer’s weight matrices across GPUs, with an all-reduce after each layer. Cuts latency but needs fast NVLink, so keep it within a node.
Place consecutive layers on different GPUs or nodes and pass activations along. Light on bandwidth and fine across nodes, but adds latency and needs enough in-flight work.
Spread MoE experts across GPUs and route tokens to them with all-to-all communication. Essential for very large MoE models such as DeepSeek-V3.
Serving one model instance across several machines over InfiniBand or RoCE. Needs a launcher such as Ray or Kubernetes LeaderWorkerSet and careful fault handling.
Running prefill and decode on separate GPU pools so each can be sized and tuned for its own bottleneck, transferring the KV cache between them. It improves goodput at scale but adds network and orchestration complexity.
An open-source distributed inference framework that sits above engines like vLLM, SGLang and TensorRT-LLM, adding disaggregated serving, KV-aware routing and KV cache transfer.
VLMs add a vision encoder whose image features become extra tokens for the language model. Images can add thousands of tokens each, so encoding cost and prefill length dominate their serving.
Sample frames at a chosen rate and resolution and merge tokens across time to keep token counts manageable. Frame sampling choices trade accuracy against cost.
Single models that take text, images, audio and video and may answer in text and speech, streaming both. Serving them combines LLM, vision and speech concerns.
Embedding models turn text or images into vectors for search, retrieval and clustering. Requests are short and need no decoding, so throughput and batching matter far more than streaming latency.
Small encoder-only models with bidirectional attention, pooled into one vector. Cheap to serve on CPUs or small GPUs, with context usually limited to a few hundred tokens.
Embedding models built on decoder LLMs with billions of parameters, top of retrieval leaderboards and supporting long inputs, at much higher serving cost.
Batch aggressively, sort by length to reduce padding, use FP16 or INT8, and cache repeated inputs. Text Embeddings Inference and vLLM both serve them efficiently.
Voice products chain detection, recognition, a language model and synthesis, and users notice delays of a few hundred milliseconds. Streaming at every stage is what makes conversation feel natural.
Detects when someone is speaking so you only transcribe speech and know when a turn ends. A small, fast model such as Silero VAD runs on CPU.
Turns audio into text. Whisper-family models dominate open source; faster-whisper and batched or streaming variants cut latency and cost.
Generates audio from text, often as an LLM predicting audio codec tokens followed by a decoder. Quality, voice cloning and time to first audio are the main trade-offs.
Starts playing audio from the first words while the rest is still generated and while the LLM is still writing. Time to first audio chunk is the metric that matters.
End-to-end models that listen and speak directly without a text pipeline, enabling interruptions and low latency, at the cost of harder control and evaluation.
Serving diffusion models is about cutting steps and per-step cost while keeping output quality. Requests are long and compute heavy, so queueing and asynchronous delivery are normal.
Use BF16 or FP8, torch.compile, fused attention, fewer steps with distilled models and caching of features between steps. Batch by resolution.
Very long sequences make attention the bottleneck; sequence parallelism across GPUs, sparse or sliding attention and step caching bring generation times down from tens of minutes.
Inference images bundle CUDA, drivers’ user-space libraries, an engine and model loading logic, and they are large. Reproducible builds and fast image and weight pulls directly affect deploy speed and cold starts.
Pin CUDA, PyTorch, engine and kernel versions together, since mismatches fail at runtime. Use a lockfile with a fast resolver such as uv, and keep weights out of the image.
NVIDIA Inference Microservices are prebuilt containers that pick an optimised engine profile for your GPU and expose a standard API. Quick to deploy, but tied to NVIDIA licensing.
GPU capacity is expensive and traffic is bursty, so replicas must follow demand. Scale on queue depth or in-flight requests rather than GPU utilisation, and plan around slow model loading.
Adds and removes requests from the running batch at every decode step instead of waiting for a whole batch to finish. The single biggest throughput win in LLM serving.
Time to pull the image, download weights and load them to GPU, often minutes. Cut it with cached weights on local NVMe, memory-mapped safetensors, smaller images and warm pools.
Route by real load such as queue length and KV cache usage, not round robin. LLM-aware gateways also consider prefix cache hits and model or adapter placement.
When replicas serve many LoRA adapters, send requests to replicas that already have the adapter loaded to avoid swap-in latency.
A queue in front of engines absorbs bursts, enforces priorities and fairness between tenants, and provides the signal autoscalers should scale on.
Removing all replicas when idle saves money for rarely used models, at the cost of a cold start on the next request. Knative and KEDA support it on Kubernetes.
Scale each part, such as tokenisation, vision encoders, prefill and decode, separately according to its own load rather than as one monolith.
GPU supply is limited in any one region or provider, so serious inference fleets span several clouds and regions. That buys capacity and resilience, but complicates networking, data movement and operations.
Mix hyperscalers, GPU clouds and reserved contracts; compare price per useful token, not per hour, and check interconnect and availability guarantees.
Forecast demand, keep headroom for peaks and failures, and shift batch work to off-peak or spot capacity. Track utilisation per GPU type and region.
Route users to the nearest healthy region with capacity, spilling over when it saturates, while respecting data residency rules.
Shipping a new model, engine version or config safely means testing quality and performance before rollout, rolling out gradually, and watching cost and latency afterwards.
Isolate tenants, protect weights and prompts in transit and at rest, log carefully around personal data, and guard against prompt injection and other LLM-specific threats.
Bring new replicas up and warm them before draining old ones, let in-flight streams finish, and canary new models on a slice of traffic with automatic rollback.
Divide GPU cost per hour by tokens per hour at your latency target to get cost per million tokens, then add idle capacity and overhead. Compare with API pricing honestly.
Export TTFT, inter-token latency, queue depth, KV cache usage, batch size and error rates to Prometheus, and trace requests through gateway and engine.