TExcelTAD
Home › Deployment & MLOps: Serving, Pipelines, Monitoring › Quantization: Smaller Numbers, Faster Models

Quantization: Smaller Numbers, Faster Models

A trained network stores every weight as a 32-bit float, but it rarely needs that precision. Quantization stores weights, and often activations too, as 8-bit (or smaller) integers plus a few scale factors. The model gets about four times smaller, it moves four times fewer bytes through memory, and on CPUs, mobile NPUs and GPUs with integer units the matrix products themselves run faster. The price is a rounding error in every number. This lesson builds the arithmetic from scratch, measures the error on a real trained model, and then uses ONNX Runtime to quantize the same kind of model the way production systems do.

For 4-bit codes, block-wise scales and NF4 (the format used to fine-tune large language models), see QLoRA. For quantization as a signal-processing topic (the uniform quantizer, 6 dB per bit, Lloyd-Max), see Quantization in Information Theory.

The affine map from floats to integers

Pick a real range [α,β][\alpha, \beta] that should be representable and an integer range [qmin⁡,qmax⁡][q_{\min}, q_{\max}], for example [0,255][0, 255] for uint8. The scale ss is the size of one integer step in real units, and the zero point zz is the integer that represents the real number 0:

s=β−αqmax⁡−qmin⁡,z=round⁡(qmin⁡−αs)s = \frac{\beta - \alpha}{q_{\max} - q_{\min}}, \qquad z = \operatorname{round}\Big(q_{\min} - \frac{\alpha}{s}\Big)
q=clip⁡(round⁡(xs)+z,  qmin⁡,  qmax⁡),x^=s (q−z)q = \operatorname{clip}\Big(\operatorname{round}\big(\tfrac{x}{s}\big) + z,\; q_{\min},\; q_{\max}\Big), \qquad \hat{x} = s\,(q - z)

The range is always widened to contain 0, so that zz is an exact integer and real zeros (padding, ReLU outputs, pruned weights) stay exactly zero after the round trip.

realuint8 alpha = -1.0 0.0 beta = 2.5 0 z = 73 255 one integer step = scale s = 3.5 / 255

Two errors come out of this map. Inside the range, rounding error is at most s/2s/2, and for values spread smoothly over many steps it behaves like uniform noise with variance s2/12s^2/12. Outside the range, clipping error can be arbitrarily large. A wide range means a big ss (more rounding error); a narrow range clips more. Choosing the range is the whole craft.

Symmetric quantization fixes z=0z = 0 and uses a signed range [−(2b−1−1), 2b−1−1][-(2^{b-1} - 1),\, 2^{b-1} - 1] with s=max⁡∣x∣/(2b−1−1)s = \max|x| / (2^{b-1} - 1). It is the usual choice for weights, which are roughly centred on zero, because a zero point of 0 makes the integer matrix product simpler. Asymmetric (affine) quantization suits activations such as ReLU outputs, which are never negative: a symmetric code would waste its whole negative half on them.

python · try it yourself
import numpy as np

def affine_params(lo, hi, bits=8):
    """Scale and zero point that map [lo, hi] (widened to include 0) onto the integers 0 .. 2^bits - 1."""
    qmin, qmax = 0, 2 ** bits - 1
    lo, hi = min(lo, 0.0), max(hi, 0.0)
    scale = (hi - lo) / (qmax - qmin)
    zero_point = int(np.clip(round(qmin - lo / scale), qmin, qmax))
    return scale, zero_point, qmin, qmax

def quantize(x, scale, zp, qmin, qmax):
    return np.clip(np.round(x / scale) + zp, qmin, qmax).astype(np.int32)

def dequantize(q, scale, zp):
    return scale * (q - zp)

x = np.array([-1.0, 0.0, 0.3, 2.5])
s, z, qmin, qmax = affine_params(x.min(), x.max())
q = quantize(x, s, z, qmin, qmax)
print(f"scale {s:.5f}, zero point {z}")
print("x      :", x)
print("q      :", q)
print("x_hat  :", np.round(dequantize(q, s, z), 4))

rng = np.random.default_rng(0)
acts = np.maximum(rng.normal(0.5, 1.0, 10_000), 0.0)        # ReLU outputs: never negative
s, z, qmin, qmax = affine_params(acts.min(), acts.max())
q = quantize(acts, s, z, qmin, qmax)
err_affine = np.abs(dequantize(q, s, z) - acts)
s_sym = np.abs(acts).max() / 127                              # symmetric int8: zero point fixed at 0
q_sym = np.clip(np.round(acts / s_sym), -127, 127)
err_sym = np.abs(q_sym * s_sym - acts)
print(f"\nReLU activations in [{acts.min():.2f}, {acts.max():.2f}]")
print(f"affine uint8   : scale {s:.5f}, zero point {z:3d}, levels used {len(np.unique(q)):3d}, max error {err_affine.max():.5f}")
print(f"symmetric int8 : scale {s_sym:.5f}, zero point   0, levels used {len(np.unique(q_sym)):3d}, max error {err_sym.max():.5f}")
scale 0.01373, zero point 73
x      : [-1.   0.   0.3  2.5]
q      : [  0  73  95 255]
x_hat  : [-1.002  0.     0.302  2.498]

ReLU activations in [0.00, 3.98]
affine uint8   : scale 0.01562, zero point   0, levels used 219, max error 0.00781
symmetric int8 : scale 0.03135, zero point   0, levels used 115, max error 0.01568

The vector example reproduces the figure: s=3.5/255≈0.01373s = 3.5/255 \approx 0.01373, zero point 73, and 0.0 comes back exactly while the other values move by at most half a step (−1.0-1.0 becomes −1.002-1.002, 0.3 becomes 0.302). On 10,000 ReLU activations, the affine code (here z=0z = 0, because the range starts at 0) uses steps of 0.01562 and a maximum error of 0.00781; the symmetric int8 code needs steps twice as wide, 0.03135, because half of its 255 values are reserved for negative numbers that never occur, and its maximum error doubles to 0.01568.

Why integers are faster

A dense layer computes yj=∑ixiwijy_j = \sum_i x_i w_{ij}. With xi≈sx(qix−zx)x_i \approx s_x (q^x_i - z_x) and symmetric weights wij≈swqijww_{ij} \approx s_w q^w_{ij}:

yj≈sxsw∑i(qix−zx) qijwy_j \approx s_x s_w \sum_i (q^x_i - z_x)\, q^w_{ij}

The sum is computed entirely in integers (8-bit products, a 32-bit accumulator), and one floating-point multiplication by sxsws_x s_w at the end converts it back, or requantizes it straight to the next layer's 8-bit input. Integer multiply-adds are cheaper in silicon than float ones, SIMD units process four times as many 8-bit values per instruction as 32-bit ones, and, often the bigger win, a quarter of the bytes travel from memory. The bias is usually stored as int32 with scale sxsws_x s_w.

Per-tensor or per-channel

One scale for a whole weight matrix (per-tensor) is simple, but a single column with large weights stretches ss for all the others. Per-channel quantization gives each output channel jj (each column of WW, each convolution filter) its own sjs_j; the formula above still works because sjs_j factors out of the sum over ii. The next example trains a small network on the 8 x 8 digit images (1,257 training, 540 test images) and quantizes its weights both ways, from 8 bits down to 2. The activations stay in float here (this "fake quantization" isolates the weight error).

python · try it yourself
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier

X, y = load_digits(return_X_y=True)
X = X / 16.0
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, stratify=y, random_state=0)
mlp = MLPClassifier(hidden_layer_sizes=(64,), max_iter=600, random_state=0).fit(X_tr, y_tr)

def forward(Ws, bs, X):
    h = np.maximum(X @ Ws[0] + bs[0], 0.0)                      # hidden layer, ReLU
    return (h @ Ws[1] + bs[1]).argmax(1)                         # class with the largest logit

def quant_sym(W, bits, per_channel):
    """Symmetric fake quantization: round to integers in [-(2^(b-1)-1), 2^(b-1)-1], then scale back."""
    qmax = 2 ** (bits - 1) - 1
    amax = np.abs(W).max(axis=0, keepdims=True) if per_channel else np.abs(W).max()
    scale = amax / qmax                                          # one scale per output column, or one in total
    return np.clip(np.round(W / scale), -qmax, qmax) * scale

Ws, bs = mlp.coefs_, mlp.intercepts_
ref = forward(Ws, bs, X_te)
print(f"float32 model: test accuracy {(ref == y_te).mean():.3f} (n = {len(y_te)})")
print("bits | per-tensor acc  agree | per-channel acc  agree")
for bits in (8, 6, 4, 3, 2):
    row = []
    for pc in (False, True):
        pred = forward([quant_sym(W, bits, pc) for W in Ws], bs, X_te)
        row.append(f"{(pred == y_te).mean():.3f}  {(pred == ref).mean():.3f}")
    print(f"{bits:4d} |      {row[0]}  |       {row[1]}")

# Rescale hidden unit 0: incoming weights and bias x 100, outgoing weights / 100.
# ReLU(100 a) = 100 ReLU(a), so the network computes exactly the same function.
W0, b0, W1 = Ws[0].copy(), bs[0].copy(), Ws[1].copy()
W0[:, 0] *= 100; b0[0] *= 100; W1[0, :] /= 100
same = forward([W0, W1], [b0, bs[1]], X_te)
print(f"\nrescaled unit 0: float predictions identical: {bool((same == ref).all())}")
print(f"largest |weight| in layer 1: before {np.abs(Ws[0]).max():.2f}, after {np.abs(W0).max():.2f}")
for pc in (False, True):
    pred = forward([quant_sym(W0, 8, pc), quant_sym(W1, 8, pc)], [b0, bs[1]], X_te)
    print(f"int8 {'per-channel' if pc else 'per-tensor '}: accuracy {(pred == y_te).mean():.3f}, agreement {(pred == ref).mean():.3f}")
float32 model: test accuracy 0.978 (n = 540)
bits | per-tensor acc  agree | per-channel acc  agree
   8 |      0.978  1.000  |       0.978  1.000
   6 |      0.976  0.998  |       0.980  0.998
   4 |      0.972  0.991  |       0.978  0.996
   3 |      0.950  0.963  |       0.959  0.974
   2 |      0.180  0.172  |       0.467  0.474

rescaled unit 0: float predictions identical: True
largest |weight| in layer 1: before 1.44, after 22.26
int8 per-tensor : accuracy 0.969, agreement 0.991
int8 per-channel: accuracy 0.978, agreement 1.000

At 8 bits the quantized network makes exactly the same predictions as the float one (agreement 1.000). Down to 4 bits it stays within a few test images of the float accuracy (0.972 per-tensor, 0.978 per-channel against 0.978), and only at 2 bits does it collapse (0.180 per-tensor; per-channel holds 0.467). Agreement with the float model is the better measure of the damage: it compares the same 540 predictions, while accuracy differences of one or two images (0.980 at 6 bits per-channel, above the float model) are noise.

The last part shows why per-channel matters. Multiplying a hidden unit's incoming weights and bias by 100 and dividing its outgoing weights by 100 leaves the network's function unchanged, because ReLU⁡(100a)=100ReLU⁡(a)\operatorname{ReLU}(100a) = 100 \operatorname{ReLU}(a). But the largest weight in the first layer grows from 1.44 to 22.26, the per-tensor scale grows with it, and even 8 bits now cost 5 of 540 predictions (agreement 0.991). Per-channel quantization is unaffected (agreement 1.000). Real networks have such uneven channels without anyone rescaling them, which is why per-channel weight quantization is the usual choice for convolution and linear layers in static recipes (ONNX Runtime's quantizers take a per_channel=True option).

Dynamic, static and quantization-aware

Weights are known before deployment; activations depend on the input. The three standard recipes differ in how they get the activations' ranges:

  • Dynamic quantization. Weights are quantized once, offline. Each activation tensor's range is measured at run time, for every batch, and quantized on the fly. No calibration data is needed, it is accurate, and it suits models dominated by matrix products with large weights (linear layers, LSTMs, transformers on CPU). The run-time min/max costs a little.
  • Static quantization. Activation ranges are fixed in advance by calibration: run a few hundred representative inputs through the model, record each activation's range (min-max, a percentile, or a range that minimises the error, for example by entropy), and store ss and zz in the model. Every layer then runs in integers end to end, the fastest option and the one integer-only accelerators require. It is only as good as the calibration data.
  • Quantization-aware training (QAT). When post-training quantization loses too much accuracy (small models, 4 bits), insert fake quantization (quantize then dequantize) into the forward pass during training or fine-tuning, so the network learns weights that survive rounding. Rounding has zero gradient almost everywhere, so the backward pass uses the straight-through estimator: the gradient passes through the rounding as if it were the identity.

Calibration in practice: the same network, its hidden activations quantized with a range from 200 training images. In the second and third rows one of those images was never divided by 16, a typical pipeline bug that puts pixel values of 0 to 16 into a model trained on 0 to 1.

python · try it yourself
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier

X, y = load_digits(return_X_y=True)
X = X / 16.0
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, stratify=y, random_state=0)
mlp = MLPClassifier(hidden_layer_sizes=(64,), max_iter=600, random_state=0).fit(X_tr, y_tr)
(W0, W1), (b0, b1) = mlp.coefs_, mlp.intercepts_

def fake_quant(x, lo, hi, bits):
    """Affine (unsigned) quantize-dequantize with a fixed range [lo, hi]."""
    qmax = 2 ** bits - 1
    scale = (hi - lo) / qmax
    zp = np.round(-lo / scale)
    return (np.clip(np.round(x / scale) + zp, 0, qmax) - zp) * scale

def predict(X, h_range=None, bits=8):
    h = np.maximum(X @ W0 + b0, 0.0)
    if h_range is not None:                                  # static quantization of the hidden activations
        h = fake_quant(h, 0.0, h_range, bits)
    return (h @ W1 + b1).argmax(1)

ref = predict(X_te)
calib = X_tr[:200]                                          # 200 training images for calibration
broken = calib.copy()
broken[0] = X_tr[0] * 16                                    # one image that skipped the /16 scaling (a pipeline bug)
print(f"float: test accuracy {(ref == y_te).mean():.3f} (n = {len(y_te)})")
for bits in (8, 4):
    for name, data, how in [("min-max, clean set ", calib, "max"), ("min-max, 1 bad image", broken, "max"),
                            ("99th pct, 1 bad image", broken, "pct")]:
        h = np.maximum(data @ W0 + b0, 0.0)
        hi = h.max() if how == "max" else np.percentile(h, 99)
        pred = predict(X_te, hi, bits)
        print(f"{bits} bits, {name:21s}: range [0, {hi:6.2f}] -> accuracy {(pred == y_te).mean():.3f}, "
              f"agreement {(pred == ref).mean():.3f}")
float: test accuracy 0.978 (n = 540)
8 bits, min-max, clean set   : range [0,   4.45] -> accuracy 0.978, agreement 1.000
8 bits, min-max, 1 bad image : range [0,  57.49] -> accuracy 0.980, agreement 0.994
8 bits, 99th pct, 1 bad image: range [0,   3.43] -> accuracy 0.978, agreement 1.000
4 bits, min-max, clean set   : range [0,   4.45] -> accuracy 0.976, agreement 0.998
4 bits, min-max, 1 bad image : range [0,  57.49] -> accuracy 0.926, agreement 0.926
4 bits, 99th pct, 1 bad image: range [0,   3.43] -> accuracy 0.978, agreement 0.993

With a clean calibration set the range is [0,4.45][0, 4.45] and both 8 and 4 bits keep the float predictions (agreement 1.000 and 0.998). One bad image stretches the min-max range to 57.49: at 8 bits the steps are still small enough (agreement 0.994), but at 4 bits only 16 levels cover [0,57.49][0, 57.49] and accuracy drops to 0.926. A percentile range ignores the extreme values: the 99th percentile, 3.43, clips the largest 1 % of activations and gives 0.978 accuracy at 4 bits even with the bad image. Calibration data deserves the same validation as training data.

ONNX Runtime: quantize_dynamic

In production, nobody rounds weights by hand. A model exported to ONNX can be quantized with one call to onnxruntime.quantization. This is a recorded example (ONNX 1.23.2, ONNX Runtime 1.31.1, skl2onnx 1.20.0, run in the course's Docker image): a larger digits network with two hidden layers (256 and 128 units, about 50,000 weights), converted to ONNX, then dynamically quantized to int8 weights.

python · try it yourself
import logging, os
from collections import Counter
import numpy as np
import onnx
import onnxruntime as ort
from onnxruntime.quantization import quantize_dynamic, QuantType
from skl2onnx import to_onnx
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier

X, y = load_digits(return_X_y=True)
X = (X / 16.0).astype(np.float32)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, stratify=y, random_state=0)
mlp = MLPClassifier(hidden_layer_sizes=(256, 128), max_iter=600, random_state=0).fit(X_tr, y_tr)

onx = to_onnx(mlp, X_tr[:1], options={"zipmap": False})
with open("digits.onnx", "wb") as f:
    f.write(onx.SerializeToString())
logging.getLogger().setLevel(logging.ERROR)              # hides the "consider pre-processing" hint
quantize_dynamic("digits.onnx", "digits.int8.onnx", weight_type=QuantType.QInt8)

results = {}
for path in ("digits.onnx", "digits.int8.onnx"):
    sess = ort.InferenceSession(path, providers=["CPUExecutionProvider"])
    label, proba = sess.run(None, {sess.get_inputs()[0].name: X_te})
    results[path] = (label, proba)
    ops = Counter(n.op_type for n in onnx.load(path).graph.node)
    print(f"{path:17s} {os.path.getsize(path) / 1024:6.1f} KiB, test accuracy {(label == y_te).mean():.3f}")
    print("   ops:", dict(sorted(ops.items())))
(l32, p32), (l8, p8) = results.values()
print(f"sklearn accuracy {mlp.score(X_te, y_te):.3f}; int8 vs float32: label agreement {(l8 == l32).mean():.3f}, "
      f"max |probability difference| {np.abs(p8 - p32).max():.4f}")
digits.onnx        199.8 KiB, test accuracy 0.980
   ops: {'Add': 3, 'ArgMax': 1, 'ArrayFeatureExtractor': 1, 'Cast': 2, 'Identity': 1, 'MatMul': 3, 'Relu': 2, 'Reshape': 1, 'Softmax': 1}
digits.int8.onnx    54.6 KiB, test accuracy 0.980
   ops: {'Add': 3, 'ArgMax': 1, 'ArrayFeatureExtractor': 1, 'Cast': 5, 'DynamicQuantizeLinear': 3, 'Identity': 1, 'MatMulInteger': 3, 'Mul': 6, 'Relu': 2, 'Reshape': 1, 'Softmax': 1}
sklearn accuracy 0.980; int8 vs float32: label agreement 1.000, max |probability difference| 0.0284

The file shrinks from 199.8 KiB to 54.6 KiB, 3.7 times smaller rather than 4 because the graph structure, biases and scales are not compressed. The test accuracy is 0.980 for the sklearn model, the float ONNX model and the quantized one, the two ONNX models agree on all 540 test labels, and the largest change in any predicted probability is 0.0284. The operator lists show what happened: each MatMul became a DynamicQuantizeLinear (measure the activation's range and quantize it), a MatMulInteger (8-bit inputs, 32-bit output) and Mul nodes that apply the scales. For static quantization, ONNX Runtime has quantize_static with a CalibrationDataReader that feeds calibration batches; PyTorch's current path for its own models is torchao (the older torch.ao.quantization API is deprecated).

Pitfalls

  • Judging by accuracy alone. Measure agreement with the float model and the change in probabilities on a fixed test set; a model whose predictions change on 3 % of inputs may keep the same accuracy and still break a downstream threshold or calibration.
  • Unrepresentative calibration data. Static ranges from a few images, from the wrong preprocessing or from a different population clip or waste the range. Use a few hundred real inputs and prefer percentile ranges when outliers exist.
  • Expecting a speed-up everywhere. Quantized kernels help only where the runtime and hardware have them. Small models, tiny batches, or a GPU path without int8 kernels may run no faster, or slower because of the extra quantize and dequantize steps. Measure latency on the target device (latency and batching).
  • Quantizing everything. The first and last layers, softmax and normalisation layers are often more sensitive; tools let you exclude nodes. Half precision (float16/bfloat16, see mixed precision) is a safer first step on GPUs.

Practice

  1. Compute ss and zz for uint8 and the range [−0.5,1.5][-0.5, 1.5]. Which integer represents 1.0?
Answer

s=2/255≈0.00784s = 2/255 \approx 0.00784, z=round⁡(0+0.5/0.00784)=round⁡(63.75)=64z = \operatorname{round}(0 + 0.5/0.00784) = \operatorname{round}(63.75) = 64. Then 1.01.0 maps to round⁡(1.0/0.00784)+64=128+64=192\operatorname{round}(1.0/0.00784) + 64 = 128 + 64 = 192, which dequantizes to 0.00784⋅(192−64)≈1.0040.00784 \cdot (192 - 64) \approx 1.004.

  1. In the first example, change the ReLU activations to rng.normal(0.0, 1.0, 10_000) (no ReLU). Which code wins now, and why?
Answer

The data are now symmetric around 0, so the affine code puts its zero point near 128 and both codes cover roughly the same range with about the same step; the advantage of the affine code disappears. Asymmetric codes pay off only when the distribution is one-sided or off-centre.

  1. A model has 120 million float32 weights. Estimate the file size after dynamic int8 quantization, and say what else must be stored.
Answer

About 120 MB instead of 480 MB for the weights. Add the scales (one float per tensor or per channel, negligible), the zero points, the biases (often kept in float or int32) and the graph; in the example above these made the file 3.7 times smaller instead of 4.

Test yourself

Why is the zero point chosen so that the real number 0 maps exactly to an integer?

  1. So that zeros such as padding and ReLU outputs stay exactly zero after quantization
  2. Because it halves the scale
  3. Because integers cannot be negative
  4. It makes the rounding error zero for every value

A hidden unit's incoming weights are multiplied by 100 and its outgoing weights divided by 100. The float network is unchanged. What happens to int8 per-tensor and per-channel weight quantization?

  1. Per-tensor gets worse, per-channel is unaffected
  2. Both are unaffected
  3. Both get worse by the same amount
  4. Per-channel gets worse, per-tensor is unaffected

What distinguishes static from dynamic quantization?

  1. Static fixes the activation ranges in advance from calibration data; dynamic measures them for every batch at run time
  2. Static quantizes only the weights, dynamic only the activations
  3. Static needs retraining, dynamic does not
  4. Static uses 4 bits, dynamic 8 bits

One calibration image was not normalised and the min-max range grew from 4.45 to 57.49. Which statement matches the measurement at 4 bits?

  1. Accuracy fell to 0.926; a 99th-percentile range restored 0.978
  2. Nothing changed, 4 bits is always enough
  3. Only the 8-bit model was affected
  4. The percentile range made it worse

How does quantization-aware training get gradients through the rounding step?

  1. With the straight-through estimator: the backward pass treats rounding as the identity
  2. Rounding is differentiable
  3. It does not need gradients
  4. It trains only the scales