20.1.4 Choosing and validating quantization
This part of Quantization: Math to Code develops the mechanisms below. Work the numerical examples or trace the code before checking the answer.
Concepts from other sections (11)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- E4M3: an fp8 format with 4 exponent and 3 mantissa bits, largest finite value 448. Read more: 21.5 Quantization: int8, int4 groups, fp8, and the KV cache
- QLoRA: LoRA trained against a base stored in 4-bit NF4, cutting training memory to roughly a quarter. Read more: 20.8 From Training Run to Shared Model: Packaging, Publishing, and Use Cases
- KV cache: the stored keys and values of all processed tokens, per layer, that let each new token attend without recomputation. Read more: Chapter 20: Inference Engines and GPU Deployment
- GGUF: llama.cpp’s single-file quantized model container, readable across llama.cpp, candle, mistral.rs, and Zig bindings. Read more: 20.2 Inference Frameworks: The Cross-Language Landscape
- Dot product: ; it measures how much two vectors point the same way, and it is zero exactly when they are perpendicular. Read more: Chapter 10: Calculus 3 in Mathematics
- Entropy: , the average surprise of a distribution. Read more: 17.1 Entropy, cross-entropy, KL, JS, and the k3 estimator in Mathematics
- Hessian: the symmetric matrix of second partial derivatives, whose eigenvalues classify a critical point. Read more: 10.3 Calculus 3 problem set: vectors, gradients, the chain rule, Hessians, multiple integrals, Lagrange in Mathematics
- K-quants / i-quants: llama.cpp’s weight quantization schemes for GGUF files; k-quants mix precision per block, and i-quants choose precision guided by an importance matrix measured on sample data. Read more: Chapter 26: Edge and Realtime Inference
- Decode step: a forward pass over one new token against the cache. Read more: 21.2 The KV cache, incremental decoding, and generate
- Group quantization: one scale per consecutive columns of a row. Read more: 21.5 Quantization: int8, int4 groups, fp8, and the KV cache
- fp16: a 16-bit format with 5 exponent bits and 10 mantissa bits; finer precision but a maximum of 65504 and a smallest subnormal of . Read more: 17.1 Mixed precision, loss scaling, gradient accumulation, and activation checkpointing
Learning objectives
- Choose a supported format and validate it on the deployment workload.
Choosing a quantizer
Section titled “Choosing a quantizer”The history and the math reduce to practical guidance. For the 2025/2026 stack, this table matches each goal to a method, its bit-width, and the reason it fits:
| Goal | Use | Bits | Why |
|---|---|---|---|
| Best W4 quality, GPU serving | AWQ or GPTQ + Marlin | 4 (W4A16) | Salient-channel / second-order; fast fused kernel |
| Max throughput on H100 | FP8 (E4M3) | 8 (W8A8) | Native tensor cores, tiny accuracy loss |
| Big-model W8A8 without retrain | SmoothQuant | 8 | Migrates activation outliers |
| Fine-tune a quantized model | NF4 (QLoRA) | 4 | Quantile-optimal for Gaussian weights |
| CPU / laptop / edge | GGUF k-quants (Q4_K_M) | ~4.5 | No GPU, hierarchical block scales |
| Aggressive 2-bit weights | QuIP# | 2 | Incoherence + E8 lattice |
| KV cache, online, no calibration | TurboQuant / QJL | 2.5–3.5 | Data-oblivious, near-optimal distortion |
Quantization in Rust with Burn
Section titled “Quantization in Rust with Burn”Everything so far has been C, CUDA, or Python pseudocode. In Rust, Burn has a backend-agnostic quantization API in burn::tensor::quantization. Burn is pre-1.0 and evolving fast, so pin a version. Its core types are QuantScheme (the configuration), QuantValue (Q8S, Q4S, and Q2S for fixed-point symmetric; E4M3, E5M2, and E2M1 for floats), QuantLevel (per-tensor or per-block granularity), Calibration (min-max), and QuantMode (symmetric). The simplest path is dynamic quantization, which calibrates on the fly:
use burn::tensor::quantization::{QuantScheme, QuantValue};use burn::tensor::Tensor;
// 8-bit symmetric, dynamic (min-max calibration computed from the tensor):let scheme = QuantScheme::default().with_value(QuantValue::Q8S);let q = tensor.clone().quantize_dynamic(&scheme); // -> quantized Tensorlet back = q.dequantize(); // -> f32 Tensor
// 4-bit, per-block granularity for weight-only quantization:let scheme = QuantScheme::default() .with_value(QuantValue::Q4S) .with_level(QuantLevel::block([128])); // group_size = 128A runnable example that quantizes, dequantizes, and measures the MSE on the NdArray backend with autodiff is in code/burn_quantize.rs. For production Rust inference, GGUF k-quant models also run through llama.cpp bindings (llama-cpp-2) and candle’s quantized module. The full cross-language runtime landscape that consumes these formats is mapped in Inference Frameworks, including a pure-Zig SIMD INT8 dot product, frameworks/code/quant_dot.zig, which is the CPU twin of code/symmetric_quant.cu.
Where this leads
Section titled “Where this leads”The theory behind this section comes from Mathematics: rate-distortion, entropy, and quantile coding in Information Theory explain why NF4 and Lloyd–Max quantizers are optimal; Hessians, Cholesky factors, and orthogonal and Hadamard matrices in Linear Algebra underlie GPTQ, QuIP#, and TurboQuant’s rotations; and the Beta and Gaussian marginals and concentration results in Probability and Statistics describe TurboQuant’s coordinate distribution. On the systems side, what quantization buys you in KV-cache capacity and throughput is the subject of LLM Systems & Inference and Serving & Load, and how quantized checkpoints are recognized and loaded is covered in Model Loading: Hub to GPU.
The same ideas appear across the industry: NVIDIA builds FP8 and INT4 kernels in CUTLASS and TensorRT-LLM on tensor-core mma; Google and DeepMind published TurboQuant, QJL, and related rotation-based research; Anthropic and OpenAI cut serving cost through weight and KV-cache quantization; Neural Magic, now part of the vLLM effort, built compressed-tensors and the Marlin and Machete kernels; and Meta’s models anchor the GGUF and llama.cpp edge-quantization ecosystem.
Further reading
Section titled “Further reading”- Foundational papers, all free on arXiv: LLM.int8() (2208.07339), GPTQ (2210.17323), SmoothQuant (2211.10438), AWQ (2306.00978), QLoRA/NF4 (2305.14314), QuIP# (2402.04396), QJL (2406.03482), TurboQuant (2504.19874)
- The current stack: llama.cpp / GGUF k-quants, bitsandbytes (NF4, LLM.int8()), AutoAWQ and GPTQModel,
compressed-tensorswith the Marlin/Machete kernels in vLLM, torchao, TensorRT-LLM FP8, and Burn for Rust
Key terms
Section titled “Key terms”- scale and zero-point: the parameters and of an affine quantizer, mapping a real range onto integer codes.
- symmetric quantization: affine quantization with , used for roughly zero-mean weights to avoid GEMM cross-terms.
- granularity: how many scales are kept (per tensor, channel, group, or block), trading metadata for distortion.
- granular noise: the rounding error of a uniform quantizer, with variance .
- calibration: choosing a clipping threshold or other quantizer parameters from sample data.
- W4A16 / W8A8: notation for weight and activation bit-widths, here 4-bit weights with 16-bit activations and 8-bit weights with 8-bit activations.
- dequant-fused GEMM: a kernel that dequantizes low-bit weights in registers or shared memory immediately before the matrix multiply.
- incoherence: the property, produced by random rotation, that a vector’s mass is spread evenly with no outlier coordinates.
- Lloyd–Max quantizer: the MSE-optimal scalar quantizer for a known distribution.
Summary
Section titled “Summary”- Quantization is lossy compression of a known distribution; every method bets on what the data looks like and quantizes optimally for that bet.
- The win is memory bandwidth: fewer bits per weight mean fewer bytes per decode step, but only if a fused dequant-plus-GEMM kernel exists for the format.
- Finer granularity and better calibration reduce distortion by giving each block its own, well-chosen range.
- Outliers are the enemy: methods have successively isolated, migrated, protected, and rotated them away.
- The frontier (QuIP#, TurboQuant) is incoherence via random rotation, which makes coordinate marginals known so a near-optimal scalar quantizer needs no calibration data, exactly what online KV-cache quantization requires.
Review questions
Section titled “Review questions”- Quantize to symmetric per-tensor INT8. Then explain what would happen to the small values if one entry were 127.0 instead.
Answer
Absmax is 1.27, so $s = 0.01$ and $q = [50, -127, 2]$, which dequantizes exactly. If one entry were 127.0, absmax min-max calibration would give $s = 1.0$, and 0.5 and 0.02 would round to codes 0 or 1 (with round-to-nearest-even, 0.5 rounds to 0), destroying them. This is the outlier problem, which finer granularity, clipping, or rotation addresses. - Why does INT4 group quantization with
group_size=128work when per-row INT4 does not?Answer
Each group gets its own scale and therefore clips to its own range. A 128-wide group has a far tighter dynamic range than a 4096-wide row, so the step size $\Delta$, and with it the granular noise $\Delta^2/12$, is much smaller, and an outlier only degrades its own group. - Why can INT4 weights be slower than FP16, and what makes them fast?
Answer
The savings are in memory traffic, and they are only realized if the kernel loads the packed 4-bit weights and dequantizes them in registers or shared memory right before the tensor-core matmul. A separate Python dequantization loop adds work and memory traffic, making it slower than FP16. Fused kernels such as Marlin, Machete, CUTLASS mixed-input GEMM, or tinygemm deliver the speedup. - Contrast how SmoothQuant and AWQ use per-channel scaling.
Answer
Both rely on the identity $(X\operatorname{diag}(s)^{-1})(\operatorname{diag}(s)W) = XW$. SmoothQuant uses it to move outlier difficulty from activations into weights, with $s_j = \max|X_j|^\alpha / \max|W_j|^{1-\alpha}$, so that both fit INT8 for W8A8. AWQ uses it to give roughly 1% of salient channels, identified by activation magnitude, more effective resolution before quantizing weights to INT4, choosing the exponent $\alpha$ by output MSE. - Why is the KV cache hard to quantize with calibration-based methods, and how does TurboQuant avoid needing calibration?
Answer
The KV cache holds keys and values of tokens generated at run time, so you cannot calibrate on them in advance. TurboQuant first applies a random Hadamard rotation, after which any vector looks uniform on the sphere and each coordinate's marginal is a known concentrated Beta distribution (about $\mathcal{N}(0, 1/d)$). With the distribution known a priori, a Lloyd–Max quantizer per coordinate is near-optimal, and a 1-bit QJL sketch of the residual makes inner-product estimates unbiased. - What extra state does each of NF4 and
Q4_Kstore, and roughly how many bits per weight doesQ4_Kcost?Answer
NF4 stores a fixed 16-level codebook and one absmax scale per block of 64, with the scales themselves double-quantized to 8 bits in blocks of 256, saving about 0.37 bits per parameter. `Q4_K` stores, per 256-weight super-block, a 6-bit scale and 6-bit min for each of 8 sub-blocks of 32, plus two FP16 super-scales, for about 4.5 bits per weight.