Inference Engineering

Lesson 10: Quantization · Workbook

Quantization: the workbook

The full working behind lesson 10. Number formats, how a quantized weight and its scale are stored, why outliers stretch the grid, GPTQ and AWQ, SmoothQuant and FP8, what gets faster for each scheme, quantizing the KV cache, and seven exercises to check yourself.

Llama 3.1 70B takes 141.1 GB in BF16, more than the 80.0 GB on one H100, so for the big model quantization decides whether it runs on one GPU at all.

The two benefits do not always come together. Fewer bits always means less memory. It only means less time when the thing you made smaller was the bottleneck. The roofline lesson showed that decode is limited by memory bandwidth and prefill by arithmetic. So a scheme that shrinks only the weights speeds up decode and leaves prefill alone, and a scheme that also runs the arithmetic in 8 bits can speed up both. This lesson builds that up from how a quantized number is stored.

Number formats

A floating-point number has a sign bit, some exponent bits and some mantissa bits. The exponent sets the range: how large and how small a number can be. The mantissa sets the precision: how finely numbers are spaced relative to their size. Every format is a trade between the two.

FormatBits (sign, exponent, mantissa)Largest valueSpacing relative to the value
FP321, 8, 233.40 × 10³⁸0.0000119%
BF161, 8, 73.39 × 10³⁸0.781%
FP161, 5, 1065,5040.0977%
FP8 E5M21, 5, 257,34425%
FP8 E4M31, 4, 344812.5%

BF16 keeps FP32’s 8 exponent bits, so it has the same range, and gives up precision. That is why models train in it: values rarely overflow. FP16 has more precision but tops out at 65,504, so large activations can overflow.

FP8 comes in two encodings, proposed together by Micikevicius et al. The paper recommends E4M3 for weights and activations, which need precision, and E5M2 for gradients during training, which need range. E5M2 follows the IEEE conventions. E4M3 gives up infinities and keeps a single bit pattern for “not a number”, which buys it one more power of two: its largest value is 448 instead of the 240 the paper says it would otherwise be. H100 (Hopper) and L4 (Ada) tensor cores compute in FP8; the A100 (Ampere) does not.

Integers are different. INT8 holds whole numbers from −128 to 127, and INT4 from −8 to 7. They are evenly spaced, with no exponent. A weight like 0.0132 is not an integer, so integer formats need one more piece: a scale.

How a quantized weight is stored

The simplest scheme is absmax quantization. Take a group of weights. Find the largest magnitude in the group and call it mm. With bb bits, the symmetric integer range is −(2b−1−1)-(2^{b-1}-1) to 2b−1−12^{b-1}-1, so for 4 bits that is −7 to 7. The scale maps mm to the top of that range:

s=m2b−1−1,qi=round⁡ ⁣(wis),w^i=qi⋅ss = \frac{m}{2^{b-1} - 1}, \qquad q_i = \operatorname{round}\!\left(\frac{w_i}{s}\right), \qquad \hat w_i = q_i \cdot s

The integers qiq_i are the codes. Memory holds the codes plus one scale per group. To use a weight, a kernel multiplies its code by the scale to get back w^i\hat w_i; this is dequantization. Rounding moves each weight by at most half a step, so the error is at most s/2s/2.

Absmax assumes the group is centred on zero. If it is not, a second number, the zero point, shifts the grid so it covers the group’s minimum to maximum. That costs a few more bits per group and wastes no levels on values that never occur.

Each group stores its scale (and zero point) beside its codes, so the real cost per weight is

bits per weight=b+scale bits+zero-point bitsgroup size.\text{bits per weight} = b + \frac{\text{scale bits} + \text{zero-point bits}}{\text{group size}} .

The overhead shrinks as groups grow. Three layouts you will meet:

Smaller groups mean more scales to store, but each scale fits its own weights more tightly. The next section shows why that matters.

One outlier stretches the grid

The scale is set by the largest value in the group. If one weight is much larger than the rest, the grid has to stretch to reach it, and the ordinary weights are left with only a few levels between them.

The figure below takes 256 weights drawn from a normal distribution, so most fall within ±2 standard deviations (σ), and replaces three of them with outliers. The grey lines are the levels each group can represent. Each weight’s dot is where it really is, and the short pink tick is where it lands after rounding.

One row of 256 weights, and what three giants do to it

Plays by itself; change a setting to take over.

Stored
Grid step
Levels in use
RMS error, ordinary weights

weightoutlierrounded value, errorlevels

256 weights from a seeded normal sample with three outliers. One scale per group, set by absmax. Lower the group size so the weights away from the outliers get their own tight scales (the outliers' own groups stay stretched), or set the outlier size to none to see the clean case.

With no outliers and one 4-bit scale for all 256 weights, the grid step is 0.33σ and the RMS (root-mean-square) rounding error is 0.09σ. Add three 12σ outliers and the step grows to 1.71σ. The ordinary weights now land on only 3 of the 15 levels, and their error rises to 0.51σ, more than 5 times worse.

Groups contain the damage. With groups of 32, the weights that share a group with an outlier still suffer (0.51σ), but the other groups keep their own tight scales (0.09σ). More bits also help: at 8 bits the same per-row grid has 255 levels, and the error falls to 0.03σ.

Weights are easy, activations are hard

Weights are fixed, so you can study them offline and spend hours picking good codes. Activations, the values flowing between layers, change with every input, so their scales must be cheap to compute, and their outliers are much worse.

Dettmers et al. measured this in the LLM.int8() paper. They found features with magnitudes up to 20 times larger than other dimensions. In their analysis, at around 6.7 billion parameters a “phase shift” occurs: these outliers then appear in every transformer layer and in about 75% of sequence positions, yet at the 6.7B scale they are concentrated in only 6 feature dimensions. They matter: setting those dimensions to zero degraded validation perplexity by 600 to 1000% in their measurements. (Perplexity measures how surprised a model is by real text: roughly, how many equally likely choices it is hedging between at each token. Lower is better, and gaps of a few tenths are usually considered small.)

Plain 8-bit quantization breaks on these models. On C4 at 13B parameters, the paper’s Table 1 reports a perplexity of 12.45 in 32-bit floats and 19.08 with per-tensor absmax INT8 (lower is better). Their fix, mixed-precision decomposition, splits each matrix multiply: the few outlier dimensions run in 16-bit and the other 99.9% of values in 8-bit. That recovers 12.45. The split mainly saves memory: the paper notes its overhead can slow models smaller than 6.7B parameters compared with FP16, and the GPTQ authors describe LLM.int8() as having the same runtime as the FP16 baseline.

Write a layer as Y=XWY = XW, where XX is tokens × channels (M×KM \times K in lesson 1’s terms; a channel is one of the KK hidden dimensions) and WW is channels × outputs (K×NK \times N). A scale per row of XX or per column of WW can be applied after the sum; a scale per channel cannot, because every output sums over all channels.

Xiao et al. explain the problem in SmoothQuant in terms of levels. Activation outliers are about 100 times larger than most activations. With one 8-bit scale for the whole tensor, a channel whose largest value is mim_i when the tensor’s largest is mm gets about 28⋅mi/m2^8 \cdot m_i / m levels, which is 2.56 when the ratio is 100. Giving each activation channel its own scale would fix it, but fast tensor-core matrix multiplies can only apply scales along the outer dimensions (per token for activations, per output channel for weights), not along the inner channel dimension being summed over.

Their observation is that the outliers stay in the same few channels. So SmoothQuant divides each input channel jj of the activations by a factor sjs_j and multiplies the matching row of the weights by the same factor. The product is unchanged, and the difficulty is split between the two:

Y=(Xdiag⁡(s)−1)(diag⁡(s) W),sj=max⁡∣Xj∣αmax⁡∣Wj∣1−αY = \big(X \operatorname{diag}(s)^{-1}\big)\big(\operatorname{diag}(s)\, W\big), \qquad s_j = \frac{\max |X_j|^{\alpha}}{\max |W_j|^{1-\alpha}}

With α=0.5\alpha = 0.5, their default for most models, both sides end up with similar ranges, and both can be quantized to INT8 (W8A8: 8-bit weights, 8-bit activations). On OPT-175B, the paper’s Table 3 reports average zero-shot accuracy (accuracy on benchmark tasks the model was not tuned for) of 66.9% in FP16, 35.5% with naive W8A8, and 66.8% with its most aggressive SmoothQuant setting. It reports up to 1.56× speedup and 2× memory reduction.

FP8 is the other answer. Floating-point levels are dense near zero and sparse far out, so one large value costs the small ones less precision than on an even integer grid. The FP8 paper’s Table 5 shows this for post-training quantization with per-channel weight scales and per-tensor activation scales: GPT-3 6.7B has a wikitext-103 perplexity of 8.51 in 16-bit, 10.29 in INT8 and 8.41 in E4M3.

Weight-only quantization: GPTQ and AWQ

If decode is limited by reading weights, you can quantize only the weights and leave the math alone. This is W4A16: 4-bit weights, 16-bit activations. The kernel reads 4-bit codes from memory, dequantizes them to BF16 inside the chip, and multiplies in BF16. Activations never need a scale, so their outliers stop being a problem.

The question becomes how to pick 4-bit codes that keep quality. Rounding each weight to the nearest level (RTN, round-to-nearest) is the baseline.

GPTQ (Frantar et al.) quantizes the weights of a layer one column at a time. After rounding a column, it adjusts the columns not yet quantized to cancel the error that rounding introduced, using a measure, computed from a small calibration set of real inputs (128 random 2,048-token segments in the paper), of how much the layer’s output changes when each weight moves (the Hessian of the layer’s squared error, which the paper approximates). The paper quantizes 175B-parameter models in about four GPU hours. On OPT-175B its Table 5 reports WikiText-2 perplexity of 8.34 in FP16, 10.54 with 4-bit RTN, and 8.37 with 4-bit GPTQ. Its own kernels run the 3-bit OPT-175B on one A100 about 3.25× faster per token than FP16 spread over five GPUs.

AWQ (Lin et al.) starts from the observation that weights are not equally important. Keeping just 1% of weight channels in FP16 removes much of the error, provided you pick the channels with the largest activations, not the largest weights. In its Table 1, OPT-6.7B at 3-bit, group 128 has perplexity 23.54 with RTN, 11.39 when the 1% of channels picked by activation stay in FP16, and 22.37 when they are picked by weight size (FP16: 10.86). Mixed precision is slow on hardware, so instead AWQ scales those salient channels up before quantizing (and the activations down to compensate), which reduces their relative rounding error. The matching division of the activations can usually be folded into the previous operation. It uses group size 128 throughout. For Llama-2-70B at INT4 with group 128, its Table 4 reports WikiText-2 perplexity of 3.32 in FP16, 3.46 with RTN, 3.42 with GPTQ and 3.41 with AWQ.

What gets faster

The figure below computes the floors from the same formulas as lesson 1, for one user, a 1,024-token context at decode, and a 2,048-token prompt at prefill; the GPU figures in the lesson use the same settings. Weight-only INT4 uses 4.125 bits per weight, scales included. In every quantized row the embedding table and the output layer (lm_head) stay in 16 bits, as GPTQ, AWQ and the usual FP8 recipes leave them; lm_head is read on every decode step. W8A8 runs the matmuls on FP8 or INT8 tensor cores, which on the H100 peak at 1,979 trillion operations per second, twice the BF16 rate. Attention stays in BF16 over a BF16 KV cache in every row.

Llama 3.1 8B

SchemeWeights (line: 80.0 GB of HBM)Decode floor, per tokenPrefill floor, 2,048 tokens
BF1616.1 GB4.52 ms30.0 ms
FP8 W8A89.1 GB2.44 ms15.6 ms
INT8 W8A89.1 GB2.44 ms15.6 ms
INT4 W4A165.7 GB1.43 ms30.0 ms

Llama 3.1 70B

SchemeWeights (line: 80.0 GB of HBM)Decode floor, per tokenPrefill floor, 2,048 tokens
BF16141.1 GB (does not fit)41.6 ms289 ms
FP8 W8A872.7 GB21.2 ms147 ms
INT8 W8A872.7 GB21.2 ms147 ms
INT4 W4A1639.5 GB11.3 ms289 ms

memory-bound or bytes stored compute-bound

Floors for one H100 SXM, batch 1. Bar color shows which resource limits the matmuls. Rows marked 'does not fit' are still computed as if the weights were on one GPU; splitting them across GPUs is lesson 13.

Decode is memory-bound in every row, so its floor tracks bytes per weight. For Llama 3.1 8B it drops from 4.52 ms in BF16 to 2.44 ms at 8 bits and 1.43 ms with INT4 weights: 221, 410 and 700 tokens per second for one user. The INT4 gain is 3.2× rather than 4× because the scales add bytes, the 16-bit output layer is read every step, and the KV cache reads do not shrink. It is still larger than the 2.8× by which the model shrinks: the 16-bit embedding table takes memory, but only one row of it is read per token.

Prefill is compute-bound. W4A16 still multiplies in BF16, so its floor is exactly the BF16 one, 30.0 ms. Real kernels also spend time dequantizing, so in practice it can be slightly slower. W8A8 halves the arithmetic time, to 15.6 ms. FP8 and INT8 give the same floor here because the H100 has the same peak for both. On an A100 only INT8 is available.

Memory decides what runs at all. Llama 3.1 70B needs 141.1 GB in BF16, 72.7 GB at 8 bits and 39.5 GB at INT4. Only the last two fit on one H100, and at 8 bits the 7.3 GB left over is less than the 10% a serving engine holds back, so there is no room for the KV cache.

Batching changes the picture. With bb users the weights are read once and used bb times, so decode matmuls become compute-bound once the batch is large enough. In BF16 on an H100 that happens at about 296 sequences. With W4A16 the weights are about four times smaller but the math is still BF16, so the matmuls hit the BF16 compute wall at about 77. Past that, adding users costs W4A16 compute time, so its lead over BF16 shrinks steadily: its matmul time is roughly bb ÷ 295 of BF16’s, and the lead is gone by about 296, where BF16 also becomes compute-bound. W8A8 moves the compute wall up as well, reaching it at about 296. So weight-only quantization is the tool for small batches and memory-limited deployments, and W8A8 is the tool for busy servers that are compute-bound.

Quantizing the KV cache

The KV cache (lesson 4) is the third thing you can shrink. For Llama 3.1 8B it is 131 KB per token in BF16 and half that in FP8. Two things follow.

First, capacity. Beside BF16 weights, with 10% held back as in lesson 4, an H100 has room for about 426,784 tokens of BF16 cache, or 853,568 in FP8. That is twice as many concurrent tokens for continuous batching (lesson 6) to schedule.

Second, speed at long context. Attention reads the whole cache every decode step, and weights do not dominate there. At 13 users with 32,768 tokens each, as many as fit in BF16, the step floor drops from 21.1 ms to 12.8 ms when the cache moves from BF16 to FP8.

vLLM supports FP8 KV caches in both E4M3 and E5M2, with one scale per tensor or per attention head. Its documentation recommends calibrating those scales on data; by default they are all set to 1.0.

Choosing a scheme

The short version:

The papers above report small quality losses on the models and benchmarks they tested. A small perplexity gap does not guarantee every task is unaffected, so evaluate on your own workload.

Check yourself

Work each one out before opening the answer. All answers come from the same formulas as the figures.

Exercise 1. GGUF Q4_0 stores blocks of 32 four-bit codes with one FP16 scale. How many bits per weight is that, and how large is Llama 3.1 8B in it, if every weight is stored that way? Enter the size in GB.

GB
Show the worked answer

4.5 bits per weight: 4+16/324 + 16/32. At that rate, 8.03 billion weights take 4.5 GB, against 16.1 GB in BF16. (Real GGUF files often keep some tensors at higher precision, so the file is usually a little larger.)

Exercise 2. Llama 3.1 70B with INT4 weights, group 128, FP16 scales (embedding and output layer in 16 bits) on one H100 (80 GB, 10% held back as in lesson 4). How many tokens of BF16 KV cache fit beside the weights (328 KB per token)? What about with 8-bit weights? Enter the INT4 figure.

tokens
Show the worked answer

The weights take 39.5 GB (4.1254.125 bits each for the layer matrices, 16 for the embedding and output layer), leaving room for about 99,186 tokens of cache. With 8-bit weights (72.7 GB) no tokens fit: the weights alone take more than the 72.0 GB left after the reserve. This ignores activations and framework overhead.

Exercise 3. Llama 3.1 70B with 4-bit codes, group 64, an FP16 scale and a 4-bit zero point per group (embedding and output layer in 16 bits). How many bits per weight, and how much weight memory? Does it fit beside a 100,000-token BF16 KV cache (328 KB per token) on one H100, with 10% held back?

Show the answer

4.3125 bits per weight: 4+(16+4)/644 + (16 + 4)/64. The weights take 41.1 GB and the cache 32.8 GB, so 73.9 GB in all: it does not fit in the 72.0 GB left after the reserve, before activations and framework overhead.

Exercise 4. An activation tensor is quantized to INT8 with one scale. One channel reaches 100 while the rest reach about 1. Roughly how many levels do the ordinary channels get? With SmoothQuant at α = 0.5, if that channel's weights reach 1, what is its smoothing factor?

Show the answer

About 2.56 levels (28⋅1/1002^8 \cdot 1/100), so most of those activations round to zero or one step. SmoothQuant’s factor is s=1000.5/10.5=s = 100^{0.5} / 1^{0.5} = 10: the activation channel is divided by 10 (its maximum becomes 10) and the matching weights are multiplied by 10 (their maximum becomes 10). Both now share the range evenly.

Exercise 5. At short context, about what batch size makes Llama 3.1 8B's decode matmuls compute-bound on an H100 with BF16 weights, with W4A16, and with FP8 W8A8?

Show the answer

About 296 in BF16, 77 with W4A16 and 296 with FP8. W4A16 reads about a quarter of the bytes for the same BF16 math, so it reaches the BF16 compute ceiling at a quarter of the batch (the 16-bit output layer pushes that a little later in the figures above). FP8 halves the bytes and doubles the ceiling, so it crosses at the same batch as BF16, but at twice the throughput. The H100’s FP8 ridge point is about 591 FLOPs per byte, against 295 in BF16.

Exercise 6. From lesson 1: an H100 does about 989 trillion BF16 FLOPs per second and reads 3.35 TB per second from memory. How many FLOPs must a step do per byte it reads before arithmetic, not memory, becomes the limit?

FLOPs per byte
Show the worked answer

About 295 FLOPs per byte: 989 × 10¹² ÷ 3.35 × 10¹². Decode for one user does 2 FLOPs per weight, about 1 FLOP per byte of BF16 weights, far below that line, which is why shrinking the bytes speeds it up. Even with 4-bit weights it does only about 4 FLOPs per byte, still memory-bound; a 2,048-token prefill is far above the line, which is why 4-bit weights leave it unchanged.

Exercise 7. From lesson 5: Llama 3.1 8B has 32 query heads but only 8 KV heads (32 layers, head dimension 128). If every query head kept its own key and value, how many KB of KV cache would each token take in BF16?

KB
Show the worked answer

524 KB: 2 × 32 × 32 × 128 × 2 bytes, 4 times the 131 KB the model really stores. Sharing heads and quantizing the cache stack: with shared heads and an FP8 cache, each token takes 65.5 KB.

Sources

  1. Dettmers, Lewis, Belkada, Zettlemoyer (2022). LLM.int8(): 8-bit Matrix Multiplication for Transformers at Scale. NeurIPS 2022. arXiv:2208.07339. Emergent outlier features from 6.7B parameters; mixed-precision decomposition; Table 1 perplexities
  2. Xiao, Lin, Seznec, Wu, Demouth, Han (2023). SmoothQuant: Accurate and Efficient Post-Training Quantization for Large Language Models. ICML 2023. arXiv:2211.10438. Section 3 on why activations are hard, Equation 4, Table 3 (OPT-175B)
  3. Frantar, Ashkboos, Hoefler, Alistarh (2023). GPTQ: Accurate Post-Training Quantization for Generative Pre-trained Transformers. ICLR 2023. arXiv:2210.17323. Tables 3, 5 and 6
  4. Lin, Tang, Tang, Yang, Chen, Wang, Xiao, Dang, Gan, Han (2024). AWQ: Activation-aware Weight Quantization for LLM Compression and Acceleration. MLSys 2024. arXiv:2306.00978. Tables 1 and 4; group size 128 throughout
  5. Micikevicius et al. (2022). FP8 Formats for Deep Learning. arXiv:2209.05433. Table 1 (E4M3 and E5M2 encodings) and Table 5 (post-training quantization, int8 against E4M3)
  6. Google Cloud. Improve your model's performance with bfloat16. BF16 has the same dynamic range as FP32
  7. llama.cpp, ggml-common.h (block_q8_0 and block_q4_0). Blocks of 32 codes with one FP16 scale
  8. vLLM documentation. Quantized KV Cache
  9. NVIDIA H100 product page, specifications table. Dense peaks: 989 TFLOP/s BF16, 1,979 TFLOP/s FP8 and 1,979 TOPS INT8 (halve the sparsity figures)
  10. Llama 3.1 8B and 70B config.json (Meta, via Hugging Face)

Back to lesson 10: Quantization