Networks are commonly trained with FP32 weights and activations [1]. Integer-only hardware can run inference more efficiently than floating point [2]. Quantization stores weights and activations as small integers and does the heavy arithmetic in integer units. This article covers the mechanics, a worked example, and the decisions to make before a quantized model ships.
What quantization buys
Moving from 32-bit to 8-bit values cuts tensor storage by a factor of 4, and the computational cost of a matrix multiplication drops quadratically, by a factor of 16 [1]. Multiply-accumulate (MAC) operations and data movement account for most of the energy spent in inference, so both savings show up in power as well as speed [1]. On some targets quantization is not optional. Some Arm Cortex-M cores have no floating-point unit, and the Google Edge TPU supports only 8-bit arithmetic [3].
The affine mapping
The scheme adopted in TensorFlow Lite maps an integer q to a real value r with two constants [2]. The Qualcomm white paper calls it uniform affine quantization [1]:
r = S * (q - Z)
S is the scale, a positive real number. Z is the zero-point, an integer of the same type as q, chosen so that real zero is exactly representable. That matters because zero padding and ReLU outputs must not pick up quantization error [2,1].
Quantizing a real value to a b-bit unsigned grid is a divide, round, offset and clamp [1]:
q = clamp(round(r / S) + Z, 0, 2^b - 1)
Values inside the range carry a rounding error of at most S/2. Values outside it are clipped. Widening the range reduces clipping but increases S, and with it the rounding error, so range setting is a trade-off between the two [1].
Symmetric quantization fixes Z = 0. Asymmetric quantization keeps the offset and fits skewed distributions such as post-ReLU activations more tightly [3]. The offset has a cost. When both weights and activations are asymmetric, the product contains a term that depends on the input data and must be computed for every inference. For that reason a common choice is symmetric weights and asymmetric activations [1]. Signed 8-bit weights can use the full range [-128, 127] or a “restricted” range [-127, 127] [3]. Jacob et al. keep weights out of -128 because it enables an optimization in their ARM kernels [2].
Worked example
We compute every number below ourselves; none is taken from a paper.
Activations, asymmetric uint8. Suppose calibration shows activations in [-1.0, 3.0].
- Scale:
S = (3.0 - (-1.0)) / 255 = 4/255 = 0.015686. One step is about 0.0157. - Zero-point:
Z = round(1.0 / S) = round(63.75) = 64. - Because
Zwas rounded, the representable range isS * (0 - 64) = -1.0039toS * (255 - 64) = 2.9961. - Quantize
r = 0.5:0.5 / S = 31.875, round to 32, addZto getq = 96. Dequantize:S * (96 - 64) = 0.50196. Error 0.00196, well inside theS/2 = 0.0078bound. - Quantize
r = 3.5:223.125, round to 223, add 64 to get 287, clamp to 255. Dequantize: 2.9961. The clipping error is 0.504, about 64 times the worst rounding error.
One outlier beyond the calibrated range costs far more than rounding.
Weights, per-tensor versus per-channel. Take a layer with two output channels. Channel A has weights up to 1.30 in magnitude; channel B has weights no larger than 0.013, a 100x spread.
- Per-tensor, symmetric, restricted int8:
S = 1.30 / 127 = 0.010236.- A weight of 0.84 in channel A becomes
round(82.06) = 82, which dequantizes to 0.83937. Relative error 0.07%. - A weight of 0.006 in channel B becomes
round(0.586) = 1, which dequantizes to 0.010236. Relative error 71%. - A weight of 0.004 in channel B becomes
round(0.391) = 0. The weight vanishes.
- A weight of 0.84 in channel A becomes
- Per-channel for B:
S_B = 0.013 / 127 = 0.00010236.- 0.006 becomes
round(58.6) = 59, which dequantizes to 0.0060394. Relative error 0.66%. - 0.004 becomes 39, which dequantizes to 0.0039921. Relative error 0.20%.
- 0.006 becomes
Requantizing the accumulator. For a matrix product, the integer core computes an int32 sum of products. The output is rescaled by M = S_w * S_x / S_y [2]. Let S_w = 0.010236 (weights above), S_x = 0.015686 (activations above) and an output with a ReLU6 range of [0, 6] in uint8, so S_y = 6/255 = 0.023529 and Z_y = 0.
M = 0.010236 * 0.015686 / 0.023529 = 0.0068241.- Jacob et al. write
M = 2^-n * M0withM0in [0.5, 1) [2]. Heren = 7andM0 = 0.87349. - As an int32 fixed-point value,
M0isround(2^31 * 0.87349) = 1,875,807,239. - For an accumulator value of 12,000:
12,000 * 1,875,807,239 = 22,509,686,868,000. Shift right by31 + 7 = 38bits with rounding: 81.89, which rounds toq_y = 82. - Check: the real value is
12,000 * S_w * S_x = 1.9268. The quantized output dequantizes to82 * S_y = 1.9294.
No floating-point operation runs on the device. The bias is stored as int32 with scale S_w * S_x and zero-point 0, so it adds directly into the accumulator [2]. The accumulator itself must stay at 32 bits to avoid overflow [1].
Per-tensor or per-channel
Jacob et al. name two common failure modes of simple post-training quantization. One is weight ranges that differ by more than 100x between output channels. The other is outlier weights that reduce precision for everything else [2]. Nagel et al. show the size of the effect. With FP32 activations and 4-bit weights, MobileNetV2 (71.72% FP32 ImageNet accuracy) scores 0.59% with per-tensor min-max ranges and 18.40% with per-channel ranges [p202, Table 1]. At INT8, the same network drops to 0.12% with naive per-tensor quantization. Cross-layer equalization brings it back to 69.91%, and absorbing high biases raises it to 70.92%. Per-channel quantization alone gives 70.65% [p202, Table 3].
Per-channel weight scales need no extra rescaling in the accelerator. Per-channel activation scales do, because the scale can no longer be factored out of the sum [1]. Not every commercial accelerator supports per-channel weights, so check the target first [1]. The same check applies to an FPGA datapath; see neural network inference on FPGAs.
Post-training quantization first
Post-training quantization (PTQ) needs no retraining and at most a small unlabeled calibration set. Nagel et al. report that 500 to 1000 images are usually enough [1]. Their recommended pipeline is:
- Apply cross-layer equalization to the FP32 model.
- Insert quantizers: symmetric for weights, asymmetric for activations, per-channel weights if the hardware allows.
- Set weight ranges by minimizing mean squared error rather than using min-max.
- If calibration data exists, run AdaRound to choose rounding directions. Otherwise use analytical bias correction.
- Set activation ranges with MSE on the calibration set [1].
With that pipeline, W8A8 stays close to floating point. The ImageNet classifiers lose at most 0.73 points (MobileNetV2, 71.72 to 70.99 per-tensor). The largest drop in the table is EfficientDet-D1 on COCO, 40.08 to 38.29 mAP [p202, Table 6]. At W4A8 the picture splits. ResNets and InceptionV3 stay within 1%. Per-tensor quantization costs MobileNetV2 2.5 points and EfficientNet-lite 4.2 points [1]. EfficientDet-D1 collapses from 40.08 to 0.31 mAP with per-tensor W4A8 [p202, Table 6].
Activation ranges can be computed per input at run time (dynamic) or fixed from calibration (static). Dynamic ranges are usually more accurate but cost run-time work, so static ranges are the common choice [3].
When PTQ falls short, the white paper suggests a debugging order. First, run the quantized graph at 32 bits and confirm it matches FP32. Then quantize only weights or only activations to see which one causes the drop. Finally, quantize one layer at a time [1].
Quantization-aware training when PTQ is not enough
Quantization-aware training (QAT) inserts simulated quantizers into the training graph. It passes gradients through the rounding step with the straight-through estimator, which treats the derivative of rounding as 1 [1]. It needs labeled data and a training budget [1]. The survey by Gholami et al. notes that recovering accuracy at low bit widths can take several hundred epochs [3]. In return, QAT brings EfficientDet-D1 at per-tensor W4A8 back to 35.34 mAP [p202, Table 10]. Jacob et al. used QAT for their integer-only MobileNets. For MobileNet SSD on COCO they report up to a 50% cut in run time on Snapdragon 835 cores, with mAP falling from 22.1 to 21.7 at full width [2]. They also note that the speedup depends on how well the CPU handles floating point. On the Snapdragon 821, which handles floating point better, the latency gain was smaller [2].
Large language models
Transformers [4] add two problems: activation outliers, and weight memory that dominates everything else.
Dettmers et al. found hidden-state features with magnitudes up to 20 times larger than in other dimensions. At around 6.7B parameters these outliers appear in every transformer layer, yet at that scale they sit in only six feature dimensions. Setting those dimensions to zero degrades validation perplexity by 600–1000% [5]. LLM.int8() quantizes each inner product with its own scaling constants. Feature dimensions containing values above a threshold of 6.0 are routed to a 16-bit matrix multiply. More than 99.9% of values are still multiplied in 8 bits [5]. The method halves inference memory for models up to 175B parameters without measured degradation. The quantization overhead slows inference for models below 6.7B parameters compared with FP16 [5].
GPTQ quantizes weights only. It works layer by layer, using approximate second-order information to adjust the remaining weights as each weight is rounded [6]. Its calibration set is 128 random 2048-token segments of C4. OPT-175B and BLOOM-176B take about four GPU-hours on one A100 [6]. On WikiText2, 4-bit OPT-175B reaches a perplexity of 8.37 against 8.34 for FP16. Plain round-to-nearest gives 10.54. At 3 bits, GPTQ gives 8.68, while round-to-nearest collapses to about 7.3e3 [p205, Table 3]. At 3 bits the model needs about 63 GB and fits one 80 GB A100. FP16 needs five such GPUs and LLM.int8() needs three [6].
The speed gain comes from memory bandwidth. Token-by-token generation is dominated by matrix-vector products. A kernel that reads 3-bit weights and dequantizes them on the fly moves far fewer bytes [6]. At batch size 1, per-token latency falls from 230 ms on five A100s to 71 ms on one (3.24x). On A6000 GPUs it falls from 589 ms on eight to 130 ms on two (4.53x) [p205, Table 6].
For sizing, the arithmetic is simple (our own numbers). A 7B-parameter model needs 14 GB of weights in FP16, 7 GB in INT8 and 3.5 GB in INT4. One FP16 scale per group of 128 weights adds 16/128 = 0.125 bits per weight, which brings INT4 to about 3.61 GB. The key-value cache and activations come on top of that. For OPT-175B at 2048 tokens, GPTQ reports about 9 GB of key-value cache [6].
Decisions to make before quantizing
- Target capabilities. Bit widths, symmetric or asymmetric support, per-channel support, and which operators have integer kernels.
- Metric and budget. Accuracy loss is only half the picture. Jacob et al. argue for measuring the latency-accuracy trade-off on the device [2].
- Data access. PTQ needs a small calibration set: 500 to 1000 unlabeled images in the white paper [1], 128 text segments for GPTQ [6]. QAT needs the training pipeline and labels.
- Order of attempts. W8A8 PTQ first. Then per-channel weights and better range setting. Then mixed precision or QAT.
- Verification. Compare the quantized model’s outputs with FP32 on held-out data from the deployment distribution, not only the calibration set.
Where Takumetra can help
We can audit a model and its target hardware for quantization readiness. We can also run PTQ or QAT experiments against an agreed accuracy and latency budget. See our AI/ML engineering services.