Sub topic 3
Quantization: float32 to int8
Prerequisites and working model
This chapter assumes that you know tensors, image preprocessing, and basic TensorFlow or PyTorch usage. You should also understand that a model’s weights and activations are usually stored as float32 values during training and inference.
Quantization maps floating-point values to lower-precision integers. The goal is to reduce model size, memory traffic, and arithmetic cost while keeping accuracy within an acceptable limit. An int8 value uses one byte, while a float32 value uses four bytes.
A quantized value is represented by a scale and a zero point:
real_value = scale × (integer_value - zero_point)
For a symmetric mapping, the zero point is usually zero. For an asymmetric mapping, the zero point lets the integer range represent a floating-point range that is not centered on zero.
Post-training quantization
Post-training quantization (PTQ) converts an already-trained model. It is usually the first method to try because it requires no retraining.
Weight-only quantization changes the weights but keeps activations in floating point. This often gives a smaller model with modest speed improvements.
Dynamic-range quantization estimates activation ranges at runtime. Full integer quantization converts both weights and activations to integers. It usually gives the best benefit on integer hardware, but it needs a representative dataset.
A representative dataset is a small sample of real inputs that shows the converter the activation ranges used during inference. It should match production images in size, lighting, subjects, and preprocessing.
import numpy as np
import tensorflow as tf
model = tf.keras.applications.MobileNetV2(
weights="imagenet", input_shape=(224, 224, 3)
)
def representative_dataset():
# Replace this with real images preprocessed exactly as during training.
for _ in range(100):
image = np.random.uniform(
-1.0, 1.0, size=(1, 224, 224, 3)
).astype(np.float32)
yield [image]
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.int8
converter.inference_output_type = tf.int8
quantized_model = converter.convert()
with open("mobilenet_v2_int8.tflite", "wb") as file:
file.write(quantized_model)The random data in this example only demonstrates the converter. It is not suitable for measuring accuracy. Poor calibration data can produce badly scaled activations and large accuracy loss.
When PTQ is not enough
Compare the original and quantized models on a held-out validation set. For classification, measure top-1 or top-5 accuracy. For detection, measure precision, recall, and mean average precision. Also check important subgroups, such as dark images or small objects.
Quantization-aware training (QAT) simulates integer rounding during training. The model learns weights that are less sensitive to quantization error. Use QAT when full integer PTQ causes unacceptable accuracy loss, especially with small models, sensitive layers, or difficult detection tasks.
| Method | Training required | Typical benefit | Main risk |
|---|---|---|---|
| Float32 | No conversion | Highest numerical precision | Largest model and cost |
| Weight-only PTQ | No | Smaller model | Limited acceleration |
| Full integer PTQ | No, but calibration data | Small and fast | Accuracy loss from poor ranges |
| QAT | Yes | Better int8 accuracy | More training complexity |
Exercise
A full-integer model loses five percentage points of validation accuracy after PTQ. What should you check first, and what is the next optimization to try?
Show answer
First verify that representative images use the same preprocessing and cover production data. If calibration is correct and the loss remains, try quantization-aware training and compare layer-level errors.