Inference Optimization and Distributed Training
Large models push hardware to its limits in two different ways. At serving time, the problem is cost and latency: each token is cheap to compute but expensive to produce, because the GPU spends most of its time reading weights from memory. At training time, the problem is size: the model, its gradients and its optimizer state don't fit on one GPU, and the compute would take years on one GPU even if they did.
The techniques for both come from the same four constraints: memory capacity, memory bandwidth, compute, and communication between GPUs. Interviewers like this topic because it tests whether you understand why a technique works, not just its name. "Use quantization" is a mid-level answer. "Decode is memory-bandwidth-bound, so halving weight bytes nearly halves the time per token, but it does little for prefill, which is compute-bound" is a senior one.
We'll cover:
- Where inference time goes, briefly.
- Quantization: weights, activations and the KV cache.
- Batching, from classic dynamic batching to continuous batching for LLMs.
- Speculative decoding, with the math for when it helps.
- The rest of the serving toolbox.
- Distributed training: data parallelism and sharding (FSDP/ZeRO), tensor parallelism, pipeline parallelism, and how they combine.
The detailed arithmetic for GPU memory, FLOPs and fleet sizing lives in Numbers to Know for ML Systems. We'll use its results here.
Where Inference Time Goes
An LLM request has two phases:
- Prefill runs the whole prompt through the model at once. Each weight read from memory is used for every prompt token, so it does hundreds of FLOPs per byte and is compute-bound. It sets the time to first token.
- Decode generates one token per sequence per step. Each step reads every weight but does only 2 FLOPs per parameter per sequence. With a small batch that's a few FLOPs per byte, far below what the GPU could do, so decode is memory-bandwidth-bound. It sets the time per output token.
For Llama-3-8B in BF16 on one H100, a single sequence's decode step reads 16 GB at 3.35 TB/s, about 4.8 ms, while its math would take about 0.016 ms at peak. The GPU's compute is more than 99% idle. Every optimization below either reads fewer bytes per token, produces more tokens per read, or does the compute-bound part more efficiently.
Before naming any optimization, say which phase and which bottleneck it targets. Quantization and speculative decoding attack decode's bandwidth limit. Batching amortizes it. FlashAttention and FP8 compute help the compute-bound parts. Mixing these up is the most common mistake in this area.
Quantization
Quantization stores numbers in fewer bits: 8-bit or 4-bit instead of 16-bit. There are three things to quantize, and they have very different effects.
Weight-Only Quantization
Store weights in INT8 or INT4 and convert them back to BF16 inside the matrix-multiply kernel. The math still runs in BF16, but each weight is read from memory in half or a quarter of the bytes. Since decode time is roughly weight bytes ÷ bandwidth, this speeds decode almost proportionally.
The core idea is a scale factor per group of weights:
import numpy as np
def quantize_int8_per_channel(w): # w: [out_features, in_features]
scale = np.abs(w).max(axis=1, keepdims=True) / 127.0
q = np.clip(np.round(w / scale), -127, 127).astype(np.int8)
return q, scale.astype(np.float16) # store int8 weights + one fp16 scale per row
def dequantize(q, scale):
return q.astype(np.float16) * scale # done on the fly, inside the GEMM kernel
The hard part is outliers. If one weight in a row is 50× larger than the rest, the scale is set by it and every other weight gets only a few distinct levels. Practical methods deal with this:
- Smaller groups: INT4 schemes use one scale per group of, say, 128 weights instead of per row. One FP16 scale per 128 weights adds 16 ÷ 128 = 0.125 bits per weight, so INT4 costs about 4.1-4.25 bits per weight in practice.
- GPTQ quantizes weights one column at a time and adjusts the remaining weights to compensate for the error, using a small calibration set.
- AWQ finds the small fraction of weight channels that matter most (by looking at activation magnitudes) and scales them up before quantization, so they keep more precision.
Weight and Activation Quantization
To speed up the compute-bound parts (prefill, large batches), both inputs to the matrix multiply must be low precision, so the tensor cores run in a faster mode. FP8 on H100-class GPUs doubles peak throughput over BF16 (about 1,980 vs 990 TFLOP/s dense). FP8 keeps a floating-point exponent, so it handles the wide range of activations much better than INT8. For INT8 activations, techniques like SmoothQuant move the hard-to-quantize range from activations into weights first.
KV Cache Quantization
The KV cache often takes more memory than the weights, and every decode step reads all of it. Storing it in FP8 halves both. For Llama-3-70B, KV per token drops from 320 KB to 160 KB, so the same memory holds twice as many tokens, which means roughly twice the batch size and better throughput per GPU.
What It Buys, in Numbers
| Llama-3-70B setup | Weight bytes | Decode step, batch 1 | Notes |
|---|---|---|---|
| BF16, 4 × H100 (TP 4) | 140 GB | 140 ÷ 13.4 TB/s ≈ 10.4 ms | baseline; ~150 GB free for KV |
| FP8, 2 × H100 (TP 2) | 70 GB | 70 ÷ 6.7 TB/s ≈ 10.4 ms | same latency on half the GPUs; FP8 compute for prefill |
| INT4 weights, 1 × H100 | ~38 GB | 38 ÷ 3.35 TB/s ≈ 11 ms | one GPU, but only ~30 GB for KV, so smaller batches |
The INT4 row shows the trade-off clearly: one GPU instead of four at the same per-token latency, but a quarter of the KV memory and compute, so the replica serves fewer concurrent users. INT4 fits low-traffic or latency-sensitive deployments on few GPUs. FP8 is the usual default for high-throughput serving on hardware that supports it.
Quality. FP8 weights and activations are close to lossless for most large models. INT8 weight-only usually is too. INT4 costs a small amount of quality that varies by model and task, and tends to show up first on reasoning, math, code and long-context tasks. Smaller models suffer more than larger ones. The only reliable answer is to run your own evals on the quantized model before shipping it.
Batching
Batching is the biggest single lever for throughput, because a decode step costs about the same whether it serves one sequence or a hundred: the weights are read once either way.
Dynamic Batching for Classic Models
For fixed-size models (a BERT classifier, an image model, a ranker), servers like Triton use dynamic batching: hold incoming requests for up to a few milliseconds, then run whatever has arrived as one batch. Two settings control it: maximum batch size and maximum queue delay.
Say a BERT-base classifier takes 4 ms for a batch of 1 and 8 ms for a batch of 32 on a GPU (illustrative numbers; measure yours). Unbatched, it serves 1 ÷ 4 ms = 250 requests per second per GPU. Batched at 32, it serves 32 ÷ 8 ms = 4,000. With a 5 ms maximum queue delay, the worst-case latency is about 5 + 8 = 13 ms. Sixteen times the throughput for about 9 ms of extra worst-case latency is almost always a good trade.
Why LLMs Need Something Different
Dynamic batching assumes every request in a batch finishes together. LLM requests don't: one answer is 20 tokens, another is 1,000. With static batching (start a batch, run until every sequence finishes), short sequences finish early and their slots sit empty until the longest one is done. If output lengths are spread evenly between 1 and 1,000 tokens, the average sequence uses about half the steps of the longest, so roughly half of the batch's slots are wasted. New requests also wait for the whole batch to finish before they can start.
Continuous Batching
Continuous batching (also called iteration-level or in-flight batching) schedules per step instead of per batch. After every decode step, finished sequences leave the batch and waiting requests join it. The batch stays full, and a new request waits at most one step to start. This is the default in every modern LLM serving engine (vLLM, SGLang, TensorRT-LLM, TGI), and it commonly improves throughput several-fold over static batching.
Two refinements make it work well:
- Chunked prefill. A new request's prefill is a big compute-heavy pass that would stall every decoding sequence for, say, 100 ms. Splitting the prompt into chunks of a few hundred to a few thousand tokens and mixing one chunk into each decode step keeps decode latency smooth. Decode steps are memory-bound and leave compute idle, so a prefill chunk fills that idle compute almost for free.
- A token budget per step. The scheduler caps the total tokens per step (decode tokens plus prefill chunk tokens), which sets the latency of each step. A lower budget means faster, steadier tokens for users; a higher one means more throughput.
Continuous batching only pays off if the KV cache can hold a large, changing set of sequences, which is why it goes together with paged attention (allocating KV memory in small blocks as sequences grow). The serving-system view of both is in Design an LLM Inference System.
The Throughput-Latency Dial
Batch size is a dial, not a free win. From the decode table in the numbers post, Llama-3-8B on one H100 with 2,000-token contexts goes from ~210 tokens per second for one user at batch 1, to ~6,500 total and ~100 per user at batch 64, to ~9,800 total and ~49 per user at batch 200. Pick the largest batch that still meets your per-user speed and time-to-first-token targets. Different products sit at different points: an interactive coding assistant wants fast tokens, while an offline batch job wants maximum throughput (Design an Offline Batch Inference Service).
Speculative Decoding
Batching helps throughput, but it doesn't make a single sequence faster. In fact, it makes each sequence slower. For latency, the bottleneck is that decode reads all the weights to produce just one token per sequence. Speculative decoding gets several tokens out of one read.
How It Works
- A cheap draft proposes the next k tokens. The draft can be a small model from the same family (a 1B model drafting for a 70B model), extra prediction heads on the big model, or even text copied from the prompt.
- The big target model runs one forward pass over all k proposed tokens at once. This is like a tiny prefill: because decode is memory-bound, checking 5 tokens costs about the same as generating 1.
- The target accepts the longest prefix of draft tokens that it agrees with, and then produces one more token of its own from the same pass.
With greedy decoding, "agrees" just means "the target's top token equals the draft token." With sampling, a rejection sampling rule keeps the output distribution exactly the same as the target model's:
def verify(draft_tokens, q_probs, p_probs):
"""q: draft model's distributions, p: target's, one per position (+1 extra for p)."""
out = []
for i, x in enumerate(draft_tokens):
if random() < min(1.0, p_probs[i][x] / q_probs[i][x]):
out.append(x) # accept the draft token
else:
residual = normalize(np.maximum(p_probs[i] - q_probs[i], 0))
out.append(sample(residual)) # correct it, then stop
return out
out.append(sample(p_probs[len(draft_tokens)])) # all accepted: one bonus token
return out
This is the important property to mention: speculative decoding is exact. It changes speed, never the output distribution.
When It Helps
If each draft token is accepted with probability α (assumed independent), the expected number of tokens produced per target pass with k draft tokens is:
E[tokens per pass] = (1 − α^(k+1)) / (1 − α)
Each round costs one target pass plus k draft steps. If a draft step costs a fraction c of a target step, the speedup is E ÷ (1 + k·c). With a draft at 5% of the target's cost (c = 0.05):
| Acceptance α | Draft length k | Tokens per pass | Round cost | Speedup |
|---|---|---|---|---|
| 0.6 | 4 | (1 − 0.6⁵) ÷ 0.4 ≈ 2.31 | 1.2 | ~1.9× |
| 0.8 | 4 | (1 − 0.8⁵) ÷ 0.2 ≈ 3.36 | 1.2 | ~2.8× |
| 0.8 | 8 | (1 − 0.8⁹) ÷ 0.2 ≈ 4.33 | 1.4 | ~3.1× |
Longer drafts give diminishing returns, because each additional token is less likely to survive. Real speedups are commonly in the 2-3× range for latency.
Acceptance rates are high when the text is predictable: code, structured output, summaries and edits that copy from the input, low temperature. They drop for creative writing at high temperature, or when the draft model is poorly matched to the target (a different tokenizer won't work at all without extra machinery).
When It Hurts
Speculative decoding spends extra compute to save bandwidth. That's a great trade when the GPU's compute is idle, which is the case at small batch sizes. At large batches, it isn't. With 200 sequences in a batch and k = 4, the target processes 200 × 5 = 1,000 tokens per pass. For an 8B model that's 2 × 8 × 10^9 × 1,000 = 1.6 × 10^13 FLOPs, about 16 ms at peak, which is no longer cheap compared with the ~20 ms memory-bound step. Rejected tokens are wasted compute. So speculative decoding is mainly a latency optimization for lightly loaded or latency-critical serving, and engines often turn it down or off as the batch grows.
Variants
- Draft model: a small model from the same family. Simple; needs extra memory and must share the tokenizer.
- Extra heads (Medusa, EAGLE-style): small heads trained on top of the target's hidden states predict several future tokens. No separate model, typically better acceptance than a generic small model.
- Prompt lookup / n-gram drafting: propose tokens by matching the recent output against the prompt. Free, and very effective for RAG answers, code edits and anything that quotes its input.
The Rest of the Serving Toolbox
A few more techniques come up regularly. Know what each one targets:
| Technique | What it does | Bottleneck it helps |
|---|---|---|
| Paged attention | allocates KV cache in small blocks as sequences grow | KV memory capacity, so bigger batches |
| Prefix caching | reuses KV cache for shared prompt prefixes (system prompts, documents, conversation history) | prefill compute and TTFT |
| FlashAttention | computes attention in tiles kept in on-chip SRAM, never writing the full score matrix to HBM; exact, not an approximation | memory traffic in attention, especially long prompts |
| CUDA graphs and kernel fusion | launch a whole decode step as one recorded graph; fuse small ops into one kernel | CPU launch overhead in small decode steps |
| GQA / MQA (model design) | fewer KV heads shared by many query heads | KV cache size, 4-8× smaller |
| Prefill/decode disaggregation | runs prefill and decode on separate GPU pools | interference between the two phases |
| Distillation | trains a smaller model to imitate a bigger one | everything: fewer parameters to read and compute |
The last row is worth stressing. A distilled 8B model that's good enough for the task is about 9× cheaper to serve than a 70B model, which is more than all the other techniques combined. In an interview, "do we need this model size?" is a fair question to raise before optimizing kernels.
If an interviewer asks you to cut serving cost by 2×, walk the list in order of impact and risk: right-size the model (or distill), then FP8 weights and KV cache, then raise batch sizes with paged attention and continuous batching, then prefix caching for repeated prompts. Speculative decoding is mostly a latency tool, not a cost tool.
Distributed Training
Now the other half. Training needs about 16 bytes per parameter with mixed precision and Adam (BF16 weights and gradients, FP32 master weights, and two FP32 Adam moments), plus activations, and about 6 FLOPs per parameter per token. An 8B model's training state is 128 GB, already more than one 80 GB GPU. A 70B model's is 1.1 TB. And pre-training a 70B model on 15T tokens needs about 6.3 × 10^24 FLOPs, which is millions of GPU-hours. So we split the work across many GPUs, in three basic ways.
Data Parallelism
Data parallelism (DP) gives every GPU a full copy of the model and a different slice of each batch. After the backward pass, GPUs average their gradients with an all-reduce, then each applies the same update, so the copies stay identical. PyTorch's DDP does this, overlapping the all-reduce with the backward pass bucket by bucket.
How much does it communicate? A ring all-reduce sends and receives about 2 × (n − 1) ÷ n times the gradient size per GPU, so roughly 2× the gradients. For an 8B model with BF16 gradients (16 GB), that's about 32 GB per GPU per step. Over NVLink at ~450 GB/s, that's about 70 ms. Across nodes at ~50 GB/s per GPU, about 0.64 s. If each GPU processes 16,000 tokens per step, its compute is 6 × 8 × 10^9 × 16,000 ≈ 7.7 × 10^14 FLOPs, about 1.9 s at ~400 TFLOP/s, so the communication can hide behind the backward pass. Larger per-GPU batches (or gradient accumulation, which sums gradients over several micro-batches before each all-reduce) make it easier to hide.
The catch: plain DP keeps all the training state on every GPU. At 16 bytes per parameter, an 80 GB GPU holds at most 5B parameters with zero room for activations. In practice pure DP stops working around a few billion parameters.
Sharded Data Parallelism: ZeRO and FSDP
ZeRO (in DeepSpeed) and FSDP (in PyTorch) keep data parallelism but stop replicating the state. Each of the n GPUs owns 1/n of it:
- Stage 1 shards the optimizer states (the 12 bytes of FP32 master weights and Adam moments).
- Stage 2 also shards the gradients.
- Stage 3 (FSDP's full sharding) also shards the weights. Before each layer runs, GPUs all-gather that layer's weights, use them, and free them. After the backward pass, gradients are reduce-scattered so each GPU gets only its shard.
With full sharding over 64 GPUs, the 70B model's 1,120 GB of state becomes 17.5 GB per GPU. The cost is communication: weights are all-gathered in the forward pass and again in the backward pass, and gradients are reduce-scattered, about 1.5× the traffic of plain DP. FSDP is the default for fine-tuning and for pre-training models up to tens of billions of parameters, especially within a fast network.
Tensor Parallelism
Tensor parallelism (TP) splits individual weight matrices across GPUs. The standard Megatron-style split for a transformer layer:
- In the MLP, the first matrix is split by columns, so each GPU computes part of the hidden layer independently, and the second is split by rows, so each GPU produces a partial sum of the output. One all-reduce combines the partial sums.
- In attention, the heads are divided among GPUs, each computing its heads independently, and the output projection is split by rows, followed by another all-reduce.
That's two all-reduces per layer in the forward pass and two in the backward pass, of activation size, on every layer. TP cuts the memory for weights, gradients and optimizer state by the TP degree and spreads the compute, but its communication is frequent and on the critical path. It's only efficient over NVLink, so TP stays within a node, usually at a degree of 2, 4 or 8.
Pipeline Parallelism
Pipeline parallelism (PP) assigns contiguous groups of layers (stages) to different GPUs. Stage 1 runs layers 1-20 and sends its activations to stage 2, and so on. Only activations cross stage boundaries, once per micro-batch per boundary, so it tolerates slower links and can span nodes.
The problem is the pipeline bubble. With one batch, only one stage works at a time. So the batch is split into m micro-batches that flow through the stages in sequence. With p stages, the idle fraction of a simple schedule is:
bubble fraction = (p − 1) / (m + p − 1)
With 4 stages and 16 micro-batches, that's 3 ÷ 19 ≈ 16% idle; with 8 stages and 32 micro-batches, 7 ÷ 39 ≈ 18%. More micro-batches shrink the bubble but each needs its activations kept until its backward pass. The 1F1B schedule (alternate one forward and one backward per stage once the pipeline is full) caps how many micro-batches' activations each stage holds at once, and interleaved schedules (several smaller stages per GPU) shrink the bubble further at the cost of more communication.
Putting Them Together: 3D Parallelism
Large runs combine all three, matching each to the network it needs:
- TP inside a node, over NVLink.
- PP across a few nodes, over InfiniBand, with enough micro-batches to keep the bubble small.
- DP (usually with ZeRO-1 sharding of optimizer state) across everything else, with gradient all-reduce overlapped with compute.
Worked example: training a 70B model on 1,024 H100s with TP = 8, PP = 4 and DP = 32 (8 × 4 × 32 = 1,024).
- Each GPU holds 1/(8 × 4) = 1/32 of the parameters: 70B ÷ 32 ≈ 2.2B.
- BF16 weights and gradients: 2.2B × 4 bytes ≈ 8.8 GB.
- Optimizer state: 2.2B × 12 bytes ≈ 26 GB, sharded across the 32 DP replicas with ZeRO-1: about 0.8 GB.
- That leaves most of the 80 GB for activations, which is what long sequences need.
- With a global batch of 4M tokens, each step is 6 × 70 × 10^9 × 4 × 10^6 ≈ 1.7 × 10^18 FLOPs. At ~400 TFLOP/s per GPU, the cluster does 1,024 × 4 × 10^14 ≈ 4.1 × 10^17 FLOP/s, so a step takes about 4 seconds.
- Each DP replica handles 4M ÷ 32 = 125,000 tokens per step, about 16 sequences of 8k tokens, so with one sequence per micro-batch, m = 16 and the bubble is 3 ÷ 19 ≈ 16% with a simple schedule, less with interleaving.
Long contexts and mixture-of-experts add two more dimensions. Context (sequence) parallelism splits a long sequence across GPUs, passing keys and values around a ring so each GPU computes attention for its part. Expert parallelism places different experts of an MoE model on different GPUs and routes each token to its experts with an all-to-all exchange.
Making Big Runs Survive
At thousands of GPUs, something fails often: a GPU, a NIC, a node, a link. Large runs commonly see interruptions daily. The defenses:
- Checkpoint often and asynchronously. A 70B model's full state is ~1.1 TB. Each GPU writes its own shard in parallel to fast storage, and the copy happens in the background while training continues.
- Detect and replace fast. Health checks catch slow or failing GPUs (one slow GPU stalls every synchronous all-reduce), the job restarts on spare nodes from the last checkpoint, and losing 10-20 minutes of work is the cost.
- Watch MFU. Model FLOPs utilization is the share of peak compute doing useful model math. Well-tuned large dense training commonly reaches around 35-50%. A drop usually means a communication or straggler problem.
- Recompute instead of storing. Activation checkpointing saves memory by recomputing parts of the forward pass during the backward pass, for roughly a third more compute.
For fine-tuning, most of this collapses: FSDP or LoRA on one node handles most jobs, as discussed in Design an LLM Fine-Tuning System.
Parallelism at Serving Time
The same ideas apply to inference, with different goals:
| Method | Training role | Serving role |
|---|---|---|
| Data parallelism | split the batch, average gradients | independent replicas behind a load balancer, for throughput |
| Tensor parallelism | fit and speed up big layers inside a node | fit the weights and cut per-token latency (each GPU reads 1/n of the weights per step) |
| Pipeline parallelism | fit the model across nodes | fit very large models across nodes; adds latency per stage, needs many requests in flight |
| Expert parallelism | spread MoE experts | spread MoE experts; all-to-all per MoE layer |
| Sharding (FSDP/ZeRO) | shard training state | not used: no optimizer state, and all-gathering weights every step would be far too slow |
The serving rule of thumb: the smallest TP degree that fits the weights plus enough KV cache, then add replicas. Engines and their parallelism options are compared in LLM Serving Engines.
Inference Optimization in an Interview
Which Tool When
- High serving cost: right-size or distill the model, FP8 weights and KV cache, continuous batching with paged attention, prefix caching for shared prompts.
- High time to first token: prefix caching, chunked prefill tuning, more prefill capacity or prefill/decode disaggregation, shorter prompts.
- Slow tokens per user: smaller batches or a lower token budget, more TP, speculative decoding at low load, weight quantization.
- Model doesn't fit: FP8 or INT4 weights, then TP inside the node, then PP across nodes.
- Training state doesn't fit: FSDP/ZeRO for up to tens of billions of parameters, 3D parallelism beyond that, LoRA or QLoRA for fine-tuning.
- Training too slow: more data parallelism (with a larger global batch), better MFU through overlap and fewer stragglers, FP8 training where supported.
Common Follow-ups
- "Does quantization speed up prefill?" Weight-only quantization barely does, because prefill is compute-bound and the math still runs in BF16. FP8 weights and activations do, by using faster tensor cores.
- "Why not always use a huge batch?" Per-user token speed drops as the batch grows, and KV memory caps it anyway.
- "Does speculative decoding change the output?" No. With rejection sampling, the output distribution is exactly the target model's.
- "Why not tensor parallelism across nodes?" Two all-reduces per layer per step over a network link roughly ten times slower than NVLink would dominate the step time.
- "How do you choose TP, PP and DP for training?" TP up to the node size to fit layers, PP just enough to fit the model with a small bubble, DP for the rest of the cluster, then check memory per GPU and the time of each step's communication against its compute.
Summary
Inference optimization starts from one fact: prefill is compute-bound and decode is memory-bandwidth-bound. Quantization reads fewer bytes per token: weight-only INT8/INT4 speeds decode, FP8 weights and activations also speed compute, and an FP8 KV cache doubles the tokens that fit. Batching amortizes each weight read over many sequences: dynamic batching for fixed-size models, continuous batching with paged attention and chunked prefill for LLMs, with batch size as a dial between total throughput and per-user speed. Speculative decoding gets several tokens from one read of the weights, exactly preserving the output, and helps most when the GPU has idle compute.
Distributed training exists because training state costs about 16 bytes per parameter and compute is 6N FLOPs per token. Data parallelism splits the batch and all-reduces gradients; ZeRO and FSDP shard the state; tensor parallelism splits layers over NVLink inside a node; pipeline parallelism splits layers across nodes at the cost of a bubble you shrink with micro-batches. Big runs combine them, checkpoint asynchronously and watch MFU. In every case, the right answer comes from knowing which resource (memory, bandwidth, compute or network) is the bottleneck, and choosing the technique that relieves it.