Model and kernel optimization

  • Production
  • 45 min
  • Lesson 3 of 7 in Inference engineering
  • Last verified

Open slides(33 slides)

Before you start

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 n×nn \times n 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 n×nn \times n 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.

Diagram: Standard attention writes the full score matrix to slow GPU memory and reads it back several times.

FlashAttention

Load a tile of Q, K, V into fast on-chip memory

Compute scores, online softmax, partial output

Next tile; never write the full n × n matrix

Standard attention

Compute n × n scores

Write scores to HBM

Read back for softmax

Write result, read again for values

Diagram summary: Standard attention writes the full score matrix to slow GPU memory and reads it back several times. FlashAttention works tile by tile in fast on-chip memory and keeps a running softmax, so the big matrix is never written out. The result is exact, with far less memory traffic.

Where it matters follows from the roofline. In prefill, nn queries meet nn keys, so the score matrix is large and the saved traffic is large. In decode, one new query meets nn 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: x≈scale×qx \approx \text{scale} \times q. 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 4+16/128=4.1254 + 16/128 = 4.125 bits each.

What you can quantize

TargetBenefitMain risk
Weightsfewer bytes read per decode step; smaller memoryaccuracy loss at 4 bits and below without care
Activationslets the chip run low-precision matrix multiplies, which help compute-bound workactivation outliers
KV-cachemore 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):

FormatBits per weightWeight bytesDecode step floor on an H100
BF161616 GB4.8 ms
INT888 GB2.4 ms
4-bit with group scales4.125about 4.1 GBabout 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: 60/127=0.4760 / 127 = 0.47. 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 1.0/127=0.00791.0 / 127 = 0.0079, 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 60/127=0.4760 / 127 = 0.47 for the whole tensor:

Original valueStored integerDequantizedError
0.200100% (vanishes)
0.510.475.5%
1.020.945.5%
−0.7−1−0.4733%
60.012760.00%

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

MethodTypeCore idea (as stated in its paper)
LLM.int8()W8A8find the outlier feature dimensions and multiply those in 16-bit; the rest, more than 99.9 percent of values, in 8-bit
GPTQweight-only, one-shotquantize layer by layer using approximate second-order information to compensate rounding error; 3 or 4 bits, no retraining
AWQweight-onlyprotect the small set of salient weight channels (about 1 percent), chosen from activation statistics, by scaling them before rounding
SmoothQuantW8A8move quantization difficulty from activations to weights offline with a per-channel rescaling that leaves the layer output unchanged
FP8W8A8an 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 2B2B 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, B∗=ridge×b/2B^{*} = \text{ridge} \times b / 2, 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.
SituationLimitScheme that fitsWhy
Decode at small batchBytes read per stepWeight-only W4A16 or W8A16Fewer bytes read; idle arithmetic units absorb the unpacking
Prefill or large batchPeak arithmeticW8A8 or FP8The chip runs 8-bit matrix multiplies faster than 16-bit
Near the ridgeBothTest it8-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”

  1. Start with perplexity on held-out text. It is quick and coarse and catches only large breakage.
  2. 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.
  3. Compare with the 16-bit baseline using the same prompts, with confidence intervals and slices by task and language (see Evaluating LLM systems).
  4. 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.
  5. 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.

Diagram: A decode step runs hundreds of small kernels, and without a graph the CPU launches each one separately, paying launch overhead every time.

With a CUDA graph

Record the kernel sequence once

Replay the whole step with one launch

Without a CUDA graph

CPU launches kernel 1

launches kernel 2

... 1,000 launches, each with overhead

Diagram summary: A decode step runs hundreds of small kernels, and without a graph the CPU launches each one separately, paying launch overhead every time. A CUDA graph records the sequence once and replays it as a single launch, which matters most at small batch where overhead rivals the memory floor.

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?

Diagram: Measure first.

Yes

No

Yes

No

Yes

No

Measure TTFT, ITL, tokens per second, GPU use, memory, batch size

Decode memory-bound?
small batch, slow ITL

Weight quantization W4 or W8
speculative decoding
CUDA graphs, fewer GPUs

Compute-bound?
long prompts or big batch

W8A8 or FP8, FlashAttention
prefix caching, chunked prefill
more replicas

KV memory limits batch?

GQA or MLA model, KV in FP8
shorter context

Launch, CPU or sampling overhead:
CUDA graphs, async scheduling, profile

Diagram summary: Measure first. If decode is memory-bound, cut weight bytes and add speculative decoding or graphs. If the work is compute-bound, use 8-bit math, FlashAttention and prefix caching. If the cache limits the batch, shrink or shorten it. If none of these, the cost is overhead, so profile.

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 n×nn \times n matrix never goes to HBM. It helps prefill most.
  • Quantization: x≈scale×qx \approx \text{scale} \times q; 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.

Resources & Further Reading

Checked sources to go deeper. The essential ones come first in each group.

Official documentation

Further reading

Research papers

Hands-on

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.

0 of 16 answered

Keyboard: arrow keys move between options. Space or Enter selects the focused option.

ObjectiveExplain how FlashAttention cuts memory traffic while staying exact, and why the saving is large in prefill and small in single-query decode.

  1. Question 1 of 16How does FlashAttention's output compare with standard attention, and what does it change?

    Choose one answer.

  2. Question 2 of 16A service is slow at decode with a batch of 2 and 1,000-token contexts. A teammate proposes switching to a FlashAttention kernel as the main fix. What is the best assessment?

    Choose one answer.

  3. Question 3 of 16Which are consequences of FlashAttention's tiling and online softmax? Select all that apply.

    Choose all that apply.

ObjectiveChoose 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.

  1. Question 4 of 16A 70B chat product runs at a batch of 2 on H100s and decode is slow. Which quantization choice follows from the roofline?

    Choose one answer.

  2. Question 5 of 16An offline summarization job runs at a batch of 512 on an H100. Moving from BF16 to W4A16 gave almost no speed-up, and contexts are short. What explains it?

    Choose one answer.

  3. Question 6 of 16A team with a fleet of A100 GPUs plans FP8 W8A8 serving because they read that FP8 is nearly lossless. What should they check first?

    Choose one answer.

  4. Question 7 of 16A GPU has 400 dense TFLOPS in BF16, 800 in FP8, and 2 TB/s of bandwidth. With FP8 weights and FP8 math, at what batch does decode reach the ridge? (Intensity is about 2B per byte.)

    Choose one answer.

ObjectiveSay 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.

  1. Question 8 of 16Activations are quantized to signed 8-bit with one scale for the whole tensor: values 0.1, 0.4, −0.3 and one outlier of 30.0. What happens to the 0.1?

    Choose one answer.

  2. Question 9 of 16Which description matches AWQ?

    Choose one answer.

  3. Question 10 of 16Which of these are weight-only quantization methods? Select all that apply.

    Choose all that apply.

ObjectiveDesign a validation gate for a quantized model, and explain why perplexity alone is not enough.

  1. Question 11 of 16An INT4 build of your model has perplexity within 1 percent of the BF16 original. A colleague says to ship it. What is the best response?

    Choose one answer.

  2. Question 12 of 16Which belong in the validation gate for a quantized model? Select all that apply.

    Choose all that apply.

  3. Question 13 of 16After moving to 4-bit weights, overall accuracy is unchanged but malformed JSON in tool calls doubles. What is the best next step?

    Choose one answer.

ObjectiveExplain what CUDA graphs and kernel fusion remove, and why temperature-0 outputs can vary with batch composition.

  1. Question 14 of 16At a batch of 1, profiling shows the GPU idles between a long chain of small kernels and the CPU is busy submitting them. Which change addresses this directly?

    Choose one answer.

  2. Question 15 of 16An engine captured CUDA graphs for batch sizes 1, 2, 4, 8 and 16. A live batch has 11 sequences. What does it typically do?

    Choose one answer.

  3. Question 16 of 16The same prompt at temperature 0 returns different text when the server is busy than when it is idle. Nothing is broken. What is the best explanation?

    Choose one answer.