Sub topic 16
FP16 and INT8: speed gains and accuracy checks
This chapter assumes you can export a model to ONNX, run it in an ONNX Runtime InferenceSession, and enable the TensorRT execution provider. It also assumes you have a parity check and a benchmark function like the ones from earlier chapters. Here you will learn what reduced precision changes, how to turn it on, and how to confirm that the faster model is still good enough.
Why reduce precision
A float32 weight takes 4 bytes. A float16 weight takes 2 bytes, and an int8 weight takes 1. Smaller numbers help in three ways:
- Less memory traffic. Many vision layers wait on memory, not arithmetic, so moving half the bytes can nearly halve their time.
- Faster math units. NVIDIA GPUs from the Volta generation onward have Tensor Cores, which run FP16 matrix math much faster than FP32. Turing and later add fast INT8 paths.
- Smaller engines and less GPU memory, which leaves room for larger batches.
The cost is accuracy. Fewer bits mean a smaller range and coarser steps between representable values. The job is to take the speed while checking that the error stays below what your application can tolerate.
| Format | Bytes per value | Approximate range | Typical accuracy impact on vision models | Needs calibration |
|---|---|---|---|---|
| FP32 | 4 | about 3.4e38 | Reference | No |
| FP16 | 2 | about 65504 | Usually very small | No |
| INT8 | 1 | -128 to 127 (with a scale) | Small to moderate, model dependent | Yes |
FP16 in the TensorRT execution provider
FP16 is the easy first step. You keep the same ONNX file and ask TensorRT to choose FP16 kernels where they are faster. TensorRT can still pick FP32 for a layer if that layer is faster or unsupported in FP16.
import onnxruntime as ort
providers = [
(
"TensorrtExecutionProvider",
{
"trt_fp16_enable": True,
"trt_engine_cache_enable": True,
"trt_engine_cache_path": "./trt_cache_fp16",
},
),
"CUDAExecutionProvider",
"CPUExecutionProvider",
]
sess_fp16 = ort.InferenceSession("resnet50.onnx", providers=providers)
print(sess_fp16.get_providers())Use a separate cache directory for each precision setting. Engines built with FP16 and engines built with FP32 are different files, and mixing them in one folder makes it hard to tell which one you are running.
Remember that the first session creation builds the engine, which can take minutes. Run a warmup before you time anything, as in the benchmarking chapter.
Where FP16 goes wrong
FP16 has a maximum value near 65504 and loses precision for very small values. Problems show up in a few places:
- Large intermediate values overflow to infinity, which then spreads to NaN in later layers. This is more common in models with unnormalized attention scores or large sums.
- Very small values underflow to zero, so tiny contributions disappear.
- Models with custom postprocessing inside the graph, such as box decoding with exponentials, are more sensitive than a plain classifier.
Plain convolutional classifiers such as ResNet-50 usually survive FP16 with differences in the third or fourth decimal place. Detection and segmentation heads deserve a closer look.
INT8 and why it needs calibration
INT8 stores each value as an integer from -128 to 127 and a floating-point scale that maps it back:
real_value ≈ int8_value × scaleA tensor with values between -6.0 and 6.0 might use a scale of about 6.0 / 127. Choosing that range is the hard part. If the range is too wide, small values lose resolution. If it is too narrow, large values get clipped.
There are two ways to get the ranges:
- Post-training quantization with calibration. You run a few hundred representative images through the model. The tool records activation ranges at each layer and picks scales from them. No retraining is needed.
- Quantization-aware training. The model trains with simulated quantization, so the weights adapt to it. It usually gives better accuracy but needs a training pipeline. The exported ONNX file contains
QuantizeLinearandDequantizeLinearnodes (Q/DQ), and TensorRT reads those scales directly.
Calibration data matters more than its size. It must look like production input: the same cameras, lighting, resolution, and preprocessing. Calibrating on 500 clean studio photos and deploying on dark, blurry camera frames is a common cause of unexpected accuracy loss.
Enabling INT8 in the TensorRT execution provider
The execution provider accepts INT8 in two forms. For a model that already contains Q/DQ nodes, you only need to enable INT8. For a model without them, you supply a calibration table, which holds the per-tensor ranges produced by a calibration run.
import onnxruntime as ort
providers = [
(
"TensorrtExecutionProvider",
{
"trt_int8_enable": True,
"trt_int8_calibration_table_name": "calibration.flatbuffers",
"trt_fp16_enable": True,
"trt_engine_cache_enable": True,
"trt_engine_cache_path": "./trt_cache_int8",
},
),
"CUDAExecutionProvider",
"CPUExecutionProvider",
]
sess_int8 = ort.InferenceSession("resnet50.onnx", providers=providers)
print(sess_int8.get_providers())Enabling trt_fp16_enable together with INT8 lets TensorRT fall back to FP16 for layers where INT8 is slower or too lossy, instead of falling all the way back to FP32. The calibration table must come from a calibration run on your data. Generating it is a separate step done with ONNX Runtime's quantization tooling or with TensorRT's calibrator. A table made for one model does not work for another, and it should be regenerated after any change to the model or preprocessing.
The same idea with trtexec
You can try both precisions without writing Python. The --fp16 and --int8 flags enable them, and trtexec also reports latency, which makes it a fast way to see whether a precision helps on your GPU.
trtexec --onnx=resnet50.onnx --saveEngine=resnet50_fp16.plan --fp16 \
--minShapes=input:1x3x224x224 \
--optShapes=input:8x3x224x224 \
--maxShapes=input:32x3x224x224Adding --int8 to a model without Q/DQ nodes and without a calibration file makes trtexec use placeholder scales. That is fine for measuring speed, because the timing does not depend on the scale values. It is not fine for measuring accuracy, since the outputs will be wrong.
Accuracy checks that match the precision
The strict check from the parity chapter, assert_allclose with rtol=1e-3, is right for FP32 and often too tight for FP16. For reduced precision, replace it with a set of checks that reflect what the application needs:
- Output closeness with a looser tolerance, to catch gross errors such as NaN or a scrambled layout.
- Top-1 and top-5 agreement with the FP32 model on a held-out set.
- The real task metric (accuracy, mAP, IoU) on a validation set, compared with the FP32 score.
Agreement on one random tensor proves very little. Use real images and enough of them to see the effect.
import numpy as np
def compare_precisions(sess_ref, sess_test, batches, input_name="input"):
top1_matches = 0
top5_matches = 0
total = 0
max_abs_diff = 0.0
for x in batches:
ref = sess_ref.run(None, {input_name: x})[0]
out = sess_test.run(None, {input_name: x})[0]
if not np.isfinite(out).all():
raise ValueError("Non-finite values in reduced-precision output")
max_abs_diff = max(max_abs_diff, float(np.abs(ref - out).max()))
ref_top1 = ref.argmax(axis=1)
out_top1 = out.argmax(axis=1)
top1_matches += int((ref_top1 == out_top1).sum())
out_top5 = np.argsort(out, axis=1)[:, -5:]
top5_matches += int(
sum(r in row for r, row in zip(ref_top1, out_top5))
)
total += len(x)
return {
"max_abs_diff": max_abs_diff,
"top1_agreement": top1_matches / total,
"ref_top1_in_test_top5": top5_matches / total,
}Call it with a list of preprocessed batches from real images:
batches = [np.random.rand(8, 3, 224, 224).astype(np.float32) for _ in range(5)]
print(compare_precisions(sess, sess_fp16, batches))The random batches above only make the example run. Replace them with your validation images before drawing any conclusion. Agreement of 99% or more on top-1 is common for FP16. For INT8 you decide the threshold from the task metric, for example "no more than 0.5 points of accuracy lost."
Measure the speed gain honestly
Use the benchmark function from the earlier chapter on every session: FP32 CUDA, FP32 TensorRT, FP16, and INT8. Compare p50 and p95 at the batch size you will deploy, not only at batch 1.
Expect these patterns:
- Gains depend on the GPU. Older GPUs without Tensor Cores see little benefit from FP16, and without fast INT8 hardware, INT8 can even be slower.
- Small models and small batches may be limited by launch overhead and host-device copies, so lower precision helps less. I/O binding can matter more than precision there.
- INT8 gains over FP16 are smaller than FP16 gains over FP32 on many models, because layers that stay in higher precision and the reformat steps between precisions eat into the savings.
The diagram shows the decision flow.
Common errors
- No speedup from FP16. Check
get_providers()to confirm TensorRT is active and not silently replaced by CUDA or CPU. Check that the GPU has Tensor Cores. - NaN or all-zero outputs. Likely an FP16 overflow. Compare intermediate outputs by exposing them as extra graph outputs, then keep the offending layers in FP32.
- INT8 accuracy drops sharply. Calibration data does not match production, or one sensitive layer, often the first or last, should stay in higher precision.
- Timings look worse after enabling INT8. The first run included engine building. Warm up and use the cache.
- Results change after a driver or TensorRT upgrade. Tactic selection differs between versions, so rerun the accuracy checks after any upgrade.
Exercise
Your FP16 TensorRT session runs 1.8 times faster than FP32 and shows 99.6% top-1 agreement on 2,000 real validation images. Your INT8 session runs only 1.1 times faster than FP16 and loses 1.2 points of validation accuracy. Which would you ship, and what would you try before giving up on INT8?
Show answer
Ship FP16: it gives most of the speed gain with almost no accuracy loss. INT8 adds little speed over FP16 and costs 1.2 points of accuracy. Before dropping it, check that the calibration data matches production input and preprocessing, enable FP16 fallback alongside INT8 so sensitive layers stay in higher precision, try keeping the first or last layer in higher precision, and consider quantization-aware training if INT8 is still needed.
Exercise
Why is comparing one random input tensor between the FP32 and INT8 sessions not a valid accuracy check?
Show answer
Random noise does not resemble real images, so it does not exercise the activation ranges that calibration measured or the decision boundaries between classes. The outputs can look close or far apart without telling you anything about task accuracy. You need real, representative images and a task metric or top-k agreement computed over many of them.