Article sections
Why does an AI model run slowly in production?What is ONNX, and why is it used?How do ONNX Runtime, TensorRT, and OpenVINO differ?What do FP32, FP16, and INT8 change?The difference between Post-Training Quantization and QATWhy is runtime fallback a hidden bottleneck?Batch size, dynamic shapes, and model cachingWhy can preprocessing and data transfer matter more than model speed?How does a numerical difference become a quality error?What information is essential in a benchmark report?What information should be retained in the production package?Field example: preserving small scratchesWhat mismatches should be checked after ONNX export?How do you choose a quantization calibration dataset?How do you diagnose operator fallback?TensorRT engines, versions, and the trust boundaryWhat do pruning and knowledge distillation offer for model compression?What criteria should determine the best engine?The Pareto frontier in precision-latency comparisonsDynamic shapes and engine optimization profilesModel compilation and startup behaviorA separate model quality regression suiteConcurrent sharing of runtime resourcesWhen should we change the model architecture?Why is it wrong to think model conversion is just a file extension change?How do you prepare representative data for INT8 quantization?How do you make a runtime benchmark fair?Traceability of the deployed engineExample experiment: how to report an FP32, FP16, and INT8 comparisonFrequently asked questionsWhy does an AI model run slowly in production?
A model may appear fast in its training environment yet fail to achieve the expected FPS in production. The problem does not always stem from the model architecture. Input transformations, CPU-GPU data copies, unsupported operators, runtime choices, an incorrect batch size, and the GPU's power/thermal state affect total performance. The first step in optimization is therefore not choosing a new technology, but measuring where the slowdown occurs.
For example, suppose the model takes 14 ms according to the inference engine's own measurements, but a total of 30 ms elapses before the product decision. If the remaining 16 ms comes from data transfer, pre/postprocessing, and output communication, accelerating only the model's core computation provides limited gains. Conversely, if the model takes 80 ms on the GPU and the entire chain takes 90 ms, focusing on runtime and model optimization makes more sense.
Generalizations such as "installing TensorRT makes it four times faster" are not sound engineering criteria. Actual gains depend on model operators, hardware architecture, supported precisions, and input shape. We cannot call an optimization successful without measurements made on the same hardware with the same input.
What is ONNX, and why is it used?
ONNX is an open format intended to transfer a model's computational graph and parameters between tools. It provides a common intermediate layer for moving from the training framework to another runtime. However, creating an ONNX file alone does not guarantee full compatibility on the target device or identical numerical results. Operator versions, dynamic input shapes, control flow, custom layers, and whether pre/postprocessing is included in the graph all matter.
Visual testing should follow export: the same sample images are passed through both the source model and the new runtime, and output differences are measured. Bounding-box coordinate scaling, mask dimensions, NMS behavior, and score ordering are verified. A small logit difference may seem unimportant in classification; however, for a sample very close to an anomaly threshold, it can change the product's accept/reject decision.
ONNX does not replace a hardware driver or runtime. The file format and the engine that executes it should be considered separately. Completing model export marks the beginning of a new compatibility test, not a performance test.
How do ONNX Runtime, TensorRT, and OpenVINO differ?
ONNX Runtime is a runtime that can execute a model graph in suitable computing environments through different Execution Providers (EPs). Providers such as CPU, CUDA, TensorRT, and OpenVINO can be used with different scopes of support. TensorRT is designed to optimize the inference graph and kernel selection on NVIDIA hardware. OpenVINO offers inference optimization on CPUs, GPUs, and supported NPUs in the Intel hardware ecosystem.
These names should not be read simply as a performance ranking. Building a TensorRT engine requires compatible model operators and shapes. In OpenVINO, the target device and driver capabilities are decisive. Using different EPs through ONNX Runtime can improve portability, but if some unsupported nodes fall back to another provider, more data copying and latency than expected may result. Success must be measured on the target platform.
| Tool | Primary role | What must be verified |
|---|---|---|
| ONNX | Model interchange format | Operator version, shapes, numerical comparison |
| ONNX Runtime | Execution framework and EP selection | EP support, fallback, data movement |
| TensorRT | Optimized inference on NVIDIA | Engine compatibility, precision, workspace, driver |
| OpenVINO | Optimized inference on Intel devices | CPU/GPU/NPU target, supported operators |
What do FP32, FP16, and INT8 change?
FP32 uses roughly a 32-bit floating-point representation, FP16 a lower-bit floating-point representation, and INT8 8-bit integer representations. Lower precision can provide higher throughput, lower memory use, and lower energy consumption on some hardware. However, these gains depend on the hardware having suitable cores and on the model graph using those cores efficiently. Some operators may continue to run at a different precision.
When using INT8, mapping numerical ranges requires calibration parameters such as scale and sometimes zero-point. If calibration data consists only of typical normal images, low-contrast defects or rare surface conditions may be underrepresented. Overall accuracy may then remain similar while the miss rate for small defects increases. Critical subgroups should therefore be checked alongside aggregate metrics.
FP16 conversion can be a practical first experiment for many models, but issues such as numerical overflow, very small gradient/activation values, or the precision requirements of particular operators must be tested. Numerical tolerances and the effects of decision thresholds should be defined in advance before moving to the production engine.
The difference between Post-Training Quantization and QAT
PTQ (Post-Training Quantization) quantizes an already trained model. It usually requires less training effort when moving to the target device; however, suitable calibration samples are essential. QAT (Quantization-Aware Training) accounts for quantization effects during training. In exchange for greater training complexity, it can recover quality lost through PTQ in some models.
The two methods should not be compared solely by asking "how many accuracy points are lost compared with FP32?" Defect type, lighting, low contrast, and product-level false-reject outcomes should be reported. In some applications, a 0.3% loss in average accuracy may be unimportant, while an increase in missed critical defects may be unacceptable. Decision thresholds must also be revalidated because the distribution of confidence scores may change after quantization.
Why is runtime fallback a hidden bottleneck?
If the target Execution Provider does not support all of the model's operators, parts of the graph may run on another provider, or conversion may fail. A graph that moves data back and forth between the CPU and GPU may remain slow despite a fast compute kernel. Tools that report which operators run on which EP should therefore be used, and the application should be checked for unexpected fallback.
For example, the model's convolutional layers may drop to 8 ms on the GPU while postprocessing moves to the CPU and adds a 15 ms wait. If only neural network latency is measured in the new version, the system appears to take 8 ms. The correct measurement is an end-to-end comparison that includes data movement and postprocessing. This shifts the optimization objective from the model to the entire system.
Batch size, dynamic shapes, and model caching
Increasing batch size can improve computational efficiency, but it may increase latency for an individual product. Dynamic-shape models make it easier to handle different image sizes, but some engines may require extra time to build optimization profiles and switch shapes. If the first model run involves kernel compilation, engine loading, or cache creation, warm and cold starts should be evaluated separately.
If every product uses the same resolution in production, a fixed input shape may be more predictable for the target runtime. However, variable resolution may be a genuine requirement in a system that processes differently sized ROIs to preserve small defects. Performance decisions should be based on this actual input distribution.
Why can preprocessing and data transfer matter more than model speed?
For high-resolution images, color conversion, copying, normalization, cropping, and letterboxing can account for a large share of total time. Some operations may be more efficient on the GPU, but unnecessary copies to and from the GPU can introduce new costs. Errors such as converting the same image twice in succession are also not uncommon.
Optimization requires a measure-change-measure again cycle. If a change improves only p50, check that p99 has not worsened. Measurement under real load with camera traffic, disk logging, and other GPU users may be more meaningful than a benchmark on an idle machine.
How does a numerical difference become a quality error?
If a defect classifier outputs 0.501 and the decision threshold is 0.500, a very small change can flip the class. Comparing model outputs between FP32 and INT8 may show a small absolute difference for most samples; however, which products change near the decision boundary should be reported separately. In segmentation, a 1-2 pixel mask difference can have a large effect on measurement, particularly for thin scratches.
A good regression set does not consist solely of random normal images. It should include critical defects, reflections, low contrast, small objects, image edges, and different product batches. Decision differences are compared against the accepted operational tolerance; production approval is not granted solely on the basis of average L2 tensor differences.
What information is essential in a benchmark report?
The model file hash, runtime and version, GPU/CPU model, driver, target device, input resolution, batch size, precision, warmup, total test repetitions, number of concurrent jobs, and measurement time boundaries should be reported. Device temperature and power limits can also affect performance results. TensorRT's official performance documentation likewise treats measurement and optimization as successive processes.
Comparing two engines when one runs FP16 batch 8 and the other FP32 batch 1 is not a comparison under equal conditions. First, equivalent workload requirements are established for each candidate; the range of configurations best suited to the device is then tested. The goal should not simply be maximum throughput, but an option that fits the production budget and preserves quality.
What information should be retained in the production package?
Keeping only model.onnx may not be enough. Export settings, the input/output contract, normalization parameters, runtime/driver compatibility, the generated engine's hash, precision selection, calibration set version, and validation report should be managed together. In particular, optimized engines may need to be rebuilt when the hardware, runtime, or driver changes.
The rollback plan should include the inference engine and configuration as well as the model. Reverting only the model file after an update may not resolve a compatibility issue caused by the new runtime. Testing that we can return to a previous version before deployment is part of production acceptance.
Field example: preserving small scratches
Suppose we detect scratches on a metal part using a segmentation model. Switching to FP16 reduces p95 inference time. However, suppose most scratches are 5-7 pixels wide and some masks become narrower after quantization. In this scenario, despite the speed gain, the quality loss may have operational consequences. Masks should be compared not only visually but also by critical defect type using Dice/IoU and product-level FN.
As a second step, INT8 can be tried using PTQ; however, actual scratch examples must be appropriately included in the calibration set without retraining. Measurements report model execution time and total pipeline time separately. Threshold selection is also revalidated using the calibrated validation set.
What mismatches should be checked after ONNX export?
Exporting a model to ONNX is not simply writing a file. Some layers from the source framework may have been converted into a different graph; small differences may arise in resizing, interpolation, padding, pooling, and coordinate transformations. Some of these differences do not alter aggregate accuracy but can affect decisions for products close to the threshold. Both intermediate output dimensions and final predictions should therefore be compared using a suitable sample set.
In object detection, some models perform NMS outside the graph. NMS may run on the CPU in one runtime and with a different kernel in another. The comparison is not fair unless the confidence threshold, IoU threshold, and bounding-box format are the same. In segmentation, replacing nearest with bilinear or another interpolation method can affect fine boundaries. The model's input and output contract should therefore be stored together with the schema.
For dynamic-shape models, creating an export file does not justify assuming that the target runtime supports every shape. Minimum/optimal/maximum input ranges, batch limits, and shape-switching costs are tested in detail. The size and data-type limits of every model output are also verified.
How do you choose a quantization calibration dataset?
When using PTQ, calibration data should represent the activation ranges the model will encounter in production. A set consisting only of easy normal samples may produce inappropriate scales in some channels. Different material batches, lighting changes, low-contrast defects, and product families should be included in calibration or at least in regression evaluation. However, selecting the calibration set based on the final test can contaminate the evaluation.
Tracking decision changes per image is useful. For a product scoring 0.51 in FP32 and 0.49 in INT8, a nominal threshold of 0.50 means the prediction has changed. Even if a single sample shows only a very small numerical deviation, the production decision may differ. Particularly with imbalanced class proportions, the cost of a few changed critical defects matters more than the average accuracy difference.
The calibration set version should be retained. When a new product family is added, the adequacy of the old calibration distribution is reassessed. If precision loss is critical, QAT, selective precision, or a model architecture change can be tried. All of these require separate controlled experiments.
How do you diagnose operator fallback?
A runtime executing a model on a CPU, GPU, or NPU does not necessarily mean that every node runs on the same device. If some operators are unsupported and fall back to another provider, tensor copies may multiply. Profiler output should be examined to determine which node runs on which provider, and total latency should be broken down.
For example, suppose 19 layers of a 20-layer model run quickly on the GPU, but the final custom operator requires CPU fallback. This last stage, including data conversions, may consume most of the time. In such a case, changing the operator or optimizing postprocessing may be more effective than buying a faster GPU.
CPU fallback is not always an error; some lightweight operators may be fast enough on the CPU. The problem is failing to measure unexpected copying and synchronization. The target runtime's support list and actual profiler results should be evaluated together so that silent performance loss becomes observable.
TensorRT engines, versions, and the trust boundary
An optimized engine file should not be treated as a general-purpose interchange format like the source model. The hardware on which it was built, runtime version, and configuration options may affect portability. The compiled execution plan must also come only from a trusted source; loading engine files can have security implications different from reading an ordinary data file.
The model file, engine file, and validation report are therefore managed together in the CI/CD process. If the engine will be regenerated on the target device, performance and quality must be measured again before production. The last working version of the old engine can be retained, but there is no guarantee that it will still work after an incompatible driver update.
What do pruning and knowledge distillation offer for model compression?
Pruning removes certain connections or channels. However, sparse weights appearing smaller in a file does not automatically mean a speed gain on the target hardware. Structured pruning can offer a more direct reduction in computation for certain operators, but model quality must be verified through retraining or fine-tuning. Distillation, a teacher-student method, attempts to transfer a larger model's behavior to a smaller model.
These methods are more substantial model-development interventions than inference runtime tuning because the representation learned by the model may change. The new model must therefore be reevaluated on small defects, hard negatives, and field subgroups. Fewer parameters alone do not guarantee faster or more reliable results in a production system.
What criteria should determine the best engine?
For a business, the best engine may not be the one with the lowest GPU-only latency. Meeting the target p99 end-to-end latency, not missing critical defects, staying within memory limits, remaining stable under sustained load, and offering a version lifecycle the maintenance team can manage must all be evaluated together.
For example, the decision table can include the source model, ONNX Runtime CPU, CUDA EP, TensorRT FP16, and TensorRT INT8 as candidates. Each candidate is tested with the same subgroup dataset. Improvements are recorded together with memory use and power consumption. Some candidates are eliminated if they do not meet business requirements, even if they are technically fast. The right measure of optimization is not a faster tensor, but a more reliable production decision.
The Pareto frontier in precision-latency comparisons
Rather than ranking acceleration candidates by a single metric, it is more useful to examine them along quality and performance axes. For example, the FP32 model may show 31 ms and high recall, FP16 21 ms and similar recall, and INT8 16 ms but a noticeable recall drop for critical scratches. In this case, INT8 may be unsuitable for production despite being the fastest option. FP16 may be preferable if it both meets the deadline and preserves behavior on critical defects.
A candidate that is both slower and lower in quality may be dominated by another candidate. Conversely, choosing between a faster option with a slight quality loss and a slower but more reliable option depends on business cost. The Pareto approach makes the actual engineering trade-off visible, but the points used must be measured under the same data and hardware conditions.
Dynamic shapes and engine optimization profiles
Some models must work with different input resolutions or batch sizes. Even if the optimized runtime supports this variety, every shape should not be expected to deliver the same performance. It may be possible to use a separate optimization profile for a frequently used input size. However, profile switching and memory reallocation can introduce latency.
If the ROI changes by product family in production, shapes from the actual distribution should be included in the benchmark. Measurements made only at the optimal profile size may hide deadline violations for products using rare but large ROIs. Both output correctness and latency should be tested across all accepted input sizes.
Model compilation and startup behavior
Some engines require substantial compilation time to turn a model into an executable engine. This cost does not usually occur on every frame of continuous operation, but it matters during deployment, restart, or model changes. Warmup and readiness checks should be completed before processing the first product. A "Process started" signal is not necessarily equivalent to a "model ready" signal.
In particular, if the device restarts itself and the camera stream begins before the engine is loaded, products may pass without inspection. The readiness protocol should wait for joint verification of the camera, model runtime, and PLC contract. A slow-loading engine must not cause the system to silently use the old model.
A separate model quality regression suite
Reporting only an accuracy metric on the test set after acceleration is incomplete. For classification, near-threshold samples and FN by defect type can be examined; for detection, bounding-box coordinate differences and small-object AP; for segmentation, boundary differences in thin masks; and for anomaly detection, score distributions. Changes in final product-level decisions are also counted separately.
For example, suppose FP32 and FP16 make the same decision on 998 of the same 1,000 products. If the two changed products have critical defects, the operational risk may be large. It is therefore necessary to examine which products changed and under what physical conditions. A small numerical difference does not directly imply a low cost.
Concurrent sharing of runtime resources
Using a single-model benchmark result is misleading when two models run on the same GPU. Even if model A alone takes 20 ms and B takes 15 ms, concurrent jobs share memory bandwidth and compute cores. Scheduling order and synchronization costs may increase total latency. Production tests must therefore run with all actual model and camera workloads enabled.
A runtime may also need to share the same CUDA version with other libraries. After a driver or runtime update, one model may work while others fail. The deployment package should include all library versions used together.
When should we change the model architecture?
If measurements show that runtime optimization is insufficient, a smaller backbone, patch-based processing, or a two-stage cascade can be considered. However, an architectural change returns to the problem of data and model training. The lightweight model must preserve small-defect recall, the new system must perform adequately across different product batches, and latency gains must be measured end to end.
This decision should not rest solely on a diagnosis of "the GPU is slow." If camera images are unnecessarily large, appropriate optics and ROI selection may solve the problem more cheaply; if illumination is poor, lighting changes may help; if copies are unnecessary, the software architecture may be the issue. Changing the model is only one of many options.
Why is it wrong to think model conversion is just a file extension change?
Exporting a model from its training framework to ONNX is an important compatibility step, but it does not automatically guarantee that the resulting graph will give the same result in the target runtime. Preprocessing order, input normalization, tensor dimension layout, dynamic axes, and postprocessing rules also determine model behavior. For example, a model trained with RGB images normalized using particular mean and standard deviation values may continue producing output when fed BGR data in production, but that output may be semantically different from what is expected.
Conversion testing compares source-model and target-runtime outputs on the same inputs. This comparison should not check only the final class label. Logit or probability differences, bounding-box coordinates, mask boundaries, and decision changes around the threshold are also examined. While many products may fall into the same class, rare and borderline defects can switch between acceptance and rejection because of differences of a few decimal places. Low-contrast defects, very small objects, dark images, and maximum input resolutions are deliberately included in the test set.
Unsupported operators sometimes cause errors during conversion; in other cases, the runtime switches to an alternative implementation path. For example, an ONNX Runtime Execution Provider may offload some graph sections to hardware while running others on the CPU. In this case, performance is affected not only by operator execution time but also by memory copies between devices. Verifying which subgraph runs where on the target hardware is an integral part of performance evaluation.
How do you prepare representative data for INT8 quantization?
Selecting calibration images for post-training quantization solely from hundreds of random normal products is risky. Low light, different material batches, dark-colored products, shiny metal surfaces, and rare defects in production affect model activation distributions. The calibration set should represent as closely as possible the value ranges that may be encountered during quantization. It must not replace the final independent test set, and repeated tuning against the test set should be avoided.
Quantization calibration must be distinguished here from probability calibration. The former focuses on choosing ranges and scales for representing tensors at low bit widths; the latter concerns how well model confidence scores align with observed accuracy. Using the same word for two different processes can cause misunderstandings in project meetings. The technical report should state explicitly what is being calibrated.
For example, in an illustrative scratch-detection system, suppose the FP32 model's recall for thin scratches is 96% and the INT8 version's is 92%. Even if average accuracy remains almost unchanged, this change may be unacceptable for some production lines. A sound comparison evaluates class- and defect-size-level metrics, near-threshold samples, false-reject cost, and latency gains together. These numbers are only a thought example and must not be interpreted as the actual performance of any runtime.
How do you make a runtime benchmark fair?
Initial benchmark measurements taken before the GPU has warmed up may differ from measurements under sustained load. It should be recorded which portions of engine compilation, cache creation, warmup, asynchronous calls, and data transfers are included. Comparing only the model's kernel execution time does not show the elapsed time from retrieving a real image from the camera buffer to producing a decision. Both microbenchmarks and end-to-end system measurements are therefore needed.
A fair comparison fixes the hardware model, power mode, driver version, runtime version, input size, batch size, precision, data layout, warmup count, total measurement duration, and temperature conditions. The report should also note whether different runtimes provide automatic batching or performance hints. For example, OpenVINO's latency-oriented and throughput-oriented settings can produce different results on the same device; they optimize different workload objectives. The phrase "fastest runtime" is meaningful only in the context of particular hardware and a particular workload.
In an experiment where batch 8 increases the number of images processed per second, total response time may have risen because the first product waits for the batch to fill. If every product on the camera line has a hard decision window, throughput gains become secondary. Conversely, a larger batch may be advantageous in a batch analysis system processing archived images overnight. Optimization must match the user's bottleneck.
Traceability of the deployed engine
Archiving only the model's weights file is insufficient. The ONNX graph, optimization parameters, target GPU type, engine-building tools, versions, calibration set identity, and thresholds should be retained so the same system can be reproduced when needed. In particular, engine files tied to hardware and runtime versions must not be assumed portable across all platforms. Compatibility testing should be performed on the deployment device.
Model files and serialized engines are part of the trust boundary. Executing unverified binary artifacts of unknown origin on a production device may create a security risk. Methods such as artifact signing, hash verification, access permissions, and loading only from approved sources should be included in the software lifecycle. A new engine should not automatically enter production simply because it loaded successfully; the same observation and quality tests must be confirmed to have passed.
Example experiment: how to report an FP32, FP16, and INT8 comparison
In an educational comparison, suppose the FP32 version has a p95 inference time of 25 ms per image, FP16 18 ms, and INT8 15 ms. This table alone is insufficient to choose INT8. If scratches 3 pixels wide are critical in production, every version should be examined on that subgroup. Suppose critical-defect recall is measured at 98% for the baseline FP32 version, 98% for FP16, and 94% for INT8. In this hypothetical case, a 10 ms speed gain may not be worth the risk of letting defective products through.
A more meaningful report is divided into three layers. The first is model quality: FP/FN, recall by defect type, calibration, and threshold changes. The second is system performance: p50/p95/p99 end-to-end time, throughput, memory, and thermal load. The third is operations: engine preparation time, startup, model version compatibility, safe rollback, and maintenance cost. This framework shows which optimization is meaningful regardless of tool names.
A fair experiment also requires fixed input resolution, ROI, and image normalization. Comparing ONNX Runtime and TensorRT while including data transfer in one measurement and excluding it in the other produces incorrect results. Engine warmup and compilation times are reported separately according to actual application requirements. For lines that run for days, the initial compilation cost may be small; at a station that restarts frequently, startup time may be critical.
Ultimately, the "fastest engine" and the "best engine for production" do not have to be the same option. The decision table should make clear how speed gains are balanced against quality costs and operational risk. The conditions for rolling back an optimization and a revalidation method using sample production products should also be prepared before approval.
Frequently asked questions
Does the ONNX format automatically accelerate a model?
No. ONNX is a portable computational graph format. Acceleration depends on how the chosen runtime and hardware execute that graph.
Is INT8 always faster than FP32?
No. Hardware support, model operators, tensor sizes, and data movement are decisive. Gains may be limited in some applications.
Does a TensorRT plan file run on every NVIDIA GPU?
Compatibility depends on the version, build settings, and hardware; not all engine files should be assumed universally portable.
Is deployment ready if model accuracy is unchanged?
No. End-to-end latency, stability, resource usage, failure behavior, version traceability, and rollback must also be tested.
Technical sources and verification
Manufacturers' and standards organizations' documentation forms the basis for details of standards and runtimes used by these methods. Unless explicitly stated otherwise, all example figures are for educational purposes.
- ONNX Runtime - Execution Providers
- NVIDIA - TensorRT benchmarking
- NVIDIA - TensorRT optimization
- OpenVINO - Latency/throughput objectives
Visual note: The nine technical diagrams are original, and numerical examples are for educational purposes. The illustrations are not actual device benchmarks, facility measurements, or factory acceptance tests.