Sub topic 3
Quantization: float32 to int8
This chapter assumes you know what a convolutional network is, can read basic PyTorch or TensorFlow code, and understand float32 and int8 as tensor data types. By the end you should be able to apply post-training quantization (PTQ), explain what the converter is doing, and decide when quantization-aware training (QAT) is needed.
Why quantize
A float32 weight takes 4 bytes. An int8 weight takes 1 byte. Quantizing a vision model therefore shrinks it by roughly 4x. That matters on a phone for three reasons:
- Memory and download size. A 14 MB model becomes about 3.5 MB.
- Memory bandwidth. Mobile inference is often limited by how fast data moves between memory and the processor, not by arithmetic. Moving a quarter of the bytes helps directly.
- Hardware support. Many NPUs (neural processing units) and DSPs (digital signal processors) run only integer math, or run it far faster and with less energy than float math.
The cost is a loss of precision. The job is to make that loss small enough that task accuracy barely changes.
The affine mapping
Quantization maps real values to integers with a scale and a zero point:
q = clamp(round(x / scale) + zero_point, qmin, qmax)
x ≈ scale * (q - zero_point)scaleis a positive float. It is the real-valued step between two neighbouring integers.zero_pointis the integer that represents real 0.0 exactly. Exact zero matters because zero padding in convolutions and ReLU outputs must stay exact.qmin, qmaxare the integer limits: -128 to 127 for int8, 0 to 255 for uint8.
Suppose a tensor has values in [-1.0, 3.0] and you use uint8. The scale is (3.0 − (−1.0)) / 255 ≈ 0.0157. The zero point is round(0 − (−1.0) / 0.0157) = 64. A real value of 1.0 becomes round(1.0 / 0.0157) + 64 = 128. Converting back gives 0.0157 × (128 − 64) ≈ 1.004. The difference of 0.004 is the rounding error.
The step size is the maximum rounding error scale. A wide range gives a large scale and coarser values. This is why outliers hurt: one extreme value stretches the range for every other value in the tensor.
Symmetric and asymmetric schemes
| Scheme | Zero point | Typical use | Trade-off |
|---|---|---|---|
| Symmetric | Fixed at 0, range is [−max, +max] | Weights | Simpler and faster kernels, but wastes range if the data is one-sided |
| Asymmetric | Any integer | Activations | Fits one-sided data such as ReLU outputs, but needs extra zero-point arithmetic |
TensorFlow Lite's int8 specification uses symmetric int8 for weights and asymmetric int8 for activations. Other runtimes make different default choices, so check the one you target.
Per-tensor and per-channel
Per-tensor quantization uses one scale for a whole weight tensor. Per-channel quantization uses one scale for each output channel of a convolution.
Per-channel is usually better for weights. Different filters in a layer can have very different magnitudes. Depthwise convolutions, which MobileNet-style models use heavily, are the worst case, and per-tensor quantization of them can cause large accuracy drops. Current converters use per-channel weights for convolutions by default. Activations stay per-tensor, because per-channel activation scales would make the kernels much more complex.
Post-training quantization
PTQ takes a trained float model and quantizes it without retraining. There are three common modes.
| Mode | Needs data | Weights | Activations | Notes |
|---|---|---|---|---|
| Dynamic range | No | int8 | Float, quantized on the fly at runtime | Easy, but limited speedup and unsuitable for integer-only hardware |
| Full integer | Yes (calibration set) | int8 | int8 | Best for NPUs and DSPs; needs calibration |
| Float16 | No | float16 | float16 | Halves size; useful for GPU delegates |
For vision on phones, full integer quantization is usually the target.
Calibration
Weights are known, so their ranges are easy to compute. Activations depend on the input, so the converter must observe them. Calibration runs a small set of representative inputs through the float model and records the minimum and maximum (or a histogram) of each activation tensor. Those ranges produce each tensor's scale and zero point.
Calibration quality sets PTQ quality. Follow these rules:
- Use roughly 100 to 500 real images from the deployment distribution.
- Apply exactly the same preprocessing as at inference time (resize, normalization, channel order).
- Cover the variety you expect, such as lighting, scale, and classes.
- Do not use random noise except as a smoke test. Noise yields wrong ranges and a model that converts but performs badly.
Full integer conversion in TensorFlow Lite
This example converts a Keras MobileNetV2 into a fully integer-quantized model.
import numpy as np
import tensorflow as tf
model = tf.keras.applications.MobileNetV2(
weights="imagenet", input_shape=(224, 224, 3)
)
def representative_dataset():
# Replace the random data with about 100 real, preprocessed images.
for _ in range(100):
yield [np.random.rand(1, 224, 224, 3).astype(np.float32)]
converter = tf.lite.TFLiteConverter.from_keras_model(model)
converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.representative_dataset = representative_dataset
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
converter.inference_input_type = tf.uint8
converter.inference_output_type = tf.uint8
tflite_model = converter.convert()
with open("mobilenet_v2_int8.tflite", "wb") as f:
f.write(tflite_model)What each setting does:
optimizations = [DEFAULT]turns quantization on.representative_datasetis the calibration generator. Each yielded item is a list with one array per model input.supported_ops = [TFLITE_BUILTINS_INT8]demands integer kernels. If an operator has no int8 version, conversion fails instead of silently leaving a float operator in the graph. This is what you want when the target is an integer-only accelerator.inference_input_typeandinference_output_typemake the model's inputs and outputs integers, so your app feeds uint8 pixels directly. Without them the model keeps float32 inputs and outputs, with quantize and dequantize operators at the edges.
Running the quantized model
The interpreter reports the input type, so you should read it from the model and not hard-code it.
import numpy as np
import tensorflow as tf
interpreter = tf.lite.Interpreter(model_path="mobilenet_v2_int8.tflite")
interpreter.allocate_tensors()
inp = interpreter.get_input_details()[0]
out = interpreter.get_output_details()[0]
image = np.zeros(inp["shape"], dtype=inp["dtype"]) # stand-in for a real image
interpreter.set_tensor(inp["index"], image)
interpreter.invoke()
scores = interpreter.get_tensor(out["index"])
print("top class:", int(scores.argmax()))If you need real-valued outputs, such as probabilities for a threshold, read the output's quantization entry, which holds (scale, zero_point). Then compute scale * (scores.astype(np.float32) - zero_point). For a plain argmax you can skip that step, because the mapping is monotonic.
When feeding a real image to a uint8 input model, you must still reproduce the model's expected preprocessing. If the original model normalized to [−1, 1], the quantized model's input scale and zero point encode that mapping. The input quantization values tell you how to turn a normalized float into the integer.
Quantization in the ONNX path
The ONNX export from PyTorch produces a float model:
import torch
import torchvision
model = torchvision.models.mobilenet_v3_small(weights="DEFAULT").eval()
dummy = torch.randn(1, 3, 224, 224)
torch.onnx.export(
model,
dummy,
"mobilenet_v3_small.onnx",
input_names=["input"],
output_names=["logits"],
opset_version=17,
)Quantization then happens as a separate step, for example with ONNX Runtime's quantization tools, which also use a calibration reader and support static (calibrated) and dynamic modes. ONNX represents quantization either with QDQ nodes (QuantizeLinear and DequantizeLinear pairs around float operators) or with operator-oriented quantized ops. QDQ is the more portable format and is preferred by many accelerator back ends. The principles above (scale, zero point, calibration, per-channel weights) carry over unchanged.
What happens inside an integer layer
Understanding this explains several gotchas. An int8 convolution multiplies int8 inputs and int8 weights and accumulates into int32, because summing many 8-bit products overflows 8 bits. After accumulation, a requantization step multiplies by a combined factor (input scale × weight scale / output scale), usually implemented as a fixed-point multiply and shift, and then adds the output zero point and clamps to the int8 range.
Consequences:
- Accumulators are wide, so errors rarely come from the multiply-add itself. They come from rounding at tensor boundaries and from clipping when the calibrated range was too narrow.
- Operations that mix tensors with different scales, such as residual additions and concatenations, need extra rescaling. They are common accuracy trouble spots.
- Fused patterns (convolution + batch norm + ReLU) are folded together before quantization, so the quantized graph has fewer boundaries than the float graph.
Quantization-aware training
QAT inserts fake-quantization operations into the training graph. Those operations round values to the int8 grid in the forward pass, while gradients pass through unchanged (the straight-through estimator). The network trains while experiencing the rounding noise and learns weights that tolerate it. After training you convert, and the learned ranges become the scales.
| Question | PTQ | QAT |
|---|---|---|
| Effort | Minutes, no training pipeline | Needs the training code, data, and extra epochs |
| Typical accuracy loss | Small for classification, often larger for detection, segmentation, and tiny networks | Closest to float accuracy |
| When to choose | First attempt, always | When PTQ misses your accuracy budget |
A practical rule: try PTQ first. If the accuracy drop on your validation set is within your budget, stop. If not, try fixes in order of cost:
- Improve the calibration set (more images, correct preprocessing, better coverage).
- Switch weights to per-channel if they are not already.
- Keep a few sensitive layers in float (mixed precision), usually the first layer, the last layer, or the layers with the worst error.
- Move to QAT, starting from the pretrained float model and fine-tuning briefly at a low learning rate.
Fine-tuning for a few epochs is usually enough. You rarely need to train from scratch.
Common failure modes
- Converts but accuracy collapses. Usual causes are calibration with random data or mismatched preprocessing, or activation outliers that stretch ranges.
- Large drop in depthwise-heavy models. Check that weights are per-channel. Some architectures have activation ranges that vary hugely across channels, and these respond better to QAT.
- Conversion error about unsupported operations. With
TFLITE_BUILTINS_INT8, any operator lacking an int8 kernel stops the conversion. Replace the operator, or allow float fallback and accept that the accelerator will not run that part. - Speedup is small or negative. Integer kernels only help if the runtime has optimized int8 code for your CPU or a delegate that takes the graph. Extra quantize and dequantize operators at many boundaries can erase the gain. Measure on the device; later chapters cover benchmarking.
- Output looks wrong after reading it raw. The output is an integer. Dequantize it with its own scale and zero point before applying thresholds or softmax.
Exercise
A tensor of activations after ReLU has values in [0.0, 6.0]. You quantize it to uint8 (0 to 255) with an asymmetric scheme. What are the scale and zero point, and why is zero exactly representable? Then explain why one outlier value of 60.0 in a calibration image would hurt accuracy.
Show answer
Scale = (6.0 − 0.0) / 255 ≈ 0.0235. Zero point = round(0 − 0.0 / 0.0235) = 0, so real 0.0 maps to integer 0 and is exact. With an outlier of 60.0 in the calibration range, scale becomes 60.0 / 255 ≈ 0.235, ten times larger. Typical activations between 0 and 6 then use only about 26 of the 256 integer levels, so their rounding error grows tenfold. Fixes include using more representative calibration data, clipping percentiles during calibration, or QAT.
Exercise
You converted a model with inference_input_type = tf.uint8 and the TFLITE_BUILTINS_INT8 op set. Conversion succeeds, and the model runs, but top-1 accuracy drops from 71% to 20%. List the first two things you check and the evidence that would confirm each.
Show answer
First, check the calibration data. If representative_dataset yields random noise or images preprocessed differently from inference, activation ranges are wrong; confirm by recalibrating with about 100 real, correctly preprocessed images and seeing accuracy recover. Second, check the input pipeline at inference time. The uint8 input must be produced using the input tensor's scale and zero point so that it matches the normalization the float model expected; confirm by comparing the float model's and quantized model's outputs for the same image, and by printing the input quantization values. If both are correct, check per-channel weights and then consider mixed precision or QAT.