Inference Engineering
Training vs Inference
AI development has two parts: training and inference. Training - weights are learned and saved. Happens once per model release. Inference - using the saved weights to answer new inputs. Happens on every request, forever.
Making this faster, cheaper, more efficient and more reliable -> Inference Engineering.
Why Generative AI Inference Is Hard
| Classical ML (XGBoost, scikit-learn) | Generative AI | |
|---|---|---|
| Model size | Megabytes | Hundreds to thousands of GBs |
| Output size | Known shape | Unknown length |
| State | Stateless | Stateful (KV cache) |
| Scaling | Replicate on another machine | Needs specialised hardware and optimisation |
Unpredictable output length -> you cannot know compute, time or batch size in advance. Stateful -> the KV cache is read and appended on every token, so it must be maintained across the request. (Extra overhead) Unpredictability + statefulness make inference hard.
Prefill and Decode
Every request is forward passes. Two phases:
- Prefill - process all input tokens at once, build the KV cache. Runs once. Produces the first output token. Compute bound.
- Decode - one forward pass per new token, reuse the KV cache and append the new token's K and V. Loops until stop or max tokens. Memory bound.
Why: prefill speed depends on how fast you can process many tokens (compute). In decode the KV cache keeps growing and hits the memory limit (memory).
Three Layers and API vs Own GPUs
- Runtime - is the model using everything the GPU can give?
- Infrastructure - enough capacity? how are requests handled and shared across servers?
- Tooling - are the team's tools adequate?
Before running your own models, evaluate if dedicated GPUs are viable versus a shared API.
- API: they handle the backend, you send input and get output.
- Own GPUs: GPU, tooling, infra and optimisation are your headache and need dedicated staff.
- Worth it only with enough customers to cover cost.
Inference Metrics
- TTFT (time to first token) - time to produce the first token. Includes prefill.
- TPS (tokens per second) - rate after the first token, set by decode.
- Perceived TPS - per user.
- Total TPS - everything the whole service emits across all GPUs (throughput).
- Inter-token latency - interval between consecutive output tokens.
Two views to measure:
- Inference-only time - time the model spends on the GPU. Can be improved only to a limit.
- End-to-end - what the user sees from the full API and infrastructure.
Model Facts That Matter: Attention, KV Memory, MoE
Transformer block: MLP holds most of the parameters. Attention is the most expensive operation in inference.
Example
A 13B model with 8000 tokens needs ~7 GB of KV cache per sequence. The weights are 26 GB. This is the memory problem.
Mixture of Experts (MoE) - the MLP is replaced by many small expert blocks chosen by a small router, trained during training.
- Example: 235B total parameters, 22B active.
- Only part of the model runs for one request.
At batch size 1, MoE is a big win (e.g. 8 of 128 experts active). At large batch (e.g. 100), different requests pick different experts, so nearly all are active and the benefit disappears.
Autoregressive models generate token by token. Image and video models are mostly diffusion models using iterative denoising.
GPU Hardware
CPU - complex computations, sequential. GPU - very simple operations, blazingly fast across thousands of data elements. Models are matrix multiplications, a uniform operation. Perfect fit. (Originally made for graphics)
A GPU has streaming multiprocessors (SMs) instead of CPU cores. H100 has 132 SMs. Inside each SM:
- CUDA cores - scalar operations
- Tensor cores - matrix (tensor) operations, most important for AI
- SFU (special function units) - sin, cos, log, softmax
- L1 / shared memory - SRAM
Memory hierarchy:
- SRAM (L1, L2) - very fast, very small. Closer to the processing means faster fetch. L1 is closest and smallest.
- DRAM = VRAM = HBM (high bandwidth memory) - large, high throughput, slower than SRAM.
Sizing GPUs and the Compute-Memory Balance
- At FP8, roughly 1 GB of VRAM per billion parameters.
- VRAM must hold the full model plus at least ~50% headroom for KV cache.
- A single GPU cannot hold DeepSeek V3; it needs at least four. At 30-40k USD each, roughly 200k USD.
- Compare with the API price: buy hardware only if you serve enough requests.
A GPU has two resources: compute (FLOPs) and memory bandwidth. Operations-to-byte ratio - FLOPs the GPU must perform per byte fed to keep both busy.
Arithmetic intensity - FLOPs the workload actually performs per byte moved. Below the hardware ratio -> memory bound (decode). Above -> compute bound (prefill). Inference engineering tries to keep both resources busy.
Why Standard Attention Is Expensive
Q, K, V are each N x d (e.g. 4096 x 128). S and P are scratchpad intermediates.
- Kernel 1: QK^T -> write S.
- Kernel 2: read S, softmax -> write P.
- Kernel 3: read P, multiply with V -> output. Every step is a round trip to memory. That is why it is expensive.
GPU Generations and Multi-GPU Communication
Letter = generation: H Hopper, B Blackwell, L Lovelace. Rubin comes next. Higher number = better (B300 > B200). Hopper added FP8 support; Blackwell added FP4. A kernel written for H100 may not use B200 well. That is why kernel work exists.
A node holds 8 GPUs connected by NVLink and NVSwitch. Between nodes, InfiniBand (NVIDIA), faster than Ethernet.
The Software Stack
Kernel - just a function that runs on the GPU across many threads. Every model operation (matmul, activation, softmax) is a kernel.
Kernel fusion - combine several kernels into one.
- Example: matmul, add bias, activation as 3 kernels -> one fused kernel. Fewer memory round trips.
Flash attention - fused kernel keeping intermediates in fast SRAM to make fewer round trips to VRAM. Makes compute cheaper. Paged attention - stores KV cache in small blocks instead of one contiguous space, like memory pages. Solves memory fragmentation (e.g. four 250 KB blocks instead of one 1 MB block). Started with vLLM.
Flash attention and paged attention solve different problems: compute round trips vs KV cache memory layout.
Inference engines (vLLM, SGLang, TensorRT) serve models with built-in optimisations and optimised kernels. They are opinionated, so switching is hard.
Speculative Decoding
The Problem LLMs generate one token at a time. Decode is memory bound, so compute sits idle.
The Solution A small draft model guesses 3-4 next tokens. The target model verifies all of them in a single forward pass. Accepted tokens are a free speedup; rejected ones are discarded. Verification is cheaper than generation, like checking a Sudoku answer vs solving it.
One rejection kills everything after it.
- Draft cost - must be very cheap.
- Draft length - short and confident beats long and wrong.
- Acceptance rate - fraction of drafted tokens accepted; shows how well it works.
| Method | How drafts are made |
|---|---|
| Draft-target | Separate smaller model |
| Medusa | Extra output heads on the target model |
| Eagle | Extra trained head on the final layer |
| N-gram | No model; dictionary from seen tokens, statistics only |
Other techniques to study yourself: batching, quantization, KV cache reuse, prefix caching.
Glossary
- Inference
- Using trained, fixed weights to answer new requests.
- Prefill
- First forward pass that processes all input tokens and builds the KV cache. Compute bound.
- Decode
- Per-token generation loop reusing the KV cache. Memory bound.
- TTFT
- Time to first token.
- SM
- Streaming multiprocessor, the GPU's basic compute unit with CUDA, tensor and special function cores.
- HBM
- High bandwidth memory, the large DRAM that forms VRAM.
- Kernel
- A function that runs on the GPU across many threads.
- Kernel fusion
- Merging several kernels into one to cut memory round trips.
- Paged attention
- Storing the KV cache in small non-contiguous blocks.
- Speculative decoding
- A cheap draft proposes tokens that the target model verifies in one pass.