Before you start: words you need#
| Word | Plain meaning |
|---|---|
| Optimization | Any change that makes the same model produce the same (or acceptably close) answers faster or cheaper. |
| Bottleneck | The one resource that limits speed right now: arithmetic, memory bandwidth, the CPU launching work, the scheduler, or the queue. Speeding up anything else does nothing. |
| Baseline | A measurement taken before a change, with a fixed workload, so the change can be judged. |
| SLO (service-level objective) | The latency or throughput target the product promises, e.g. “95% of requests see their first token within 500 ms”. Lesson 23.a covers SLOs in depth. |
Module 13 is a toolbox: quantization (13.b–13.h), KV cache savings (13.i), fusion (13.j), CUDA graphs (13.k), FlashAttention (13.l), compilers (13.m), speculative decoding (13.n–13.o) and smaller models (13.p). This lesson is how to pick the right tool. Read it first.
1. What is it?#
A repeatable procedure for making an inference system faster without wasting weeks on the wrong thing:
1. DEFINE what "faster" means: which metric, what target, what must not get worse
2. MEASURE where the time goes: first by phase, then by kernel
3. CLASSIFY the bottleneck: memory / compute / launch / scheduling / queueing
4. SELECT an optimization that attacks THAT bottleneck
5. ESTIMATE the expected gain before doing the work
6. APPLY one change
7. VERIFY the gain, and the answer quality
8. REPEATSteps 3 and 5 are the ones people skip, and skipping them is why optimization projects fail.
Diagram — The optimization loop#
flowchart LR M["Measure<br/>baseline + SLO"] --> F["Find the bottleneck<br/>profile, do not guess"] F --> C["Classify<br/>memory / compute / host / queue"] C --> X["Apply ONE change"] X --> V["Verify<br/>speed AND output quality"] V -->|"still short of goal"| F V -->|"goal met"| S["Stop"] class M,F neutral class C queue class X compute class V memory class S io
2. Why does it exist?#
Because inference performance is counterintuitive, and intuitions from other kinds of software mislead:
"We cut FLOPs by 40%" → zero gain if the step is memory-bound (2.e)
"GPU utilization is 100%" → says nothing about useful work (22.d)
"The kernel is 2x faster" → 5% end to end if it was 10% of the time
"Quantization made it 4x faster" → for decode; prefill may barely change
"More GPUs will help" → only with the right parallelism, and not always (14.m)Every one of these is something real teams have said, and every one cost real time.
3. Simple analogy#
You are late for work and the commute is 40 minutes: 30 on the motorway, 10 walking from the car park. Buying a car that is twice as fast on the motorway saves 15 minutes. Walking twice as fast saves 5. Before you buy anything, you time the parts.
That is Amdahl’s law: speeding up a part of the work helps only in proportion to how much of the total time that part takes.
overall speedup = 1 / ((1 − p) + p / s)
p = fraction of total time spent in the part you speed up
s = how much faster that part becomes
p = 0.10, s = ∞ → 1.11x (make 10% of the work free: 11% faster overall)
p = 0.50, s = 2 → 1.33x
p = 0.80, s = 2 → 1.67x
p = 0.80, s = 10 → 3.57xCompute this before starting any work. It takes thirty seconds and often kills a bad idea.
4. Tiny example — the estimation habit#
PROPOSAL: "Let's write a fused RMSNorm kernel."
ESTIMATE FIRST:
The profile says RMSNorm kernels are 8% of the decode step.
A fused version reads memory 3x less for that op (6 passes → 2).
Amdahl: 1 / ((1 − 0.08) + 0.08/3) = 1 / (0.92 + 0.027) = 1.056 → 5.6% faster.
Effort: 2 days.
COMPARE:
Turning on CUDA graphs (13.k): ~25% faster decode at small batch, 1 hour.
FP8 weights and KV cache (13.e): ~1.5–2x decode throughput, 3 days incl. validation.
DECISION: CUDA graphs first, then FP8, then maybe the kernel.Five minutes of arithmetic reorders a quarter’s worth of work.
5. The methodology in detail#
Step 1 — Define the target#
BAD: "make it faster"
GOOD: "cut p95 inter-token latency from 45 ms to 30 ms at 32 concurrent users,
without p95 time-to-first-token going above 500 ms,
and without the evaluation score dropping more than 0.5 points"Without a target you cannot tell when you are done, and you cannot trade off correctly. Every inference optimization trades something — memory, accuracy, latency at one load for latency at another. Naming the constraint names the trade.
Step 2 — Measure, at three levels#
LEVEL 1 — Request phases (engine and application metrics, 19.c, 22.j)
queue wait, tokenize, prefill, decode, detokenize, network
→ tells you WHICH PHASE
LEVEL 2 — Timeline (Nsight Systems or the PyTorch profiler, 6.d, 22.h)
kernel time vs gaps between kernels, synchronization points, copies
→ tells you whether the GPU, the CPU or a wait is the problem
LEVEL 3 — One kernel (Nsight Compute, 6.d)
SM busy %, DRAM bandwidth %, occupancy, stall reasons
→ tells you WHY a kernel is slowAlways go 1 → 2 → 3. Starting at level 3 optimizes kernels that do not matter.
Step 3 — Classify#
Symptom Bottleneck Where to look
───────────────────────────────────────────────────────────────────────────────
Small batch although memory is free scheduling 12.j, 20.c, 17.b
Long queue wait capacity 23.b
Gaps between kernels, CPU busy launch / dispatch 5.d, 13.k, 13.m
DRAM % high, SM % low memory bandwidth 13.b–13.h, 13.i, 13.l
SM % high, DRAM % low compute 13.e, 13.j, 15.c
Both low latency / occupancy 6.c
Long prompts stall everyone's tokens scheduling 12.k, 14.j
Client sees much worse TTFT than server network / proxy 9.a, 21.iSteps 4 and 5 — Select and estimate#
Pick the tool that attacks the classified bottleneck, then estimate:
expected gain = Amdahl(p = share of time in the bottleneck,
s = improvement the tool gives on that bottleneck)If the estimate is under 10%, look for a bigger lever first.
Steps 6 and 7 — Apply and verify#
One change at a time. Two simultaneous changes with a 15% net gain could be +40% and −25%, and you would never know.
Verify both speed and quality. Any change to precision (13.b–13.h), sampling or the draft model can change answers. Run the four-level quality check in 11.k. A 2x speedup with a 5% quality drop may be a bad trade — you can only decide if you measured both.
The usual order of levers (typical, not universal)#
Checked against current engines on 11 November 2026. In vLLM, SGLang and TensorRT-LLM, items 1, 3, 6 and 8 are on by default; check rather than assume.
| Rank | Optimization | Typical gain | Effort | Risk |
|---|---|---|---|---|
| 1 | Serve with an engine that does continuous batching (Module 15) | 3–10x vs. a naive server | hours | low |
| 2 | Fix scheduling: batch limits, admission, token budget (17.b, 20.c) | 1.5–4x | days | low |
| 3 | Prefix caching, if prompts share prefixes (12.m) | 1.3–5x for agents and chat | hours | low |
| 4 | Stop work when the client disconnects (20.e) | 1.1–1.4x | hours | low |
| 5 | FP8 weights and FP8 KV cache (13.e, 13.h) | 1.5–2x | days | low–medium |
| 6 | CUDA graphs and torch.compile (13.k, 13.m) | 1.1–1.4x | hours | low |
| 7 | Speculative decoding with the model’s MTP head or an EAGLE-3 head (13.n) | 1.5–2.5x at low load | days | medium |
| 8 | Chunked prefill (12.k) | smoother inter-token latency | hours | low |
| 9 | 4-bit weights: NVFP4 on Blackwell, AWQ/GPTQ elsewhere (13.f, 13.g) | 1.5–2.5x for decode | days | medium |
| 10 | Right-size the model: a smaller or distilled model (13.p) | 2–10x | weeks | high |
| 11 | Tensor or expert parallelism for latency (Module 14) | 1.5–3x latency | days | low |
| 12 | Custom kernels (6.e) | 1.05–1.3x | weeks | medium |
Items 1–8 are mostly configuration. Most teams jump straight to 10–12. Do them in order.
6. Under the hood: the estimation formulas#
Decode floor: time per step ≥ bytes read per step / memory bandwidth
Prefill floor: time ≥ FLOPs / peak FLOP/s
Quantization gain: bytes ratio when memory-bound; FLOP-rate ratio when compute-bound
Batching gain: up to min(new batch / old batch, ridge point / current intensity) (6.a)
Fusion gain: (memory passes before / passes after) on that op's share of time
CUDA graph gain: total launch overhead / step time
Speculation gain: ≈ expected accepted tokens per verify step / (1 + draft cost) (12.n)
Amdahl: 1 / ((1 − p) + p/s)Worked example. A 70B model, FP16 weights (140 GB), decode at batch 1 on one GPU with 4.8 TB/s of HBM bandwidth (an H200):
floor = 140 GB / 4.8 TB/s ≈ 29 ms per token
FP8 weights (70 GB): ≈ 15 ms → ~2x, because decode is memory-bound
FP8 compute on top: no extra gain at batch 1 — the tensor cores were idle anywayAt batch 256 the same step is closer to compute-bound, and FP8 compute starts to matter. The same optimization has different value at different loads; always estimate at the load you serve.
7. Performance implications#
The method itself is the performance gain: it stops three weeks being spent on a 4% win while a configuration flag would have given 40%.
Re-estimate after each change. Fixing one bottleneck exposes the next: after FP8 halves memory traffic, launch overhead (13.k) or the scheduler (17.a) may become the limit.
8. Production implications#
- Keep a performance journal: date, baseline, change, measured gain, quality change, decision.
- Automate the benchmark so anyone can rerun it; use realistic prompt and output lengths and a realistic arrival pattern (22.g).
- Track achieved vs. roofline (22.b) as a regression signal.
- Re-measure after every upgrade. Engines change defaults every release (for example, vLLM v0.32.0 made an FP8 KV cache the default for some models on Blackwell); a benchmark from last quarter describes a different system.
9. Common mistakes#
- Optimizing without measuring. The cardinal sin.
- Several changes at once. You learn nothing.
- Not measuring quality. Half of inference optimizations trade some accuracy.
- Unrealistic benchmarks. Fixed lengths and no concurrency hide the real bottleneck.
- Ignoring Amdahl. Optimizing 5% of the time.
- Optimizing the median when the SLO is on the tail (p95, p99).
- Not re-measuring after the change. “It should be faster” is not data.
10. Hands-on exercise#
A. Build the benchmark. Write a reproducible benchmark for a running server (vLLM is fine, 16.b): realistic prompt and output length distributions, Poisson arrivals, and report TTFT and ITL percentiles, throughput and cost per million tokens. Every other exercise in this module uses it.
B. Diagnose. For that system, produce a one-page diagnosis: phase breakdown, timeline, top-five kernels and a classification from the table in section 5.
C. Estimate, then do. Pick three optimizations from the ranking. Estimate each with section 6. Implement one and compare the measured gain with your estimate. How far off were you, and why?
D. Amdahl in practice. List every component of the decode step with its share of time. For each, compute the best possible end-to-end gain if it became free. Which are worth working on?
E. The journal. Start performance-journal.md and keep it for the rest of this module.
11. Interview questions#
- Walk me through how you would optimize an LLM inference service you have never seen.
- A colleague cut FLOPs by 40% and saw no speedup. What do you tell them?
- What is Amdahl’s law, and how do you use it before starting work?
- Rank the first five optimizations you would try on a typical LLM service, and justify the order.
- Why change one thing at a time?
- How do you decide between quantization and speculative decoding for a latency problem?
- What would you measure before declaring an optimization safe to ship?
12. Further reading#
- [FUNDAMENTAL] Amdahl, “Validity of the single processor approach to achieving large scale computing capabilities” (1967)
- [FUNDAMENTAL] Brendan Gregg, the USE method — utilization, saturation, errors for every resource
- [ESTABLISHED] Pope et al., “Efficiently Scaling Transformer Inference” — analysis before implementation, done well
- [REFERENCE] vLLM optimization and tuning guide