Inference Engineering
contents
1. what inference actually is
You finished training. You have a 16 GB blob of weights sitting on disk: 8 billion learned numbers, 2 bytes each. A user types a prompt. You need to:
- load the weights into GPU memory
- run the prompt through the model to get a probability distribution over the next token
- pick one token, append it, repeat until done
That last loop is the painful part. Each output token = another full pass through the model. A 100-token reply = 100 sequential forward passes. Token N+1 depends on token N, so you can't parallelize this.
the iron triangle
Three things you trade off:
- Latency is how fast one user sees output
- Throughput is how many users per second one GPU serves
- Cost is $/million tokens
A batch is a group of user requests that go through the model together, in the same forward pass. At batch=1, an H100 (NVIDIA's data-center GPU) pushes ~200 tok/s from an 8B model. At batch=128: ~25,000 tok/s. Same GPU, same hourly rate. Per-token cost drops ~125x. Section 3 shows why it's that cheap. But past a point, more batching = each user waits longer.
The serving game: pack as many concurrent requests onto each GPU as you can without pushing latency past your SLO (service level objective). An example SLO is "P99 TTFT under 500ms": 99% of requests get their first token within 500ms. Section 4 defines TTFT (time to first token) and the other metrics. Every technique below lets you pack more requests or makes each one faster. That is the whole idea.
2. GPU 101 - the hardware vocab
A few terms first. Every optimization below moves data between different kinds of memory.
VRAM and HBM - same thing, two names
Your CPU has RAM. The GPU has its own separate memory called VRAM. On AI GPUs, VRAM uses a technology called HBM (High Bandwidth Memory). "HBM" and "VRAM" mean the same thing in this post: the GPU's main memory pool.
- H100 has 80 GB of HBM
- Separate from CPU RAM. Data copies over PCIe, the CPU-to-GPU bus (slow)
- HBM bandwidth: ~3 TB/sec on H100. This number limits decode, the one-token-at-a-time loop from section 1 (more in section 3).
SRAM - the GPU's tiny on-chip cache
The GPU chip also has tiny pools of much faster memory called SRAM (shared memory / L1 cache). Each compute unit, a streaming multiprocessor (SM), has ~256 KB. An H100 has 132 SMs.
- Faster than HBM. The FlashAttention paper estimates ~19 TB/s of SRAM bandwidth on an A100, the GPU before the H100.
- ~2400x smaller in total (132 SMs x 256 KB = ~33 MB vs 80 GB)
- FlashAttention (section 6) does as much work as possible in SRAM before it touches HBM.
Think of a kitchen. The compute units are a cook who chops fast. SRAM is the cutting board: tiny, but right under the knife. HBM is the fridge in the next room. It holds everything, but every trip takes time. CPU RAM is the shop down the road.
memory bandwidth - the number that matters
How fast data moves between memory and compute. On an H100:
- Compute: ~1000 TFLOPS (trillion 16-bit floating-point operations per second)
- HBM bandwidth: ~3 TB/sec
That ratio is ~300 ops per byte. In kitchen terms, the cook can chop 300 times in the time it takes to bring one ingredient from the fridge. If a recipe needs only 10 chops per ingredient, the cook stands around for the other 290. That's decode. Welcome to memory-bound.
tensor cores
Specialized units that do small matrix multiplications fast. Busy during prefill (prompt processing, compute-bound), idle during decode (memory-bound). Section 3 covers both phases.
3. prefill vs decode
Two phases with different bottlenecks.
prefill
Your prompt has 500 tokens. The model processes all 500 at once: one big matrix (prompt embeddings) times another big matrix (weights). Tensor cores light up. Every multiply-add unit does useful work.
Compute-bound. FLOPS set the speed. Prefill time sets TTFT (time to first token). Long prompt = long prefill = user waits.
decode
Now you're generating. You have one token. You multiply its hidden state (a tiny vector of numbers that stands for the token inside the model) by the entire 16 GB of model weights to predict the next token.
The math is trivial: a vector-matrix multiply. The pain is memory. The GPU reads all 16 GB from HBM for that one tiny computation. Then does it again for the next token. And again.
Think of the model as a 16 GB lookup table. Every new token reads the whole table. That's also why batching is so cheap. Put 128 users in the same step and the GPU still reads the 16 GB once, then uses each weight 128 times instead of once. The read is the slow part, so 128 users cost about as much as one. That's the ~125x from section 1.
Why memory-bound? Remember the ~300 ops-per-byte ratio from section 2. Decode does far fewer than 300 ops per byte read, so the GPU sits idle and waits for memory.
Memory-bandwidth-bound. More compute doesn't help. Only reading less from memory helps. Decode time sets TPOT (time per output token).
Batching stays cheap while the read is the slow part. Grow the batch until decode does more than ~300 ops per byte read, and compute becomes the slow part. Then each step takes longer, and each user waits longer.
Prefill and decode have different bottlenecks. More FLOPS help prefill but not decode. Less memory traffic and bigger batches help decode but not prefill. Production systems treat them as two separate problems.
4. the metrics that matter
Four numbers. If you can't recite these about your deployment, you don't understand it.
TTFT (Time To First Token). Request arrival to first character visible. Driven by prefill + queuing. Anything > 1s feels laggy. Target < 500ms P99 for chat.
TPOT (Time Per Output Token). Gap between consecutive tokens during decode. Some tools call it ITL (inter-token latency). Driven by HBM bandwidth + batch size. < 50ms feels smooth (~20 tok/s). Agent loops can tolerate < 100ms.
Goodput. Requests/second that meet your SLO. Raw throughput is misleading: 1000 req/s means nothing if half miss the latency target.
MFU (Model FLOPS Utilization). Fraction of peak FLOPS you use. Training hits 40-60%. Inference hits 10-30%. That's normal, because decode is memory-bound.
Averages lie. One slow request in ten makes an app feel broken. Track P50, P95 and P99, never the mean. In a chat app with a million daily active users (DAU), the slowest 1% of requests means at least 10,000 unhappy users.
5. the KV cache
The KV cache is the main data structure in LLM inference.
why it exists
Attention, briefly: Transformers use attention. For every token, the model computes three vectors: a Query (Q, what this token is looking for), a Key (K, what it contains) and a Value (V, what it passes on). A new token compares its query with the key of every earlier token, and the best matches pass on their values. A layer runs several of these side by side, and each one is a head. You do not need the math here. One fact matters.
To generate token N, attention looks at the K and V of every previous token (1 through N-1).
Without a cache, you'd recompute K and V for every previous token at every step. Generating the 100th token = redoing work for tokens 1-99. 99% wasted compute.
The fix: K and V for a token never change once computed. Compute them once and cache them in HBM. That cache (one entry per token, per layer, per attention head) is the KV cache. Just memoization.
why it dominates memory
The KV cache grows with every token. Each token leaves one K vector and one V vector, d numbers each, in every KV head of every layer, for every user in the batch. The formula counts those numbers and multiplies by their size:
B = batch, L = layers, = KV heads (the heads that store K and V, often fewer than all heads, see below), d = numbers per vector, N = tokens so far, bytes = size of one number. The 2 is for storing both K and V.
Plug in Llama 70B (L=80, =8, d=128) at FP16 (16-bit floats, 2 bytes each), one user, 32K context (N = 32,768 tokens):
That's per user. Bump to batch=32: 344 GB. Llama 70B itself is only 140 GB.
The KV cache is the memory bottleneck. Every technique that fits more requests on a GPU comes down to a smaller KV cache.
how to fight it
Three levers, in order of frequency:
- PagedAttention removes wasted reservation (section 7.1)
- Prefix caching reuses the cache across requests with shared prefixes (section 7.4)
- KV cache quantization stores K, V in 8-bit INT8/FP8 instead of FP16 (section 8). Halves memory. < 0.5% quality loss.
In vLLM, the serving engine from section 7, KV quantization is one flag:
# turn on KV quantization in vLLM
llm = LLM(
model="meta-llama/Meta-Llama-3-70B",
kv_cache_dtype="fp8", # half the KV memory
gpu_memory_utilization=0.90,
)MHA / MQA / GQA / MLA
These are four ways for a layer's heads to share K and V. You don't choose this. The model architect did. But it explains why two similar-sized models can have 10x different KV cache sizes:
| Variant | What it shares | Used by |
|---|---|---|
| MHA (multi-head attention) | Nothing. Each head has its own K, V (original transformer) | GPT-2 |
| MQA (multi-query attention) | All heads share one K, V pair. Aggressive savings. | PaLM |
| GQA (grouped-query attention) | Heads share K, V in groups of 4-8. Sweet spot. | Llama 2 70B, Llama 3, Mistral, Qwen |
| MLA (multi-head latent attention) | Squeezes each token's K and V into one short vector, and expands it back when attention needs it. 93% smaller KV cache than DeepSeek 67B. | DeepSeek V2/V3 |
6. FlashAttention
You'll never write this yourself. But it's why long-context inference works at all.
the problem
Standard attention scores every query against every key: S = Q x K^T. That's an N x N matrix per attention head. In FP16, at N=4K it takes 32 MB. At N=128K it takes 32 GB, bigger than most GPUs.
The naive algorithm writes the full matrix to HBM, reads it back, applies softmax (which turns each row of scores into weights that add up to 1), writes again, reads again, multiplies by V. Four HBM trips (two writes, two reads) for a matrix that the next step reads once and throws away.
the fix (Dao et al., 2022)
Never build the full matrix. Do all the chopping on the cutting board (SRAM), and never put the half-chopped matrix back in the fridge (HBM). Instead:
- Tile Q, K, V into blocks that fit in SRAM
- For each Q block, iterate over K, V blocks. Compute attention scores in SRAM, never writing the intermediate matrix to HBM
- Online softmax. Softmax needs the biggest score in the row and the sum over the row, which looks like it needs every score first. Online softmax keeps a running max and a running sum instead, and rescales the sum whenever a bigger score shows up. The result is exact
The extra memory now grows with N instead of N x N. Double the context and it doubles, instead of growing 4x. Same exact output, far fewer fridge trips. At long context, this is the difference between a working model and an out-of-memory (OOM) crash.
vLLM and SGLang (serving engines, section 7) and PyTorch's scaled_dot_product_attention turn it on by default. You don't configure it.
7. vLLM's superpowers
What's vLLM? The most popular open-source LLM serving engine. Think nginx for language models: point it at a model and get a high-throughput inference server. SGLang and TGI (Hugging Face's Text Generation Inference) are alternatives. All three bundle the four optimizations below.
Together these four give 5-10x throughput over a naive Hugging Face .generate() loop. All configurable, and at scale you'll tune them.
7.1 - PagedAttention (OS virtual memory for the KV cache)
Naive KV cache allocation: reserve max possible context length per request. Model supports 128K context? Reserve gigabytes. Even if the user sends "hi".
Think of notebooks. The naive way hands every request a notebook with room for 128K tokens before it writes a word. PagedAttention hands out one small page (16 tokens) at a time as the request writes, and keeps a table of contents that says where each page sits. If you've taken an operating systems (OS) class, you know this story: it's virtual memory.
- Split VRAM into fixed-size blocks (16 tokens each by default)
- Allocate on demand as the sequence grows
- Block table maps logical positions to scattered physical blocks (like OS page tables)
- With copy-on-write, two requests that share a system prompt share the same physical blocks. vLLM forks a block only when they diverge.
PagedAttention is vLLM's whole reason for existing. It is on by default. It explains why vLLM packs 2-3x more requests per GPU than a naive setup.
7.2 - continuous batching
Static batching: collect N requests, pad to same length, process as one batch, return together. Short responses sit idle waiting for the longest. Massive waste.
Continuous batching checks at every decode step if any request finished. If one did, the scheduler evicts it and slots in a new request from the queue.
Software engineering (SWE) analogy: static batching is a thread-per-request server that waits for the slowest connection. Continuous batching is an event loop. It admits new work as soon as a slot opens.
Watch it run. Eleven requests arrive over time; the scheduler admits up to 6 at once into the KV cache. Prefill is one step, decode is many.
7.3 - chunked prefill
Continuous batching still has a gap. A long prompt enters the queue, and its 500ms prefill stalls every decode-phase request in the batch. Latency spikes for everyone.
Chunked prefill breaks long prefills into chunks (e.g. 512 tokens) and interleaves decode steps between them. The long prefill still finishes. But no one else's TPOT spikes.
SWE analogy: preemptive scheduling. No single process starves the others.
7.4 - prefix caching
Most production traffic shares prefixes: same system prompt, same few-shot examples, same RAG (retrieval-augmented generation) context. Without caching, every request recomputes KV for the shared prefix. Thousands of tokens of duplicate work.
Automatic prefix caching stores KV blocks keyed by token content. This is the block sharing from 7.1, done for you. vLLM finds the matching blocks by their tokens. New requests with a matching prefix reuse the cached blocks and skip that part of prefill. TTFT drops to near-zero for the shared part.
# all four optimizations in vLLM
from vllm import LLM, SamplingParams
llm = LLM(
model="Qwen/Qwen3-8B-AWQ",
quantization="awq", # section 8 - 4-bit weights
enable_prefix_caching=True, # 7.4 - reuse shared prefixes
enable_chunked_prefill=True, # 7.3 - long prompts stop stalling decode
max_model_len=4096,
gpu_memory_utilization=0.90,
# PagedAttention (7.1) and continuous batching (7.2) are always on
)8. quantization
why it works
Weights default to FP16/BF16 (two 16-bit float formats): 16 bits per number. A 70B model = 70 billion x 2 bytes = 140 GB.
Quantization: store those numbers in fewer bits. INT4 = 4 bits = 35 GB for the same model. 4x less memory, 4x less bandwidth consumed during decode.
Decode is memory-bound. Read 4x less from HBM and generation runs up to 4x faster.
How is quality measured? Perplexity measures how "surprised" the model is by held-out text (text it never saw in training). Lower is better.
Won't quality crash? Not down to 4 bits. Weights have redundancy. 8-bit raises perplexity by < 1%. 4-bit raises it ~5%, and users do not notice that. Below 4-bit, the model breaks.
how it works
The simplest version: symmetric (absmax) quantization. You have a tensor (a block of numbers, like one weight matrix) of FP16 weights. You want INT8 (8-bit integers).
Picture a ruler that runs from minus the largest weight to plus the largest weight. For INT8 it has 255 evenly spaced marks, numbered -127 to 127. Each weight snaps to its nearest mark, and you store the mark's number (1 byte) instead of the weight (2 bytes). In math:
- Find the largest absolute value in the tensor:
- Compute a scale factor: where b = target bits (8 for INT8, so you're mapping to [-127, 127])
- Quantize:
- At inference, dequantize:
The scale s is the gap between two marks. The rounding introduces error, but it's tiny per-weight and averages out across billions of parameters.
the outlier problem
Weights are the fixed numbers in the model file, like the 16 GB from section 1. Activations are the numbers that flow through the model for the current prompt, like the hidden state in section 3. Each slot in that vector is a dimension.
Symmetric quantization works well for vision models (ResNet quantizes to INT8 with near-zero quality loss). Transformers are harder.
The problem: ~0.1% of activation dimensions produce values 10-100x larger than the rest. When you compute the scale factor, those outliers stretch the integer range. Every non-outlier value gets squeezed into a tiny band and loses precision. One extreme value ruins thousands of normal values.
Example: your activations range from [-1, 1] except one dimension hits 50. That one value stretches the ruler to run from -50 to 50, so the marks now sit 50/127 apart. Your [-1, 1] values land on 7 marks (-3 to 3) instead of 255. Most of your information is gone.
This is why naive per-tensor INT8 fails for large language models and why the techniques below exist.
techniques you'll see on HuggingFace
Everything below is post-training quantization (PTQ): train in FP16, quantize after.
GPTQ rounds one column of weights at a time. After each column, it nudges the columns it hasn't rounded yet to cancel the error it just made. To know which weights matter most, it runs real inputs X through the layer and looks at (the Hessian). A weight that meets big inputs moves the output more when it gets rounded. Gets 4-bit with minimal perplexity loss.
AWQ (Activation-Aware Weight Quantization) looks at which activations run large. A weight that keeps getting multiplied by a big activation matters more, because its rounding error gets multiplied up too. AWQ protects the ~1% of weights like that. It scales them up before rounding (and their activations down by the same amount), so they lose less. Every weight still ends up in 4 bits. Often slightly better than GPTQ at 4-bit.
SmoothQuant solves the outlier problem for W8A8 (both weights AND activations in INT8). Activations are hard to round because of their outliers. Weights are easy. SmoothQuant divides each activation dimension by a number and multiplies the matching weights by the same number, so the layer's output stays the same. The outliers shrink, and the weights get a bit bigger, which they can take.
Which to pick: for 4-bit weight-only, AWQ or GPTQ (AWQ is the current default). For W8A8 (weights and activations), SmoothQuant or FP8. For zero effort on Hopper GPUs (the H100 generation), FP8.
number formats you'll meet
| Format | Bits | When to use |
|---|---|---|
| FP32 | 32 | Master copy of the weights in training. Don't use for inference. |
| BF16 | 16 | Inference default. Baseline. |
| FP8 | 8 | Hopper+ GPUs. Near-lossless. Zero effort. |
| INT8 (W8A8) | 8 | Weights AND activations in 8-bit. Faster prefill too. |
| INT4 (AWQ/GPTQ) | 4 | Biggest decode speedup. ~5% higher perplexity. |
| INT2/INT3 | <=3 | Model breaks. Research only. |
# FP8 if you have a Hopper GPU
llm = LLM(
model="meta-llama/Meta-Llama-3-70B",
quantization="fp8", # on-the-fly, no separate model
kv_cache_dtype="fp8", # bonus: KV in FP8 too
)9. when one GPU isn't enough
Llama 70B at FP16 = 140 GB. H100 = 80 GB. Doesn't fit. Even at 4-bit (35 GB), production KV cache pushes past 80 GB. You need multiple GPUs.
tensor parallelism (TP) - the one you'll use
Split each weight matrix across GPUs. Each GPU holds 1/N of every weight. At inference time, each computes its slice, then they exchange partial results via AllReduce (every GPU contributes its partial, ends up with the sum).
- AllReduce happens on every layer. Lots of communication.
- Needs NVLink (~900 GB/s, GPU-to-GPU within one box). InfiniBand across nodes is too slow (~50 GB/s).
- Max
TP=8because that's how many H100s fit in one NVLink domain.
Rule of thumb: use the smallest TP that fits your model and KV cache. TP=2 tends to cost less per token than TP=4 for the same model: half the GPUs, and less AllReduce traffic per GPU. TP=4 tends to give a lower TPOT, because each GPU reads a quarter of the weights per step instead of half.
# vLLM with tensor parallelism
llm = LLM(
model="meta-llama/Meta-Llama-3-70B",
tensor_parallel_size=4, # split across 4 GPUs in the same node
gpu_memory_utilization=0.90,
)10. serving the model
vLLM is configured. Now your app talks to it.
the one-line server
vLLM ships an OpenAI-compatible HTTP server:
$ vllm serve Qwen/Qwen3-8B-AWQ \
--quantization awq \
--enable-prefix-caching \
--enable-chunked-prefill \
--tensor-parallel-size 2 \
--max-model-len 4096 \
--port 8000
# now you have an OpenAI-compatible endpoint at localhost:8000"OpenAI-compatible" = any client library that talks to the OpenAI API talks to your vLLM server unchanged. Switch base_url and you're done.
streaming
Wait for the full response = user stares at a spinner for 5+ seconds. Stream tokens via SSE (Server-Sent Events) instead. The server keeps the connection open and pushes tokens as the model generates them. Text appears word-by-word like ChatGPT. In the OpenAI SDK, set stream=True.
tuning
Two knobs:
--max-num-seqs: max concurrent requests in batch. Higher = more throughput + more KV memory + longer TPOT. Start at 64.--max-num-batched-tokens: total tokens per scheduler step. Caps prefill-decode packing.
scaling out
One vLLM process saturates one GPU (or TP group). More traffic = more replicas behind a load balancer. Use least-pending-requests routing instead of round-robin, because LLM request durations vary a lot.
11. the deployment playbook
Latency bad. Throughput bad. Bill bad. Where to start? This order:
- Profile first. The bottleneck might be tokenization, queuing or the network instead of the model. Run
torch.profileror Nsight Systems before you touch anything. - Switch to vLLM/SGLang. If you're on raw
.generate(), start here (section 7). - Quantize. AWQ 4-bit or FP8 (section 8).
- Prefix caching and chunked prefill. Free wins for shared system prompts.
- Right-size the GPU count. Smallest TP that fits.
TP=2beatsTP=4on cost per token. - KV cache quantization.
kv_cache_dtype="fp8"doubles the effective batch size. - Speculative decoding. A small draft model guesses several tokens, and the big model checks them in one forward pass (how it works). 2-3x for predictable outputs. Skip it for creative generation.
- Disaggregate prefill and decode. Separate GPU pools per phase. Worth it at 100+ GPUs.