Sub topic 14
Exporting a Trained Model for Deployment
This chapter assumes you can train a YOLO model with the Ultralytics package and read its validation metrics. It also assumes you know what a confidence threshold and an NMS IoU threshold do. Here you will turn a trained checkpoint into a file that other runtimes can load, and learn what can go wrong along the way.
Why export at all
A training run produces a PyTorch checkpoint, usually best.pt. That file stores weights plus Python objects, so loading it needs PyTorch and the Ultralytics code. This is awkward or impossible on many targets: a C++ service, a phone, a browser, an embedded board, or a container that must stay small.
Exporting converts the model into a format that a dedicated inference runtime can execute. The runtime is often faster than PyTorch for inference and does not need the training stack.
Choosing a format
Each format targets a different runtime and hardware family.
| Format | `format=` value | Typical runtime | Typical use |
|---|---|---|---|
| ONNX | `onnx` | ONNX Runtime, OpenCV DNN, many others | Portable default; CPU and GPU servers |
| TensorRT | `engine` | NVIDIA TensorRT | Fastest inference on NVIDIA GPUs |
| OpenVINO | `openvino` | Intel OpenVINO | Intel CPUs and integrated GPUs |
| TorchScript | `torchscript` | LibTorch | C++ without Python |
| TensorFlow Lite | `tflite` | TFLite | Android and microcontroller-class devices |
| CoreML | `coreml` | Apple CoreML | iOS and macOS |
ONNX (Open Neural Network Exchange) is a vendor-neutral file format for a computation graph. It is the usual first step because several other converters accept ONNX as input. Format availability and extra dependencies change between Ultralytics versions, so check the export documentation for your installed version.
Exporting to ONNX
The export call loads the checkpoint, traces the network with a dummy input, and writes a file next to the weights.
from ultralytics import YOLO
model = YOLO("runs/detect/train/weights/best.pt")
path = model.export(format="onnx")
print(path)export returns the path of the new file. The ONNX file lands in the same folder as best.pt, as best.onnx.
Export options that change behavior
The defaults work for a first attempt. These options matter in practice:
imgsz: the input size baked into the graph. Use the size you trained or validated at.half=True: store weights as 16-bit floats. This roughly halves file size and speeds up GPU inference. It is not generally useful on CPU.dynamic=True: allow variable input height, width, and batch size. A fixed shape is usually faster and easier for converters to optimize.simplify=True: run an ONNX graph simplifier to remove redundant operations. It is on by default in recent versions.opset: the ONNX operator-set version. Pick one your target runtime supports.int8=True: quantize to 8-bit integers. This needs calibration data and is mainly for edge targets (see below).
What the exported model outputs
An exported model is not always a drop-in replacement for the Python predictor. The Ultralytics predict call does three things around the network: it resizes and pads the image, runs the network, and applies confidence filtering and NMS. A plain ONNX export usually contains only the network. Its output is a raw tensor that you must decode yourself.
For a YOLOv8 detection model with 80 classes at 640×640 input, the ONNX output has shape (1, 84, 8400). The 84 rows are 4 box values (centre x, centre y, width, height, in input-pixel units) followed by 80 class scores. The 8400 columns are candidate boxes from all feature-map positions. There is no separate objectness score in this layout; the highest class score serves as the confidence. Other YOLO versions use different layouts, so always inspect the output shape of your own file.
The practical consequence is that your deployment code must reproduce preprocessing and postprocessing exactly as the training framework did.
Running the ONNX model
The Ultralytics package can load an ONNX file and handle pre- and postprocessing for you. That is the quickest way to confirm the export works.
from ultralytics import YOLO
onnx_model = YOLO("runs/detect/train/weights/best.onnx")
results = onnx_model.predict("bus.jpg", conf=0.25, iou=0.7)
for r in results:
for box in r.boxes:
print(onnx_model.names[int(box.cls[0])], round(float(box.conf[0]), 2))To run without Ultralytics, use ONNX Runtime directly. The sketch below handles the parts that most often go wrong: letterbox resizing, channel order, scaling, and the transposed output. It assumes the (1, 4+nc, N) layout described above and uses opencv-python, numpy, and onnxruntime.
import cv2
import numpy as np
import onnxruntime as ort
def letterbox(img, size=640, pad_value=114):
h, w = img.shape[:2]
scale = min(size / h, size / w)
nh, nw = round(h * scale), round(w * scale)
resized = cv2.resize(img, (nw, nh), interpolation=cv2.INTER_LINEAR)
canvas = np.full((size, size, 3), pad_value, dtype=np.uint8)
top, left = (size - nh) // 2, (size - nw) // 2
canvas[top:top + nh, left:left + nw] = resized
return canvas, scale, left, top
def detect(session, image_path, conf_thr=0.25, iou_thr=0.7, size=640):
img = cv2.imread(image_path) # BGR, uint8
canvas, scale, left, top = letterbox(img, size)
blob = canvas[:, :, ::-1].transpose(2, 0, 1) # BGR->RGB, HWC->CHW
blob = np.ascontiguousarray(blob, dtype=np.float32)[None] / 255.0
out = session.run(None, {session.get_inputs()[0].name: blob})[0]
preds = out[0].T # (N, 4+nc)
scores_all = preds[:, 4:]
class_ids = scores_all.argmax(axis=1)
scores = scores_all.max(axis=1)
keep = scores >= conf_thr
preds, class_ids, scores = preds[keep], class_ids[keep], scores[keep]
cx, cy, w, h = preds[:, 0], preds[:, 1], preds[:, 2], preds[:, 3]
# Undo letterbox: remove padding, then divide by the resize scale.
x1 = (cx - w / 2 - left) / scale
y1 = (cy - h / 2 - top) / scale
x2 = (cx + w / 2 - left) / scale
y2 = (cy + h / 2 - top) / scale
# cv2 NMS expects (x, y, w, h) boxes.
xywh = np.stack([x1, y1, x2 - x1, y2 - y1], axis=1).tolist()
idx = cv2.dnn.NMSBoxes(xywh, scores.tolist(), conf_thr, iou_thr)
return [
(int(class_ids[i]), float(scores[i]),
[float(x1[i]), float(y1[i]), float(x2[i]), float(y2[i])])
for i in np.array(idx).flatten()
]
session = ort.InferenceSession(
"runs/detect/train/weights/best.onnx",
providers=["CPUExecutionProvider"],
)
for cls_id, score, box in detect(session, "bus.jpg"):
print(cls_id, round(score, 2), [round(v) for v in box])Note that cv2.dnn.NMSBoxes applies NMS across all classes together. Ultralytics suppresses per class by default, so two overlapping boxes of different classes may both survive in Ultralytics but not here. Use cv2.dnn.NMSBoxesBatched or run NMS per class if that difference matters.
Verifying the export
An export can succeed and still be wrong. Check it before shipping.
- Run the same image through the
.ptmodel and the exported model with identicalconfandiou. - Compare the number of detections, the classes, and the box coordinates. Small differences of a pixel or two are normal. Large gaps are not.
- Run validation on the exported model with
YOLO("best.onnx").val(data="my_data.yaml")and compare mAP with the original. A drop below about one point of mAP50-95 is typical for FP16. A larger drop points to a bug or an aggressive quantization.
Common export and deployment problems
- Boxes are shifted or the wrong size. The letterbox padding or scale was not undone. Map coordinates back using the same
scale,left, andtopused in preprocessing. - Detections are poor but not absent. Check channel order (RGB versus BGR) and the 0-1 scaling. OpenCV loads images as BGR; the model expects RGB.
- Image size errors at inference. The model was exported with a fixed
imgsz. Feed that exact size or re-export withdynamic=True. - Duplicate boxes everywhere. The exported graph contains no NMS and your code skipped it. Add NMS as shown above.
- Class names are missing. The ONNX file does not carry your Python class list in a way every runtime reads. Keep your
namesmapping from the dataset YAML alongside the file. - Operator not supported. The
opsetis too new or too old for your runtime. Re-export with a differentopset. - GPU provider ignored. ONNX Runtime falls back to CPU if the CUDA provider cannot load. Print
session.get_providers()to see what was actually used.
Quantization and calibration
INT8 quantization stores weights, and often activations, as 8-bit integers. It cuts size and latency on edge hardware but can reduce accuracy. Static INT8 export needs a calibration set, a few hundred representative images that let the converter estimate value ranges. If calibration images differ from production images (different lighting, camera, or scene), accuracy may drop more than your validation score suggests. Always re-run validation on the quantized model.
A deployment checklist
- Keep the dataset YAML (class names) and training
imgszwith the model file. - Record the confidence and NMS IoU thresholds you chose in the previous chapter.
- Record the library versions used for export and for runtime.
- Test the exported file on the target hardware, not only on your workstation.
- Compare exported metrics with the original checkpoint.
Exercise
You export a YOLOv8 model to ONNX and run it with ONNX Runtime. The output tensor has shape (1, 84, 8400), but your code reads it as (8400, 84) by simply reshaping, and detections look random. What should you do instead, and what does each of the 84 values per candidate represent?
Show answer
Transpose the output (out[0].T) so each row is one candidate box; reshaping scrambles the values because the data is stored as 84 rows by 8400 columns. Each candidate has 84 values: the first 4 are the box (centre x, centre y, width, height in input pixels) and the remaining 80 are class scores. The highest class score is the confidence and its index is the class.
Exercise
Your exported model's boxes are consistently offset toward the top-left and too small when run on a 1280×720 photo with a 640×640 input. Which preprocessing and postprocessing values were most likely mishandled?
Show answer
The letterbox parameters. The image is scaled by min(640/720, 640/1280) = 0.5 and padded vertically. The padding offsets (left and top) and the scale must be subtracted and divided out when mapping boxes back to the original image. Forgetting either step shifts and shrinks the boxes.