Highlights

Contents

Part IV
04

Quantization

Weights can be expensive to store and read. Quantization trades numerical detail for a smaller representation. Scales, grouping, kernels, and evaluation decide whether that trade produces a useful deployment.

YOU ARE HEREmessageschat templatetokenizertoken IDsconfig.jsonmodel.safetensorsint8 / int4 weightsOUR DECODER, REBUILT FROM THE CONFIGprefilldecodeattention kernelKV cacheparity checkvs referenceLM head → logitssamplingdetokenizereply textnext token

#Section 16Why Quantize an LLM

A model’s weights can exceed available device memory before any context is processed. Quantization reduces their representation so the system can fit or retain more history.

Model memory includes weight storage; GPU memory limits must also accommodate caches and working buffers. Reducing weight bytes can help memory bandwidth during decode and make deployment possible on constrained devices.

LLAMA 3 8B: WEIGHT SIZE AND DECODE LOWER BOUND PER FORMAT (H100, FUSED KERNELS)weights (GB)ms per token, batch 1bf1616.064.48int88.032.24int4, groups of 1284.141.16decode time follows bytes almost one for one, because decode is bandwidth-bound
Figure 4.23Llama 3 8B’s weights in three formats, and the decode lower bound each gives on an H100 with a fused kernel. Halving the bytes halves the time.

The precision vs quality trade-off comes from rounding weights to fewer possible values. How much that changes useful behavior depends on the model, method, and workload; evaluate rather than assuming a bit width is lossless.

PICTURE THIS: THE RECIPE SAYS 237.4 G OF FLOURscale in 5 g steps0100200300400reads 235 or 240 gscale in 100 g steps0100200300400reads 200 gerror ≤ 2.5 g: the cake is fineerror up to 50 g: the cake is notquantization chooses the step size of the scale
Figure 4.24The kitchen scales of the analogy. The same 237.4 g of flour, weighed on a scale with fine steps and on one with coarse steps.

#Section 17Numerical Representations

Every number in a model is stored in some fixed number of bits, and the format decides two different properties. Dynamic range is how large and how small a number can be represented at all. Precision is how finely numbers are spaced within that range. Floating-point formats spend bits on both; integer formats spend them all on evenly spaced steps.

A floating-point number has a sign bit, some exponent bits that pick a power of two, and some mantissa bits that pick a position between that power and the next. More exponent bits give more range; more mantissa bits give more precision.

Format Bits Sign / exponent / mantissa Largest value Smallest normal Relative step
FP32 32 1 / 8 / 23 3.40×10383.40 \times 10^{38} 1.18×10−381.18 \times 10^{-38} 1.2×10−71.2 \times 10^{-7}
FP16 16 1 / 5 / 10 65,504 6.1×10−56.1 \times 10^{-5} 9.8×10−49.8 \times 10^{-4}
BF16 16 1 / 8 / 7 3.39×10383.39 \times 10^{38} 1.18×10−381.18 \times 10^{-38} 7.8×10−37.8 \times 10^{-3}
INT8 8 integer 127 1 1 (absolute)

FP32 provides wide range and fine local precision. FP16 has narrower range but finer local detail than BF16, which retains a wide exponent range. INT8 uses evenly spaced integer codes with a separate scale. These representations trade storage against different kinds of numerical error.

WHERE THE BITS GO: SIGN, EXPONENT (RANGE), MANTISSA (PRECISION)FP32signexponent 8mantissa 23range ±3.4 × 1038, relative step 1.2 × 10−7FP16exp 5mantissa 10range ±65,504, relative step 9.8 × 10−4BF16exponent 8mant 7range ±3.4 × 1038 (same as FP32), relative step 7.8 × 10−3INT8integer, −128 … 127256 evenly spaced steps; the range comes from a separate scalebf16 = fp32with the low16 bits cut off
Figure 4.25Bit layouts. BF16 keeps FP32's exponent and gives up mantissa; FP16 keeps more mantissa and gives up range; INT8 has neither, just 256 evenly spaced steps.

Precision is easier to feel with a number. The decimal 0.1 stored in bf16 becomes 0.099609375. Near 12, a typical logit size, the gap between neighbouring representable values is 0.00000095 in fp32, 0.0078 in fp16 and 0.0625 in bf16. So a bf16 logit of 12 can only be 11.9375, 12 or 12.0625, never anything in between. Section 40 uses this fact to choose comparison tolerances.

Number of bits per parameter is what decides memory: 32, 16, 16 and 8 for the four formats, plus 4 for the INT4 formats that most local LLM deployments use. INT4 has 16 levels, −8-8 to 7, which is coarse enough that how the levels are placed matters a great deal.

#Section 18Quantization Fundamentals

Quantization maps floating-point values onto a small set of integers so they can be stored in fewer bits, and dequantization maps them back. The mapping is a straight line with two parameters. The scale factor ss is the width of one integer step in real units. The zero point zz is the integer that represents real zero. The quantization range is the real interval the integers cover.

q=clamp⁡ ⁣(round⁡ ⁣(xs)+z, qmin⁡, qmax⁡),x^=s (q−z)q = \operatorname{clamp}\!\left(\operatorname{round}\!\left(\frac{x}{s}\right) + z,\ q_{\min},\ q_{\max}\right), \qquad \hat{x} = s\,(q - z)

Read the first equation as quantize: measure xx in units of ss, round to the nearest whole step, shift by the zero point, and clip to the integers the format allows. Read the second as dequantize: undo the shift and multiply by the step width. The result x^\hat{x} is not xx again. The difference, x−x^x - \hat{x}, is the quantization error.

With real numbers

Choose a scale that maps the weight range to integer codes, round to the nearest supported code, then reconstruct by applying the scale. The figure shows the resulting rounding error.

Now INT4, with 7 as the largest positive level. The scale becomes 2.54/7=0.36292.54 / 7 = 0.3629, eighteen times coarser. The integers are [2,−4,0,7,−1,3][2, -4, 0, 7, -1, 3] and the reconstruction is [0.7257,−1.4514,0,2.54,−0.3629,1.0886][0.7257, -1.4514, 0, 2.54, -0.3629, 1.0886]. The errors are now up to 0.178, and the small weight 0.046 has become exactly zero.

SIX WEIGHTS, SNAPPED TO AN INT8 GRID (STEP 0.02) AND AN INT4 GRID (STEP 0.3629)int8: every weight lands within 0.010.817-1.2730.0462.54-0.3091.128int4: coarse steps, 0.046 becomes 0-4-3-2-101234567grey: original weight orange: where it is stored slate numbers: the int4 code
Figure 4.26The six weights on a number line, with the INT8 grid (fine ticks) and the INT4 grid (coarse ticks). Each weight snaps to its nearest tick; with INT4, 0.046 snaps to zero.

Two kinds of error

As long as xx is inside the range, the error is rounding error, at most half a step, ∣x−x^∣≤s/2|x - \hat{x}| \le s/2. Outside the range, the clamp kicks in and the error is clipping error, which can be arbitrarily large. Choosing the range is a trade between them. A wide range, set by the single largest value, never clips but makes every step wide. A narrow range gives fine steps for the bulk of the values and clips the rare large ones. For weights, which are fixed and known in advance, most methods use the maximum magnitude and avoid clipping; methods that search for a slightly smaller range sometimes do better.

#Section 19Symmetric vs Asymmetric Quantization

The example above used zero-centered ranges: [−2.54,2.54][-2.54, 2.54] mapped to integers centred on 0, with zero point z=0z = 0. This is symmetric quantization. It uses signed integer ranges (−127-127 to 127 for INT8, usually leaving −128-128 unused so the range is balanced), and it is the natural choice when values are spread roughly evenly on both sides of zero, as trained weights are.

Asymmetric quantization maps an arbitrary interval [xmin⁡,xmax⁡][x_{\min}, x_{\max}] onto the unsigned integers 0 to 255. The scale is (xmax⁡−xmin⁡)/255(x_{\max} - x_{\min}) / 255 and the zero point is the integer that lands on real 0, z=round⁡(−xmin⁡/s)z = \operatorname{round}(-x_{\min} / s). It pays off when values are lopsided. Activations after SiLU are a good example: they can dip slightly below zero but mostly sit above it.

With real numbers

For skewed values, an asymmetric range allocates more codes where the data actually lies. A symmetric range may waste codes on a large unused negative region.

ACTIVATIONS [−0.28, 0, 0.41, 1.93, 3.70] IN 256 INT8 CODESsymmetric: s = 0.0291, z = 0118 codes never used-10−0.2800140.41661.931273.70-128127asymmetric: s = 0.0156, z = 180−0.28180440.411421.932553.700255
Figure 4.27The same five activations, quantized symmetrically and asymmetrically. Symmetric wastes the codes below −10 on values that never occur; asymmetric spends every code on the range that is actually used.

Trade-offs

Asymmetric is more accurate for skewed data, but the zero point costs something at matmul time. A product of a dequantized weight and an activation, sw(qw−zw)⋅sa(qa−za)s_w (q_w - z_w) \cdot s_a (q_a - z_a), expands into four terms, and the extra ones have to be computed or precomputed. With z=0z = 0 that algebra disappears. So the usual compromise is symmetric for weights, where it costs little accuracy, and asymmetric or symmetric-with-calibration for activations. One rule holds in both: real zero must map to an exact integer. Padding, masked positions and ReLU outputs are exactly zero, and they must come back as exactly zero.

#Section 20Granularity

A scale has to be shared by some set of values, and the choice of that set is called granularity. With per-tensor quantization, one scale covers a whole weight matrix: 2 million numbers in one of Qwen3's query projections. With per-channel quantization, each output row of the matrix gets its own scale, so a matrix with 2,048 rows has 2,048 scales. With per-group quantization, each row is cut into groups of consecutive weights, typically 32, 64 or 128, and each group gets its own scale.

Why smaller groups preserve more information

A scale is set by the largest magnitude it must cover. One outlier inflates the scale for everything that shares it, and every other value in the set is rounded more coarsely. Smaller groups confine the damage: the outlier inflates only its own group.

Here is a real example. Row 0 of the query projection in layer 0 of Qwen3-0.6B has 1,024 weights. Their typical magnitude is small: the median absolute value is 0.0082 and 99% of them are below 0.0304. The largest is 0.0518, an outlier about six times the median. Quantize the row to 4 bits in three ways:

A large outlier sets a coarse shared scale. Smaller groups contain that effect, allowing other groups to represent their narrower ranges more precisely.

QWEN3-0.6B, LAYER 0 q_proj, ROW 0: LARGEST |w| IN EACH GROUP OF 1280.020.040.060.05180+0.0304128+0.0299256+0.0352384+0.0265512+0.0344640+0.0315768+0.0280896+one scale per row must cover 0.0518median |w|int4 RMS errorone scale per row17.8%groups of 12811.7%groups of 3210.0%+0.016, +0.125, +0.5bits per weight for scales
Figure 4.28The largest magnitude in each group of 128 for a real Qwen3-0.6B weight row. With one scale for the row, every group is quantized as if it held the 0.0518 outlier; with one scale per group, only the first group is.

Metadata overhead

Each scale has to be stored, usually in fp16, so smaller groups cost bits. One 16-bit scale per 128 weights adds 16/128=0.12516 / 128 = 0.125 bits per weight; per 32 weights it adds 0.5. Asymmetric schemes also store a zero point per group. That is why "4-bit" models are really 4.125 to 4.5 bits per weight, and why group size 128 is the common default: most of the accuracy of small groups for an eighth of a bit.

#Section 21Weight-Only Quantization

There are two things you could quantize in a linear layer: the weights, which are fixed, and the activations, which change with every input. Weight-only quantization means quantizing model weights and keeping activations in floating point. It is the most common scheme for LLM inference, and its name in papers is W8A16 or W4A16: 8-bit or 4-bit weights, 16-bit activations.

With INT8 weight storage, each linear layer keeps an int8 matrix and one fp16 scale per output row (or per group). The matmul itself still runs in bf16: dequantization during computation turns each weight back into bf16 just before it is multiplied. In a well-written kernel this happens in registers, one tile at a time, so the bf16 weights never exist in memory.

python
def quantize_rows(w):                         # w: (out, in), bf16
    s = w.abs().amax(dim=1, keepdim=True) / 127   # (out, 1): one scale per row
    q = torch.round(w / s).clamp(-127, 127).to(torch.int8)
    return q, s.to(torch.float16)

def linear_w8(x, q, s):                       # x: (B, T, in), bf16
    w = q.to(x.dtype) * s.to(x.dtype)         # dequantize: (out, in)
    return x @ w.T                            # a fused kernel never builds w

Memory savings

Actual weight storage depends on which tensors are quantized and on scale metadata. Embeddings or norms may remain in floating point.

Better than rounding

The code above is round-to-nearest, the simplest method. It works well at 8 bits and loses noticeably at 4. Two methods from 2022 and 2023 do much better at 4 bits without retraining. GPTQ (Frantar and colleagues, 2022) quantizes a layer's weights one column at a time and adjusts the not-yet-quantized columns to compensate for each column's rounding error, using second-order information from a few hundred calibration samples. AWQ (Lin and colleagues, 2023) observes that a small fraction of input channels, those with large activations, matter most, and scales them up before quantization so their weights are rounded more finely. Both produce ordinary int4 weights with group scales, so they run on the same kernels.

#Section 22Quantization and Performance

Smaller checkpoints reduce transfer and loading work. Reduced weight memory can leave room for more cache, while fewer bytes read per step can help bandwidth-bound decode.

Those numbers assume something that is not automatic: kernel support. The speed-up only appears if a kernel reads the compressed weights from memory and dequantizes them on the chip, inside the matmul. Such fused kernels exist for common formats and GPUs, for example Marlin for 4-bit weights on recent NVIDIA GPUs, and serving engines pick them automatically. Without one, the format saves memory and costs speed.

Why a smaller model may still run slower

Dequantizing a whole matrix into a main-memory temporary adds a write and another read before multiplication. That path can move more data than the original floating-point model. Fuse reconstruction into the compute kernel when supported.

BYTES MOVED THROUGH HBM PER WEIGHT, ONE DECODE STEP, LLAMA 3 8B ON AN H100bf162 B → 4.48 msbf16 Wread 2matmulint8, fused1 B → 2.24 msint8 W + sread 1dequantize inregisters + matmulint8, naive5 B → 11.20 msint8 W + sread 1dequantizewrite 2bf16 copyread 2matmulsmaller file,slower run
Figure 4.29Bytes moved per weight in a decode step. Plain bf16 reads 2. A fused int8 kernel reads 1 and dequantizes on the chip. A naive int8 path reads 1, writes 2 and reads 2 again: smaller on disk, slower to run.

Dequantization overhead is the other cost. Even in a fused kernel, each weight needs a convert and a multiply by its scale, and for int4 an unpack from half a byte. In memory-bound decode at small batch this work hides behind the memory reads and is free. In compute-bound prefill, or at large batch, it is extra arithmetic on the critical path, and a W4A16 model can prefill more slowly than the bf16 original. Measure prefill and decode separately (Section 23), because quantization can help one and hurt the other.

#Section 23Measuring Quantized Models

A quantized model is a different model. It must be measured on its own, against the original, with the same prompts, template and decoding settings. Seven measurements cover it.

Checkpoint size is the bytes on disk, including scales and zero points. GPU/CPU memory is the peak memory while running, which includes the cache, activations and the framework's workspace, not just the weights; measure it at the batch size and context length you will serve. Decode speed is tokens per second for one stream at a fixed context, after a warm-up, averaged over several runs. Prefill speed is prompt tokens per second, or time to first token, at a fixed prompt length. Report both, for the reason given in Section 22.

Quality regression is measured three ways, from cheapest to most meaningful. Logit differences compare the quantized model's next-token distribution with the original's on the same inputs: the largest absolute difference in logits, the KL divergence between the two softmax distributions,

DKL(p ∥ p^)=∑ipilog⁡pip^i,D_{\text{KL}}(p \,\|\, \hat{p}) = \sum_i p_i \log \frac{p_i}{\hat{p}_i},

which reads as "the average extra surprise when the quantized model's probabilities p^\hat{p} are used in place of the original's pp”, and the top-1 agreement, the fraction of positions where both models pick the same most likely token. Perplexity on held-out text summarizes the same thing as a single number (the training chapter defines it, Unit III). And end-task evaluation, running real benchmarks such as question answering, maths word problems or code generation, tells you whether a difference in logits actually changes answers.

Measure Tells you Watch for
Checkpoint size download and load cost scales and zero points included
Peak memory what fits, how many users measured at serving batch and context
Decode tokens/s streaming speed warm-up, fixed context, same batch
Prefill tokens/s or TTFT wait before the first word can get worse when decode gets better
Logit diff, KL, top-1 agreement how far the distribution moved per position, not just averaged
Perplexity overall fit to text same text and tokenizer for both models
End-task scores whether answers change enough examples to see a real difference