Model and kernel optimization
- Production
- 45 min
- Lesson 3 of 7 in Inference engineering
- Last verified
Select text in the lesson first to keep it with your note. With the keyboard, move focus here and press the button: the note goes with the section you are reading.
In this module
On this page
Before you start
- Completed:Memory and the KV-cache
You will be able to
- Explain how FlashAttention cuts memory traffic while staying exact, and why the saving is large in prefill and small in single-query decode.
- Choose between weight-only low-bit quantization and W8A8 or FP8 by using the roofline (memory-bound or compute-bound) and the hardware's supported formats.
- Say what scale-based quantization stores, why activation outliers break per-tensor 8-bit, and the core idea of LLM.int8, GPTQ, AWQ, SmoothQuant and FP8.
- Design a validation gate for a quantized model, and explain why perplexity alone is not enough.
- Explain what CUDA graphs and kernel fusion remove, and why temperature-0 outputs can vary with batch composition.
An engineer has a plan to make the model do the same calculations with fewer trips to memory. He explains it quickly, with a diagram.
Ananya lets him finish. “Same calculations?” she says. “Show me.”
What would you ask him to show?
Concept
Lessons 1 and 2 said what limits an inference engine: bytes moved at low batch, arithmetic at high batch, cache memory throughout. This lesson is the toolbox that acts on those limits at the level of the model and its kernels (a kernel is one function that runs on the GPU). Two ideas organise it.
- Move fewer bytes, by storing numbers in fewer bits (quantizationQuantizationStoring numbers with fewer bits. For vectors it saves memory; for model weights it cuts memory and the bytes read per decode step. Both cost some rounding error, so test on your own eval set.Open the glossary entry) and by not writing intermediate results to slow memory (fused, tiled kernels such as FlashAttention).
- Waste less time around the arithmetic, by removing launch and scheduling overhead (CUDA graphs, fusion) and understanding the numerics that those changes touch.
The engineer’s proof has two parts. Show the output is the same, or the quality loss is measured and acceptable. And show where the time goes, so the fix targets the real cost. Both parts recur below.
Why It Matters
Quantization is often the single biggest lever on cost, and it is also the one most often adopted on faith. “It is 4 bits so it is 4 times faster” and “perplexity barely moved so it is free” are both wrong, and interviewers probe them. Knowing why a method works lets you predict where it fails: which layers, which batch sizes, which hardware, which tasks.
Mental Model
Picture the weights as a library shipped on trucks. Quantization packs more books per truck, but the books must be unpacked before anyone reads them, and a few oversized volumes will not fit the new boxes without special handling. A fused kernel is a courier who completes three errands in one trip. A CUDA graph is a standing order that replaces a hundred phone calls with one. None of these changes what the readers do, which is why each must be shown to leave the answers intact.
Attention kernels: FlashAttention
Standard attention computes the score matrix of every query against every key, an matrix, writes it to the GPU’s main memory (HBM), reads it back for the softmax, writes the result, and reads it again to multiply by the values. The arithmetic is modest; the traffic is not.
FlashAttentionFlashAttentionA way of computing attention that reduces reads and writes to slow GPU memory, giving the same result faster.Open the glossary entry (Dao et al., 2022) is IO-aware: it splits the queries, keys and values into tiles that fit in fast on-chip memory, and combines tiles with an online softmax, a running maximum and sum, so the full matrix is never written out. The abstract states that it computes exact attention and needs fewer HBM accesses than standard attention. Later versions improve how work is divided on the GPU: FlashAttention-2 (2023) reports about twice the speed of the first, and FlashAttention-3 (2024) targets Hopper-generation GPUs, reporting up to 740 TFLOPs/s in FP16 on an H100 (about 75 percent of its peak). These are figures from the papers’ own benchmarks.
Where it matters follows from the roofline. In prefill, queries meet keys, so the score matrix is large and the saved traffic is large. In decode, one new query meets cached keys per head, so the score “matrix” is a single row and the traffic that dominates is reading the cache itself, which no tiling avoids. That is a reasoning step, not a claim from the papers: do not expect FlashAttention to fix a slow decode. Engines use separate kernels tuned for decode attention, such as ones that read the cache through block tables.
Quantization
Quantization stores a number as a small integer or float and a scale: . The scale can be one per tensor, one per channel, or one per group of weights (128 is a common group size). A scale per group costs a little extra: 4-bit weights with a 16-bit scale for every 128 values average bits each.
What you can quantize
| Target | Benefit | Main risk |
|---|---|---|
| Weights | fewer bytes read per decode step; smaller memory | accuracy loss at 4 bits and below without care |
| Activations | lets the chip run low-precision matrix multiplies, which help compute-bound work | activation outliers |
| KV-cache | more concurrent sequences (lesson 2) | long-context accuracy |
Notation: W4A16 means 4-bit weights and 16-bit activations. The weights are unpacked to 16 bits just before the multiply, so this saves bytes but not arithmetic. W8A8 means 8 bits for both, and the multiply itself runs in 8-bit. FP8 is an 8-bit floating-point format; the FP8 paper (Micikevicius et al., 2022) defines two variants, E4M3 (4 exponent bits, 3 mantissa bits) and E5M2.
Weight storage for an 8B model at different precisions (the 4-bit row includes a 16-bit scale per 128 values):
| Format | Bits per weight | Weight bytes | Decode step floor on an H100 |
|---|---|---|---|
| BF16 | 16 | 16 GB | 4.8 ms |
| INT8 | 8 | 8 GB | 2.4 ms |
| 4-bit with group scales | 4.125 | about 4.1 GB | about 1.2 ms |
Why activations are harder: outliers
A small example, with illustrative values. Quantize the activations 0.2, 1.0, −0.7, 0.5, 60.0 to signed 8-bit with one scale for the whole tensor. The scale is set by the largest value: . Then 1.0 becomes 2 (dequantized 0.94, a 5.5 percent error), −0.7 becomes −1 (−0.47, a 33 percent error), and 0.2 becomes 0 and disappears. Without the 60, the largest value is 1.0, the scale is , and every value is within about 2 percent (0.2 becomes 25, dequantized 0.197).
The same example as a table, with one scale of for the whole tensor:
| Original value | Stored integer | Dequantized | Error |
|---|---|---|---|
| 0.2 | 0 | 0 | 100% (vanishes) |
| 0.5 | 1 | 0.47 | 5.5% |
| 1.0 | 2 | 0.94 | 5.5% |
| −0.7 | −1 | −0.47 | 33% |
| 60.0 | 127 | 60.0 | 0% |
One outlier sets the scale for everyone, so the ordinary values lose their precision.
Large outlier values in a few channels are a documented feature of transformer activations (the LLM.int8 paper calls them emergent outliers). Weights are comparatively well behaved. That asymmetry is why weight-only schemes are easy and W8A8 needs a trick.
Methods: name the idea
| Method | Type | Core idea (as stated in its paper) |
|---|---|---|
| LLM.int8() | W8A8 | find the outlier feature dimensions and multiply those in 16-bit; the rest, more than 99.9 percent of values, in 8-bit |
| GPTQ | weight-only, one-shot | quantize layer by layer using approximate second-order information to compensate rounding error; 3 or 4 bits, no retraining |
| AWQ | weight-only | protect the small set of salient weight channels (about 1 percent), chosen from activation statistics, by scaling them before rounding |
| SmoothQuant | W8A8 | move quantization difficulty from activations to weights offline with a per-channel rescaling that leaves the layer output unchanged |
| FP8 | W8A8 | an 8-bit floating-point format with a wider dynamic range than INT8, which tolerates outliers better; needs hardware support |
The papers’ speed claims come from their setups: GPTQ reports about 3.25 times faster than FP16 on an A100 for large models, SmoothQuant up to 1.56 times with a 2 times memory reduction. Treat them as upper-end results, not what your engine will show.
The regime rule
Which scheme wins depends on which side of the ridge the work is on.
- Memory-bound decode at small batch. Time is bytes over bandwidth. Weight-only W4A16 or W8A16 cuts the bytes while the idle arithmetic units absorb the unpacking cost. On an H100, the 8B model’s weights shrink from 16 GB to about 4.1 GB at 4.125 bits per weight, so the step floor falls from 4.8 ms to about 1.2 ms. That is a ceiling; KV reads, unpacking and kernel efficiency pull the real gain below it.
- Compute-bound prefill and large batches. Time is operations over peak rate, so fewer bytes no longer help, and unpacking adds work. W8A8 or FP8 wins because the chip runs 8-bit matrix multiplies faster than 16-bit. NVIDIA lists H100 FP8 tensor throughput at twice its BF16 figure.
- The middle. With 8-bit weights and 8-bit math, intensity is per byte and the FP8 ridge is twice the BF16 ridge (about 590 against 295 on an H100, using dense figures that are half the listed sparse ones). The batch at which decode turns compute-bound, , comes out near 295 in both cases. So 8-bit math leaves the crossing where it was, while weight-only 8-bit with BF16 math would halve it to about 148 (lesson 1). Quantization changes the cost on each side of the crossing more than the crossing itself.
| Situation | Limit | Scheme that fits | Why |
|---|---|---|---|
| Decode at small batch | Bytes read per step | Weight-only W4A16 or W8A16 | Fewer bytes read; idle arithmetic units absorb the unpacking |
| Prefill or large batch | Peak arithmetic | W8A8 or FP8 | The chip runs 8-bit matrix multiplies faster than 16-bit |
| Near the ridge | Both | Test it | 8-bit math leaves the crossing near a batch of 295 |
Hardware support is part of the answer. vLLM’s quantization compatibility table (accessed 2026-10-21) lists FP8 W8A8 for Ada, Hopper and some AMD GPUs but not Ampere, so an A100 fleet uses INT8 W8A8 or weight-only schemes instead. The table also says it changes as support grows, so check the version you run.
Validating quality: never “it is free”
- Start with perplexity on held-out text. It is quick and coarse and catches only large breakage.
- Run your task evals: your golden set, tool-call accuracy, JSON validity, long-context retrieval. Aggregate benchmarks can hide regressions in code, mathematics, other languages and long inputs.
- Compare with the 16-bit baseline using the same prompts, with confidence intervals and slices by task and language (see Evaluating LLM systems).
- Calibrate on production-like data. Methods that use calibration data, such as GPTQ and AWQ, can fit a sample that does not look like your traffic.
- Canary and watch: output length, refusal rate, tool-error rate, and a rollback.
A realistic failure: average accuracy is flat after moving to 4 bits, but structured-output failures double. Rounding error pushes a rare token over a boundary, and a malformed bracket breaks the parser. Only a task-level metric sees it.
Other levers on the model
Distillation trains a small model on a large one’s outputs and suits stable, narrow, high-volume tasks. Routing sends easy requests to a small model. Pruning and structured sparsity need hardware support and recovery tuning, and the datasheet “with sparsity” peaks assume it. Mixture-of-experts models trade total memory for lower compute per token (lesson 5). Each costs engineering or quality in its own way.
Reducing time around the arithmetic
A decode step runs hundreds of small kernels. Each one is launched by the CPU. NVIDIA’s CUDA-graph write-up (2019) measured, for a trivial kernel of about 2.9 µs, a total per-kernel time of 9.6 µs with a synchronization after each launch, 3.8 µs with overlapped launches, and 3.4 µs when replayed through a graph, so the saving is the per-launch overhead. A CUDA graphCUDA graphA recorded sequence of GPU operations that is replayed with a single launch, removing per-kernel CPU launch overhead. Engines capture graphs for a set of batch sizes and pad a live batch to the nearest one.Open the glossary entry records a sequence of GPU operations once and replays it with a single launch.
An illustrative calculation: if a step launches 1,000 kernels and each costs about 4 µs of CPU launch overhead that is not hidden, that is 4 ms, comparable to the 4.8 ms memory floor of an 8B model on an H100. At small batch, the GPU can spend as long waiting to be told what to do as moving weights. The kernel count here is invented to show the scale; profile your own engine.
Graphs replay a fixed sequence, so an engine captures them for a set of batch sizes and pads a real batch up to the nearest captured size. vLLM’s design notes (accessed 2026-10-21) describe full graphs for uniform decode and piecewise graphs for other cases, configurable capture sizes, and a memory and capture-time cost for each mode. The practical consequences are warm-up before benchmarking and a cold-start cost to plan for.
Kernel fusion merges adjacent operations (a normalisation with its neighbours, an activation with a matrix multiply’s epilogue) so intermediate results stay in fast memory, the same trick as FlashAttention on a smaller scale. Other overlap tricks hide CPU scheduling and sampling behind GPU work. Compilers and hand-tuned kernels (torch.compile, TensorRT-LLM, Triton, CUTLASS) deliver these.
Numerics and determinism
Floating-point addition is not associative: adding the same numbers in a different order can give a slightly different result. A kernel that splits a reduction differently for different batch sizes therefore returns different numbers for the same request depending on what else is in the batch.
The Thinking Machines write-up “Defeating Nondeterminism in LLM Inference” (September 2025) argues that this lack of batch invarianceBatch invarianceThe property that a request's result does not depend on which other requests share its batch. Many inference kernels lack it, which is one reason temperature 0 is not fully deterministic.Open the glossary entry, not simple concurrency, is the main reason a forward pass at temperature 0 can vary between runs. In its experiment, 1,000 temperature-0 completions of the same prompt on a 235-billion-parameter model produced 80 unique outputs, diverging as early as token 103. With batch-invariant kernels all 1,000 were identical, at a cost: on an 8B model, a run that took 26 seconds took 42 to 55 seconds. These are the authors’ measurements on their setup.
For you, the lesson is practical. Temperature 0 is greedy decoding, not a guarantee of identical bytes. Quantization, a kernel change or a new batch size can alter outputs without any bug, so design evaluations that tolerate small variation and keep a deterministic mode, at its cost, for cases such as reproducing a failure.
Which optimization first?
Real-World Application
A concrete plan for a 70B chat model on H100s at low concurrency: the work is memory-bound, so start with FP8 or 4-bit weights (about 70 GB or 35 GB against 140 GB). Check hardware support first. Run your task evaluations against the BF16 baseline, with slices for tool calls and long inputs. Canary a share of traffic and watch output length and tool errors. Only then tune the batch size, and turn on CUDA graphs and warm-up. For an offline summarization job at large batches the work is compute-bound, so the same quantization budget goes to W8A8 or FP8 and larger batches instead.
Interview Perspective
Expect: “Why does FlashAttention not change the output?”, “When does W4A16 beat FP8, and when does it lose?”, “What is an activation outlier?”, “After moving to INT4 accuracy is flat but JSON failures doubled. Diagnose.”, “Why does temperature 0 give different answers?”. A strong answer ties each choice to the roofline, names the quality check, and mentions hardware support.
Common mistakes: calling FlashAttention an approximation; saying INT4 is four times faster; calibrating on data unlike production; reporting perplexity as proof of no loss; ignoring that FP8 needs supporting hardware; claiming temperature 0 is bit-reproducible.
Provenance: Common industry pattern and Generated practice. These are standard serving topics for ML-infrastructure and GenAI roles; none is verified for a named company. Method names and hardware support change quickly, so check current documentation.
Practice Questions
- Basic: Why does FlashAttention reduce memory traffic without changing results?
- Intermediate: When does W4A16 beat FP8 W8A8, and when does it lose?
- Advanced: After moving to INT4, average accuracy is flat but JSON tool-call failures doubled. Diagnose and respond.
- Product-Company: Cut serving cost by 40 percent on a 70B chat model without hurting quality. Give a ranked plan with evaluation gates.
Activity
Quantize a small list of numbers by hand with one scale, then with a separate scale for the large value (or per group), and compute the error for each. Then explain which regime (memory-bound or compute-bound) each of W4A16 and FP8 W8A8 helps on a GPU of your choice, using its datasheet bandwidth and dense peak.
Homework
Write a one-page quantization rollout plan for a model you serve: the format and why (with the regime and the hardware support), the evaluation gate (datasets, slices, baseline, threshold), the calibration data, the canary and the rollback trigger.
Quick Revision
- FlashAttention is exact. It tiles and fuses attention so the matrix never goes to HBM. It helps prefill most.
- Quantization: ; the scale is per tensor, channel or group.
- Activation outliers break per-tensor 8-bit; LLM.int8, SmoothQuant and FP8 each handle them differently.
- Memory-bound decode: weight-only low-bit. Compute-bound work: W8A8 or FP8. Check hardware support.
- Validate on task metrics against the baseline, not on perplexity alone.
- CUDA graphs and fusion remove launch overhead; profile first.
- Temperature 0 is greedy, not bit-reproducible; batch invariance costs speed.
Check yourself
- Walk-through: You run a 70B model in BF16 on four GPUs. Propose and justify a quantization plan for an interactive chat product at low concurrency and for an offline batch summarization job.
- Variation: Repeat for A100s, which do not support FP8 in the table above.
- Common misconception: “Quantization is free if perplexity barely moves.” Perplexity is coarse, and task failures can double while it stays flat.
Related
Resources & Further Reading
Checked sources to go deeper. The essential ones come first in each group.
Official documentation
Optimization and Tuning (opens in a new tab)
The engine's own tuning guide, useful for turning the ideas in this lesson into settings.
Further reading
Mastering LLM Techniques: Inference Optimization (opens in a new tab)
A vendor overview of quantization, batching and attention optimizations that places these techniques next to each other.
Research papers
The cache-management side of the same serving stack, which shows what the attention kernels read from.
Hands-on
batch_invariant_ops (opens in a new tab)
The repository behind the batch-invariance write-up, for readers who want to run the kernels.
More for this module: Inference engineering resources
Practice
Test what you just read. Quizzes and cards are grouped by module: Inference engineering.
Check yourself16 questions on what this lesson set out to teach
Checking answers needs JavaScript. You can still read every question and option below.
Keyboard: arrow keys move between options. Space or Enter selects the focused option.