A night camera frame can break an INT8 model that scored fine all day. Learn to quantise, compile with TensorRT, and prove layer by layer that the binary is still your model.
Shrink a trained network to 8-bit numbers, build it into a fast engine for a Jetson, and show with measurements that it still sees what the original saw.
First guess how fast INT8 will be, then press Lock in my guess. Step the precision from PyTorch to INT8 and watch the measured latency land. Then calibrate on daytime frames only, and look at the night frames. Below, we build every piece from zero.
You need a rough idea of what a neural network layer is (numbers in, numbers out) and a little Python. We build quantisation, TensorRT and parity from zero.
Physical AI Systems, edge track, step 2. Built from primary sources: the NVIDIA TensorRT documentation, the Ultralytics Jetson benchmarks, the Google quantisation whitepaper (arXiv 1806.08342) and the FP8 paper (arXiv 2209.05433). The latency and COCO numbers are measured by Ultralytics. The night-frame numbers are a toy model we built, and the page says so each time.
Latency (ms per image, without pre and post processing) and COCO mAP50-95 are Ultralytics’ YOLO26n results on a Jetson AGX Orin 64 GB at 640 pixels, Ultralytics 8.4.32. The twelve layer errors and the night mAP are our toy model: Laplace-shaped activations, night gain 4.5 times larger in layer L7, 8-bit rounding computed for real. Toy numbers are illustrative.
Chapter 0
See how an INT8 model can pass every daytime test and still fail on the first dark road
A delivery robot drives a campus at noon. Its camera model finds people, bikes and bins. The team shrinks the model to run on a small board, tests it on the usual picture set, and sees almost no loss. They ship it.
At 9 p.m. the robot drives past a bike rack and does not see the bikes. Nothing crashed. No error appeared. The model simply stopped seeing. The test that said “fine” had never shown it a dark road.
This lesson is about that gap. It has three steps: quantise (store the numbers in fewer bits), compile (turn the model into a fast program for one chip), and prove parity (show the fast program still behaves like the original). The first step is where the night problem is born.
A trained network is full of 32-bit decimal numbers. Quantisation replaces each one with an 8-bit whole number from −127 to 127. That is 255 possible values instead of billions. The model gets four times smaller, and the chip can do the maths with simpler circuits.
Think of a ruler. A ruler with 255 marks must cover the whole range of values you expect. If you stretch it over 0 to 3, each mark is 0.024 apart. If a value arrives that is 16, the ruler has no mark for it. You can only say “off the end”.
The ruler length is decided once, before the model ships. The team shows the model a small set of pictures, records how large each layer’s numbers get, and fixes the ruler to that. This step is calibration, and the quantising it prepares is post-training quantisation (PTQ): no new training, just a fit to the pictures you showed.
Now the night case, with numbers from our toy model. Layer L7 of the network saw daytime pictures during calibration. Its largest activation was 3.08, so the scale is s = 3.08 / 127 = 0.0243.
day: x = 1.00 → 1.00 / 0.0243 = 41.2 → q = 41 → back to 0.995 (error 0.5%)
night: x = 5.00 → 5.00 / 0.0243 = 206 → clip to 127 → back to 3.08 (error 38%)
At night the camera raises its gain. Dark pictures are noisy, and the layer that reacts to noise and edges produces values up to 16.4, about five times the daytime range. In our toy model 25% of L7’s night values lie beyond 3.08. All of them are cut off at 3.08. The layer’s error on night frames is 51%, against 1.0% on day frames.
Cutting off values is called clipping. It is the failure mode of this chapter. Nothing in the weights changed. The ruler was fitted to the data you showed it, and the world showed something else.
Bars show toy mAP for daytime frames, night frames, and the average over your test set. Slide the share of night frames, then switch what the ranges were calibrated on.
Toy model, illustrative: FP32 mAP 0.48 on day frames and 0.40 on night frames are our own made-up values. INT8 scores come from rounding 1,200 synthetic activations per layer and per kind of frame. The average is (1 − f) × day + f × night.
Drag the share to 5%. The test-set average barely moves, because night frames are rare in the test set. It hides the collapse. The average is a sum over the pictures you happened to collect. It says nothing about the pictures you did not.
mAP (mean average precision) is one score for how well a detector finds objects, averaged over all test pictures and all object classes. It is the number every team reports. It answers “how good on this test set?” It cannot answer “on which pictures does it break?”
The fix has two parts. First, slice the metric: report mAP separately for day, dusk, night, rain and any other condition you care about. Second, look inside: compare the quantised model to the original layer by layer, so the first layer that goes wrong lights up. Chapter 5 builds both.
You will see the same trade at work all the way down: the speed you gain (Chapter 2), the engine that holds it (Chapter 3), the custom parts that can break it (Chapter 4), and the checks and benchmarks that keep you honest (Chapters 5 and 6).
You can read this beside Quantization I and Quantization II for the theory, and Export, Partition, Fallback for how the model reaches this step.
Chapter 1
Choose the range each tensor may use, and see why one wide channel can ruin its narrow neighbours
You have a trained detector and 500 calibration pictures. For each layer you must now pick one number, the range r. Pick it too wide and every mark on the ruler sits far from the next, so ordinary values round badly. Pick it too narrow and big values fall off the end.
Two errors fight each other. Rounding error is the small miss when a value lands between two marks. It grows with the gap s = r / 127. Clipping error is the big miss when a value is beyond r and is cut to r. A wider range cuts clipping and raises rounding. A narrower range does the reverse.
The simplest choice is min/max: take the largest absolute value the calibration pictures produced. Nothing clips on those pictures. But one rare spike stretches the ruler for everything else.
The next choice is a percentile: ignore the top 0.1% of values and set r at the 99.9th percentile. A few values clip, and the rest get finer marks. A third choice is entropy calibration. It tries many ranges and keeps the one whose quantised histogram is closest, by KL divergence, to the original histogram. TensorRT ships calibrators of both the entropy and the min/max kind (IInt8EntropyCalibrator2 and IInt8MinMaxCalibrator).
Try it on one layer. The histogram shows how many activations fall at each value, on a log scale so rare big values stay visible. Switch on the spike to see one big value stretch the ruler.
Drag the range r, or press a preset. Red zones are clipped. Switch to 4 bits to see the marks of the grid.
Toy data, illustrative: 1,200 synthetic Laplace-shaped activations of one layer. Error is the relative root-mean-square of quantise then dequantise, computed for real. “Typical values” are those inside the 99th percentile.
With the spike on, min/max gives a range of 30. The marks are 0.24 apart, and the typical values, which sit near 0.7, round badly. A percentile range fixes that but clips the spike. Whether clipping the spike is safe depends on what it means. A noise spike is safe to clip. A real signal, such as a bright headlamp, is not. The range alone cannot tell you. Task accuracy can.
A convolution layer has many output channels, each one a separate filter with its own weights. After normalisation layers are folded in, some channels have weights 50 times larger than others. Per-tensor quantisation gives all channels one scale, set by the widest channel. The narrow channels then use only a few of the 255 marks.
Per-channel quantisation gives each channel its own scale. It costs one extra number per channel and almost nothing in speed. Google’s quantisation whitepaper (Krishnamoorthi, 2018) recommends per-channel scales for weights and one per-layer scale for activations, and reports 8-bit post-training quantisation within 2% of floating point across many CNNs. TensorRT follows the same split: for a convolution, the per-channel axis must be the output-channel axis.
Six channels have weights of very different size. Bars show each channel’s quantisation error. Drag the spread between the widest and narrowest channel.
Toy weights, illustrative: 48 Laplace-shaped weights per channel, channel sizes spaced evenly on a log scale from 0.05 up to 0.05 times the spread. Errors are computed for real at INT8.
Work one case. At a spread of 40, the widest channel reaches 7.67, so the shared scale is 7.67 / 127 = 0.060. The narrowest channel reaches only 0.155. That is 0.155 / 0.060 = 2.6 marks, so its weights collapse to a handful of levels and the error is 34%. With its own scale, 0.155 / 127 = 0.0012, and the error is 0.8%. The widest channel is fine either way. A mean error across channels would blur this, so the device reports the worst channel.
Some layers stay in higher precision. Typical choices are the first layer, which sees raw pixels, and the last layers, which make the final box and class scores. You find them by measurement: quantise one layer at a time, run the checks of Chapter 5, and keep the layers with large errors in FP16. TensorRT lets you set a precision per layer, and it will mix them in one engine.
Modern exports write the ruler into the graph. The ONNX file holds QuantizeLinear and DequantizeLinear nodes (Q/DQ) around each tensor, with the scale stored in them. TensorRT calls this explicit quantisation, and treats a network that contains Q/DQ layers that way. Its older calibrator interfaces are marked deprecated since TensorRT 10.1, superseded by explicit quantization. The scales are then visible in the file and easy to diff.
pythonimport numpy as np def calibrate(acts, how="minmax", pct=99.9): """acts: (frames, features) float32 activations from the calibration set.""" a = np.abs(acts).ravel() return a.max() if how == "minmax" else np.percentile(a, pct) def fake_quant(x, r, bits=8): q = 2**(bits-1) - 1 # 127 for INT8 s = r / q # scale: gap between marks return np.clip(np.round(x / s), -q, q) * s def per_channel_scales(W): # W: (out_ch, in_ch, kh, kw) return np.abs(W).reshape(W.shape[0], -1).max(axis=1) / 127 # shape (out_ch,)
The failure to watch for is a per-tensor scale on a layer whose channels differ widely. Its symptom is a layer whose output matches in the big channels and is flat in the small ones. You measure it as per-channel error in Chapter 5. The fix is per-channel weight scales, or leaving that layer in FP16.
Chapter 2
Read the measured ladder, and see why INT8 does not double the speed of FP16
You have a camera model that runs at 11.58 ms per image in PyTorch on a Jetson AGX Orin. The robot needs more headroom. Which rung of the precision ladder buys it, and how much does each rung cost in accuracy? Before you read the next device, guess how much faster FP16 is than FP32.
A floating-point number stores a sign, an exponent (how big) and a mantissa (the digits). FP32 uses 32 bits. FP16 uses 16: a 5-bit exponent and a 10-bit mantissa. It keeps the huge range of FP32, so it needs no calibration. It halves the bytes the chip must move, and the Tensor Cores (the matrix units of the GPU) run it fast.
That is why FP16 is the free first step. You build the engine with FP16 allowed, check the outputs, and usually nothing moves. INT8 asks more of you: a calibration set, a range per tensor, and the checks of Chapter 5.
Ultralytics publishes YOLO26n numbers on Jetson boards, at 640 by 640 pixels and without pre and post processing. The tool is Ultralytics 8.4.32 on the AGX Orin 64 GB and 8.4.33 on the Orin NX 16 GB. Read the device, then compare each rung with the one before it.
Pick a board. Each bar is milliseconds per image. Switch on the ghost to see what a perfect 2× INT8 would look like.
Measured by Ultralytics (docs.ultralytics.com/guides/nvidia-jetson), YOLO26n, 640 px, COCO mAP50-95 and size on disk as listed there. Inference time does not include pre and post processing. The ghost bar is our arithmetic, not a measurement.
Take the AGX Orin. TensorRT FP32 is 4.18 ms against PyTorch at 11.58 ms: 2.8 times faster, from fused layers and a tuned engine alone, with no precision change. FP16 brings 2.62 ms, another 1.6 times. INT8 gives 2.30 ms, only 1.14 times faster than FP16. The Orin NX shows the same shape: 4.13 ms for FP16 and 3.49 ms for INT8, a 1.18 times gain.
Many GPUs run INT8 math faster than FP16 math, often about twice as fast at peak. So where did the doubling go? A layer’s time has two parts: math (multiply and add) and everything else (moving data from memory, starting each kernel, small layers that cannot fill the chip). Only the math part speeds up.
Call the math share f. If INT8 math is twice as fast, the INT8 time is T16 × (1 − f + f / 2). Set that equal to the measured ratio 2.30 / 2.62 = 0.878. Then 1 − f / 2 = 0.878, so f = 0.24. This is an inference, not a measurement: it says that only about a quarter of the FP16 time was math. The rest was bandwidth and launch overhead, which a smaller number format barely touches (INT8 does cut bytes moved, so part of the gain comes from there too).
The lesson for planning: do not promise a 2 times gain from INT8 before you profile. A small network such as YOLO26n on a big GPU is mostly overhead already. A large network, where math dominates, gains more.
Look at the cost side as well. INT8 mAP is 0.4640 against 0.4789 for FP16 on the AGX Orin, a drop of 0.0149 or 3.1%. On the Orin NX it is 0.4489, a drop of 0.0300 or 6.3%. The same model, two boards, two different losses. The calibration and the tactics differ per build. This is the reason Chapter 5 exists.
Lower still, TensorRT lists INT8, INT4 (weights only), FP8 in the E4M3 layout and FP4 in the E2M1 layout. E4M3 means 4 exponent bits and 3 mantissa bits. The paper that proposed FP8 for deep learning (Micikevicius et al., 2022) defines E4M3 and E5M2, and notes that E4M3 gets extra range by dropping infinities and using a single bit pattern for “not a number”.
You can derive the values yourself. Take the 4-bit E2M1 format: one sign bit, two exponent bits with bias 1, one mantissa bit. With exponent 0 the number is a subnormal (m × 0.5). Otherwise it is (1 + m / 2) × 2e−1. The non-negative values are 0, 0.5, 1, 1.5, 2, 3, 4 and 6. That is all of them. For E4M3 the same rule with bias 7 gives a largest value of 1.75 × 28 = 448.
With so few values, a scale is essential. The microscaling (MX) formats from the Open Compute Project attach one 8-bit scale to each small block of values (as summarised by secondary sources, 32 values per block). NVIDIA lists the Jetson AGX Thor, with a Blackwell GPU, at 2070 FP4 TFLOPS with sparsity. We found no published YOLO26n timing on that board, so the measured ladder above stops at INT8.
Each row is the set of numbers one format can store, after its largest code is stretched to 8. Drag a value and see where it rounds.
The grids are derived from the bit layouts: INT8 has 127 steps, E4M3 follows the rule above (largest value 448), E2M1 has the eight values listed. Real FP4 uses a scale per block; here one scale covers the whole line.
Near 2.4, INT8 has marks 0.06 apart. E4M3 has marks 0.29 apart (a step of 16 on its own scale, stretched by 8 / 448). E2M1 has marks 0.67 apart (a step of 0.5 on its own scale, stretched by 8 / 6). FP formats are dense near zero and sparse near the top. That suits bell-shaped values, and it is why block scales matter for FP4.
pythondef fp_values(ebits, mbits, bias, nan_top=False): """All non-negative values of a tiny float format, from its bit layout.""" out = [] for e in range(2**ebits): for m in range(2**mbits): if nan_top and e == 2**ebits - 1 and m == 2**mbits - 1: continue # E4M3 keeps one not-a-number pattern v = m/2**mbits * 2.0**(1-bias) if e == 0 else (1 + m/2**mbits) * 2.0**(e-bias) out.append(v) return out print(fp_values(2, 1, 1)) # [0, 0.5, 1, 1.5, 2, 3, 4, 6] print(max(fp_values(4, 3, 7, True))) # 448.0
Chapter 3
Watch the builder time every way to run each layer, and learn which machines may load its result
You have an ONNX file: a list of layers and their weights. A GPU cannot run a list. It needs a program: which kernel to launch for each layer, in what order, with which memory layout. TensorRT is NVIDIA’s tool that writes this program. It runs in two phases. The builder makes the program once, slowly. The runtime loads and runs it many times, fast.
The builder first rewrites the graph. It fuses a convolution, its bias and its activation into one kernel, so the data makes one trip to memory instead of three. This alone explains why TensorRT FP32 beat PyTorch by 2.8 times in Chapter 2.
Then, for each layer, there are several ways to do the same job. Each way is a tactic: a different kernel, tile size or memory layout. A tactic that is best for a big 3×3 convolution may be poor for a small one. The builder cannot guess, so it times the candidates on the real GPU and keeps the fastest. This is why building is slow, and why the result belongs to that GPU.
The output is the engine plan: a file (often named .plan or .engine) with the chosen kernels and the weights, already in their final precision. At run time, TensorRT deserialises the plan and launches the kernels.
Press Build. Each row is a layer, each bar is one candidate tactic being timed. The fastest per layer gets a green frame. Then switch on the timing cache and build again.
Toy layers and toy tactic times, illustrative. The real builder times many more candidates, and it only saves a timing when the layer shape, precision and GPU match an earlier entry.
Work the first row of the toy build. Four tactics for the first 3×3 convolution take 1.9, 1.2, 0.8 and 1.4 ms. The builder keeps the 0.8 ms one. The fourth layer is the same kind of layer, but at a different size, and its fastest tactic is the 0.9 ms one. Same operation, different winner. Summed over six layers, the winners give 3.6 ms, while always taking the first candidate would give 6.3 ms.
Precision joins the search. When you allow FP16 and INT8, the builder may pick an INT8 kernel for one layer and an FP16 kernel for its neighbour. Where two layers disagree, it inserts a reformat step that converts the data between them. Each reformat costs time, which is why Chapter 4 warns against a stray FP32 layer in the middle of an INT8 network.
The timing cache stores the timings the builder has already measured. When you rebuild after a small model change, layers it has seen before skip the timing step. The cache is itself tied to the GPU and the software, so reuse it only on the same hardware and TensorRT version.
pythonimport tensorrt as trt log = trt.Logger(trt.Logger.WARNING) builder = trt.Builder(log) net = builder.create_network() trt.OnnxParser(net, log).parse_from_file("yolo26n_qdq.onnx") # Q/DQ nodes carry the INT8 scales cfg = builder.create_builder_config() cfg.set_flag(trt.BuilderFlag.FP16) # allow FP16 where it is faster cfg.set_flag(trt.BuilderFlag.INT8) # allow INT8 kernels cache = cfg.create_timing_cache(b"") # empty cache; load saved bytes to reuse cfg.set_timing_cache(cache, False) plan = builder.build_serialized_network(net, cfg) # slow: times every tactic open("yolo26n.plan", "wb").write(plan) # bytes, valid for this GPU + this TensorRT
The same build is one line with trtexec, the command-line tool in the TensorRT package. It builds, can save the plan with --saveEngine, and then times inference and prints metrics such as GPU Compute Time, the time the kernels take for one inference. Run trtexec --help on your install for the flags of your version.
Log what the builder chose. A good habit is to save the build log and the per-layer precision table next to the plan, so that when a layer later fails parity you can see whether it was built in INT8, FP16 or FP32 and which kernel it got.
By default, NVIDIA’s Engine Compatibility page says, a plan works only with the TensorRT version that built it, and only on the type of device that built it. TensorRT stores the full library version in the plan and fails to deserialise if the runtime differs. It compares the GPU’s compute capability (its major and minor architecture number) and fails on a mismatch. Other properties, such as memory bus width or L2 cache size, produce a warning. Deserialisation can also fail if the running GPU has less memory than the building GPU.
There are two relaxations. A version-compatible build (supported from TensorRT 8.6) can run on later runtimes, at a possible speed cost. A hardware-compatible build runs across GPUs of the same or a later architecture, also at a cost, and NVIDIA states it is not supported on JetPack. For a Jetson fleet, the safe rule is simple: build on the device type that will run it.
The plan was built on one GPU with one TensorRT version. Pick where you load it.
Rules paraphrased from NVIDIA’s TensorRT Engine Compatibility page. The machines drawn are schematic.
Now the failure and its fix. A team builds the plan on a workstation and copies it to the robot. On the robot, deserialisation fails, or a service quietly rebuilds the plan at boot while the robot is waiting to start. The symptom is a crash on first start or a slow first boot. The measurement is the compute capability and TensorRT version printed in both places. The fix is a plan per device type, named by capability, TensorRT version and model hash, or a first-boot build that saves its plan and timing cache to disk.
Chapter 4
Fill the gap when the graph needs an operation TensorRT does not have, without breaking the INT8 chain
A research team adds a camera-to-bird’s-eye-view step to its network. The step reads a feature map at fractional positions and blends the four nearest cells. PyTorch has this as one call. You export to ONNX, and the TensorRT parser stops with a message: no importer for this operation. The graph is complete except for one box.
TensorRT’s own documentation puts it plainly: it can be extended by implementing custom layers, often called plugins, for the cases in which the supported layers do not meet a model’s needs. A plugin is a box you fill with your own GPU code. TensorRT treats it as one more layer.
TensorRT has to plan around the box without looking inside it. So the plugin tells TensorRT five things: its name and version; the shape and type of each output for a given input; which combinations of data type and memory layout it supports; how much scratch memory it needs; and, finally, how to run it on a CUDA stream. In the current C++ interface (IPluginV3) these are separate methods, and a creator object is registered so that the parser can find the plugin by name.
The third item matters most for this lesson. If the plugin declares only FP32, TensorRT must hand it FP32 data. If the layers around it run in INT8, TensorRT has to insert a conversion before the plugin and another after it. Each conversion reads and writes the whole tensor.
Seven layers run in INT8. The orange-outlined box is your plugin. Choose which precisions it supports and watch the reformat steps appear.
Toy times, illustrative: each ordinary layer 0.30 ms, the plugin kernel 0.50 ms in FP32, 0.30 ms in FP16, 0.20 ms in INT8, and each reformat 0.15 ms. Real costs depend on the tensor size and the memory speed.
Count the chain. Six ordinary layers at 0.30 ms make 1.80 ms. With an INT8 plugin the total is 1.80 + 0.20 = 2.00 ms. With an FP32-only plugin the total is 1.80 + 0.50 + 2 × 0.15 = 2.60 ms. The plugin kernel itself is slower, and the two conversions add 0.30 ms. That is a 30% rise for one custom box. This pattern, a high-precision island inside a low-precision network, is the requantisation churn that Export, Partition, Fallback describes from the partition side.
The heart of a plugin is a CUDA kernel: a function that thousands of GPU threads run at once, each on a different element. Here is a small INT8 one, a scale-and-clamp. It reads INT8 input, multiplies by a float, clamps, and writes INT8 output, so the plugin can sit inside an INT8 chain without a reformat. Writing fast kernels is a craft of its own; the kernels lesson and the GPU kernel landscape cover it.
cuda// One thread per element. in/out are INT8 tensors of n values. __global__ void scale_clamp_i8(const int8_t* in, int8_t* out, int n, float mult) { int i = blockIdx.x * blockDim.x + threadIdx.x; // this thread's element if (i < n) { float v = in[i] * mult; // dequantise-and-scale in one multiply v = fminf(fmaxf(v, -127.f), 127.f); // clamp to the INT8 range out[i] = (int8_t)__float2int_rn(v); // round to nearest } } // Launched from the plugin's enqueue() on TensorRT's stream: // scale_clamp_i8<<<(n + 255) / 256, 256, 0, stream>>>(in, out, n, mult);
Two practical details. In C++ you register the plugin creator with the plugin registry (for the standard plugins, NVIDIA says all must be registered by calling initLibNvInferPlugins in your application). In Python, defining plugins with a decorator-based approach is recommended from TensorRT 10.6, and a plugin defined that way and compiled ahead of time (an AOT plugin) can be embedded in an engine that does not depend on Python at run time.
Put real shapes on it. Suppose the plugin receives an INT8 feature map of shape [1, 64, 80, 80] (batch, channels, height, width). That is 64 × 80 × 80 = 409,600 elements, one byte each. The launch line above covers it with (409,600 + 255) / 256 = 1,600 blocks of 256 threads. An FP32-only plugin forces a reformat that reads 409,600 bytes and writes 1,638,400 bytes (four bytes per element), and the reformat after it moves the same amount back. That is about 4.1 MB of extra traffic per frame, for work that does no maths.
Test the plugin before you trust it. Feed the same random INT8 tensor to your kernel and to the PyTorch operation it replaces, and compare the outputs. For an INT8 output the honest tolerance is one integer step, since two correct implementations can round a half differently. For an FP16 or FP32 plugin use a relative error, and set it from the noise floor of Chapter 5.
The symptom is a network that is slower after the plugin than a profile of the plugin kernel predicts. The measurement is a per-layer profile of the built engine: look for reformat layers on both sides of the plugin. trtexec can print a per-layer profile (see its help for the option). The fix is to make the plugin accept the neighbours’ precision, so no conversion is needed, and to test the plugin against the PyTorch operation it replaces. Chapter 5 shows how to compare them with a tolerance.
Chapter 5
Compare the compiled binary to the original layer by layer and slice by slice, with a tolerance you can defend
Back to the robot and the bike rack. After the night failure, the team needs to answer one question before every release: is the compiled binary still the model we trained? One mAP number cannot answer it. A defensible answer has three parts, and each part catches a different failure.
Parity means the compiled engine gives results close enough to the original model that you would accept swapping one for the other. Close enough is a number you choose, per layer and per slice, before you look at the result.
Run the same input through the original model and through the engine. Compare the output of every layer. Two simple measures are enough. The relative error is the size of the difference divided by the size of the original: e = |yq − y| / |y|. The cosine similarity is how well the two vectors point the same way; for small errors it is about 1 − e² / 2, so an error of 10% gives a cosine of 0.995. Cosine hides small errors, so prefer the relative error when you set tolerances.
Layer-level checking has a purpose that the final score lacks: it points at the cause. If L7 is the first layer over its tolerance, you look at L7’s range, its scale and its inputs. In practice you compare each layer given the original model’s own input, so that one bad layer does not paint every later layer red. NVIDIA’s Polygraphy tool can run a model through TensorRT and ONNX Runtime and compare every intermediate output. One caution: marking an inner tensor as an output stops TensorRT from fusing it away, so the debug engine differs from the shipping engine. Compare the shipping engine at its outputs too.
Start with FP16. Its per-layer error should be tiny, about 0.05% in our toy model, because FP16 rounds each number to roughly 3 decimal digits. If an FP16 engine already shows large layer errors, the cause is not quantisation: look for a wrong layer, a bad import or a plugin bug before you touch the INT8 ranges.
Rows are kinds of frame, columns are layers L1 to L12, each cell is the relative error of that layer. Red cells exceed your tolerance. Below, each slice gets a pass or fail against a 5% mAP-drop gate.
Toy model, illustrative: the same twelve synthetic layers as the first device, INT8 with min/max ranges. The mAP gate compares the toy slice score with its FP32 value.
With day-only calibration the map has a clear story. Day is clean. Dusk and rain each have a cell over the line (dusk L7 at 11%, rain L3 at 17%). Night lights up L3, L6, L7 and L8, and L7 is the worst at 51%. The first column that crosses a 10% tolerance in the night row is L3, at 13%, and the largest is L7. A mean over the twelve layers would have said 10%, a number that points at nothing.
Now switch the calibration to day and night. The night row cools. The dusk and rain rows improve too. The fix was not a trick in the compiler. It was showing the ruler the data it would meet.
Layer error is a cause. The decision still rests on the task metric. Report mAP for every slice that matters: day, dusk, night, rain, glare, a far-range band, small objects. Set a gate per slice, for example “no more than 5% relative drop from FP32”. A release that fails any slice does not ship. The aggregate stays on the dashboard, but it does not decide.
A slice with few images gives a noisy score. Suppose the night slice has 400 images and a score near 0.40. Treating it like a proportion for a rough size: the standard error is √(0.40 × 0.60 / 400) = 0.0245, and a 95% interval is about ±0.048. A drop of 0.02 would be invisible. Two ways help: compare on the same images for both models (a paired test, which cancels the image-to-image noise), and collect more night images. The evaluation statistics lesson builds these tests in full.
Tolerances need a floor too. Run the original model twice on different settings (FP32 against TF32, or two GPUs) and measure how much its own outputs move. That spread is the noise floor, and a tolerance below it will fail for no reason. Set INT8 tolerances from your own measurements, not from a blog.
pythonimport numpy as np def layer_parity(ref, got, tol): """ref/got: dict layer_name -> array. Returns the first layer over tol, and all errors.""" errs = {k: np.linalg.norm(got[k] - ref[k]) / (np.linalg.norm(ref[k]) + 1e-12) for k in ref} first = next((k for k in ref if errs[k] > tol[k]), None) # dict order = execution order return first, errs def slice_gate(map_ref, map_got, max_drop=0.05): """One verdict per slice: relative mAP drop against a gate.""" return {s: (map_ref[s] - map_got[s]) / map_ref[s] <= max_drop for s in map_ref}
The failure mode is the one this chapter opened with: a single aggregate metric hides a slice collapse. The symptom is a field failure under one condition. The measurement is the slice table and the layer map. The fix is per-slice gates, a calibration set that spans the slices, and per-layer tolerances in the release check.
Chapter 6
Measure latency in a way that gives the same answer tomorrow, on the next release, and on the next board
On Monday the engine runs at 2.30 ms. A teammate changes one fusion setting and reports 2.05 ms. On Tuesday someone repeats the test and gets 2.40 ms. Which number is true? Possibly none of them. The board was cooler on Monday, a background job ran on Tuesday, and the GPU clock moved with the load.
A benchmark is only useful if it gives the same answer when nothing has changed. This chapter lists what to fix so that it does, and then turns the list into a test that guards every release.
A Jetson is built to save power. Its operating system lowers the GPU, CPU and memory clocks when the load is light, and raises them when work arrives. This is dynamic frequency scaling. A short benchmark can run while the clock is still climbing, or after heat has pushed it down. Three more things add noise. The first runs are slow because kernels are loaded, caches are cold and memory is being allocated (warm-up). Other processes share the board. And a changing input size changes the work.
Jetson Linux sets limits with power modes (chosen with nvpmodel). The jetson_clocks script then locks the CPU, GPU and memory clocks to the maxima of the active mode, so frequency scaling stops. Choose the power mode first. Check them with sudo nvpmodel -q and sudo jetson_clocks --show. The lesson on the edge roofline and thermals goes deeper (edge roofline and thermals).
Two sessions of the same engine, run on different days. The teal line is session A and the dim line is session B. Choose the clocks, decide whether to drop the first runs, and set the number of runs.
Simulated, illustrative: a 2.30 ms engine, a warm-up transient over the first runs, a slow clock drift under power saving, and 2% noise. No real board was measured for this device. Real drift depends on load and temperature.
Run it with default clocks and 100 runs. In this simulation the two sessions disagree by about 19%, because each caught the drifting clock at a different point. Lock the clocks and the gap falls below 1%. Go back to default clocks and raise the runs to 400: the gap is still about 3%. More runs help, but they cannot fix a clock that keeps moving. The warm-up runs also pull any mean up, which is why you drop them or report the median.
Two details of the numbers. A 99th percentile needs enough runs: with 100 runs it is just the second-slowest run, which is one unlucky sample. With 1,000 runs it is the tenth-slowest, which is stable enough to compare. And pinned memory (page-locked host memory that the GPU can read directly) removes a copy from the timing, so a benchmark that uses it measures a different path than one that does not. State which you used.
trtexec reports GPU Compute Time, the kernel time for one inference, and a host latency that adds the copies in and out. The Ultralytics numbers in Chapter 2 exclude pre and post processing. Your control loop sees more than any of these, as the inference latency stack lesson shows.A regression test is a check that runs on every release and fails when something got worse. Keep a baseline file: for each model, each device and each software release, the median and the 99th percentile you accepted. On a new build, run the same harness and compare. The tolerance should come from the harness itself. If repeated sessions on a quiet board spread by 1%, a limit of 3% is meaningful. A limit of 0.1% fails every day.
Run the accuracy gates of Chapter 5 in the same job. A release that is 8% faster and fails the night slice must not ship, and a release that passes accuracy but is 12% slower must be explained. The regression testing lesson covers the general pattern.
pythonimport json, statistics as st def summarise(times_ms, warmup=20): t = sorted(times_ms[warmup:]) # drop warm-up runs return {"median": st.median(t), "p99": t[int(0.99 * (len(t) - 1))]} def check(key, now, baselines="baselines.json", slack=0.03): """key = 'yolo26n|agx-orin|trt10.x|maxn'. Fail if slower than baseline by more than slack.""" base = json.load(open(baselines))[key] for m in ("median", "p99"): assert now[m] <= base[m] * (1 + slack), f"{key} {m}: {now[m]:.2f} ms vs {base[m]:.2f} ms"
The failure mode: a benchmark at default power settings gives numbers that move, so a real regression hides in the noise and a fake one blocks a good release. The fix is to lock clocks first, then compare.
Chapter 7
Train with the rounding in the loop when calibration alone cannot recover the accuracy
The team fixed the night collapse with better calibration. Now the release gates in Chapter 5 show a smaller problem: with some layers pushed to 4-bit weights to save memory, three slices drop 6% to 9%. Better ranges do not fix it. The weights themselves sit at awkward places on the grid.
Post-training quantisation rounds a finished model. It never asks the model whether it minds. Quantisation-aware training (QAT) does ask. It trains the network with the rounding already inside, so the weights move to values that are good on the grid, and the other parameters shift to make up the difference.
During training, every quantised tensor goes through a fake quantiser: quantise, then immediately dequantise. The numbers stay floats, but they now sit on the grid, so the network feels the rounding. At export, the real integers replace the fake ones, and the network behaves the same.
One problem blocks learning. Rounding is a staircase. Its slope is zero almost everywhere, so the gradient (the signal that says which way to nudge a weight) dies. The fix is the straight-through estimator (STE): in the forward pass use the rounded value, in the backward pass pretend the staircase was a straight line. A weight outside the clipping range gets no gradient, since moving it changes nothing.
Walk one weight through it. Take the 4-bit grid with scale s = 1 / 7 = 0.143, where the largest weight is 1.0. A latent weight w = 0.43 gives w / s = 3.01, which rounds to 3, so the forward pass uses y = 0.429. Suppose the gradient says “lower this weight” by 0.002 per step. After one step w = 0.428, and the forward value is still 0.429. The weight does not move on the grid at all until w falls below 0.357, where w / s drops under 2.5 and the value jumps to 2 × 0.143 = 0.286. This is why QAT keeps the full-precision latent weight: small pushes add up until they cross a rounding edge.
Try it on a tiny problem. Sixteen weights predict a target from sixteen features that are strongly related to each other. Press Train and watch the error of the quantised weights. The flat line is what rounding after training gives.
Choose a bit width. Press Train to run 500 steps. Then switch on the mismatch and train again.
A real computation, but a toy problem, illustrative: 256 samples, 16 correlated features, plain gradient descent with a falling learning rate, and error shown as a share of the target’s power. Real networks have many layers and other parameters that also adapt.
At 4 bits, rounding after training leaves an error of 3.4% of the signal. QAT brings it down to about 0.5%. At 8 bits, rounding is already good (0.01%), and QAT has little to add. That is the usual pattern. Krishnamoorthi’s whitepaper reports 8-bit post-training quantisation within 2% of floating point on many CNNs, and QAT narrowing the gap to about 1%. With QAT it also reaches 4-bit weights, at losses of 2% to 10%, larger for smaller networks.
Now the failure that this chapter exists to warn about. Switch on the mismatch. The training used a scale 0.8 times the one the export will use. The network learned to be good on the wrong grid. When the real grid is applied, the error at 4 bits is worse than plain rounding: about 9% of the signal, against 3.4%. The accuracy was real in the training run. It was lost at export.
QAT needs training data, training compute and a training loop you control. Use it when calibration, per-channel scales and layer exclusions have not closed the gaps of Chapter 5, or when you go to 4 bits. Put night images in its data, for the reason Chapter 0 gave.
For large language models, the recovery step is usually LoRA: freeze the quantised model and train small low-rank add-on matrices. QLoRA (Dettmers et al., 2023) backpropagates gradients through a frozen, 4-bit quantised pretrained model into LoRA adapters. See LLM post-training for the mechanics.
pythonimport torch def fake_quant(w, s, bits=8): q = 2**(bits-1) - 1 wq = torch.clamp(torch.round(w / s), -q, q) * s # snapped to the grid return w + (wq - w).detach() # forward: wq backward: identity (STE) # In training: y = x @ fake_quant(W, s_export, 4).T # At export: write Q/DQ nodes with the SAME s_export, per-channel axis and rounding mode.
Chapter 8
Keep the numbers, the checklist and the core code in one place
Three steps, one loop. Quantise: pick a range for each tensor from data that looks like the field, with per-channel scales for weights and exclusions for fragile layers. Compile: let TensorRT time the tactics and build a plan for the exact device type that will run it. Prove: compare the binary with the original layer by layer and slice by slice, with tolerances you set before the run, and benchmark with locked clocks so the speed number is stable.
| Item | Value or rule | Where it comes from |
|---|---|---|
| YOLO26n, AGX Orin 64 GB, 640 px | PyTorch 11.58 ms, TensorRT FP32 4.18, FP16 2.62, INT8 2.30 | Ultralytics Jetson benchmarks, 8.4.32 |
| YOLO26n, Orin NX 16 GB | PyTorch 13.90 ms, FP32 7.01, FP16 4.13, INT8 3.49 | Ultralytics, 8.4.33 |
| COCO mAP50-95, AGX Orin | 0.4790, 0.4770, 0.4789, 0.4640 | Ultralytics (same four rungs) |
| COCO mAP50-95, Orin NX | 0.4799, 0.4770, 0.4789, 0.4489 | Ultralytics |
| Size on disk, AGX Orin | 5.3, 11.5, 7.9, 5.4 MB | Ultralytics |
| Timing scope | Inference time excludes pre and post processing | Ultralytics |
| INT8 scale | s = r / 127, symmetric scheme | TensorRT quantised types page (symmetric scheme); the r / 127 form is the standard scale for a signed 8-bit range |
| FP8 E4M3, FP4 E2M1 | Largest values 448 and 6, derived from the bit layouts | Micikevicius et al. 2022; TensorRT types |
| Weights and activations | Per-channel scales for weights, one scale per layer for activations | Krishnamoorthi 2018; TensorRT |
| PTQ and QAT at 8 bits | Within 2% of float after PTQ; about 1% with QAT; QAT with 4-bit weights loses 2% to 10% | Krishnamoorthi 2018 |
| Plan reuse | Same TensorRT version and same device type, by default | TensorRT Engine Compatibility |
| Plugins | IPluginV3; Python plugins by decorator from TensorRT 10.6 | TensorRT custom layers page |
| Locked clocks | nvpmodel first, then jetson_clocks | Jetson tooling guides (secondary) |
| Night toy model | L7 error 51% day-calibrated, 1.0% on day frames | This lesson, illustrative |
pythondef release_check(model, engine, frames_by_slice, tol, gate=0.05): """Quantise-compile-prove, as one gate. Returns (ok, report).""" report = {} for slice_name, frames in frames_by_slice.items(): ref = run_layers(model, frames) # dict layer -> array, original model got = run_layers(engine, frames) # same layers from the compiled engine first, errs = layer_parity(ref, got, tol) # Chapter 5: first layer over tolerance drop = 1 - map_score(engine, frames) / map_score(model, frames) report[slice_name] = {"first_bad_layer": first, "worst": max(errs.values()), "map_drop": drop} ok = all(r["map_drop"] <= gate and r["first_bad_layer"] is None for r in report.values()) return ok, report
This lesson follows Export, Partition, Fallback, which gets the model into a graph the compiler accepts. Next, the inference latency stack asks what the 2.30 ms is part of, and the edge roofline and thermals explains why the clocks you locked here will not always hold in the field. VLA on the robot applies the same loop to a large model, and neural engines and NPU runtimes shows the same ideas on other chips.
For the theory behind the ruler, read Quantization I, Quantization II and sparsity and quantization. For the test habit, read regression testing for ML and evaluation statistics. For the kernels under a plugin, read kernels and Triton. The silicon behind FP8 and FP4 gets its own lesson in this series; we name the topic here and do not link it.
Built from primary sources opened for this lesson. Measured latency, accuracy and size: Ultralytics, YOLO on NVIDIA Jetson. Engine and plugin behaviour: NVIDIA TensorRT documentation, Engine Compatibility, Working with Quantized Types and Extending TensorRT with Custom Layers. Theory: Krishnamoorthi, Quantizing deep convolutional networks for efficient inference; Micikevicius et al., FP8 Formats for Deep Learning; Dettmers et al., QLoRA. Jetson clock tooling: RidgeRun’s guide, a secondary source. The Jetson AGX Thor figure is from NVIDIA’s embedded systems page. The OCP Microscaling Formats specification defines block-scaled FP4 and FP8; we describe it from secondary summaries and suggest you read the specification itself. All night-frame numbers, the benchmark sessions and the QAT task are our own toy models, labelled where they appear.
Now press Present or Teach and explain the loop from memory: why a night frame clips, why INT8 gave 1.14 times, why a plan is tied to a device, and how you would prove parity. Then go back to the ladder at the top, calibrate on day and night, and check whether the red layer cools.