dgenerate-ultralytics-headless 8.3.134__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- dgenerate_ultralytics_headless-8.3.134.dist-info/METADATA +400 -0
- dgenerate_ultralytics_headless-8.3.134.dist-info/RECORD +272 -0
- dgenerate_ultralytics_headless-8.3.134.dist-info/WHEEL +5 -0
- dgenerate_ultralytics_headless-8.3.134.dist-info/entry_points.txt +3 -0
- dgenerate_ultralytics_headless-8.3.134.dist-info/licenses/LICENSE +661 -0
- dgenerate_ultralytics_headless-8.3.134.dist-info/top_level.txt +1 -0
- tests/__init__.py +22 -0
- tests/conftest.py +83 -0
- tests/test_cli.py +138 -0
- tests/test_cuda.py +215 -0
- tests/test_engine.py +131 -0
- tests/test_exports.py +236 -0
- tests/test_integrations.py +154 -0
- tests/test_python.py +694 -0
- tests/test_solutions.py +187 -0
- ultralytics/__init__.py +30 -0
- ultralytics/assets/bus.jpg +0 -0
- ultralytics/assets/zidane.jpg +0 -0
- ultralytics/cfg/__init__.py +1023 -0
- ultralytics/cfg/datasets/Argoverse.yaml +77 -0
- ultralytics/cfg/datasets/DOTAv1.5.yaml +37 -0
- ultralytics/cfg/datasets/DOTAv1.yaml +36 -0
- ultralytics/cfg/datasets/GlobalWheat2020.yaml +68 -0
- ultralytics/cfg/datasets/HomeObjects-3K.yaml +33 -0
- ultralytics/cfg/datasets/ImageNet.yaml +2025 -0
- ultralytics/cfg/datasets/Objects365.yaml +443 -0
- ultralytics/cfg/datasets/SKU-110K.yaml +58 -0
- ultralytics/cfg/datasets/VOC.yaml +106 -0
- ultralytics/cfg/datasets/VisDrone.yaml +77 -0
- ultralytics/cfg/datasets/african-wildlife.yaml +25 -0
- ultralytics/cfg/datasets/brain-tumor.yaml +23 -0
- ultralytics/cfg/datasets/carparts-seg.yaml +44 -0
- ultralytics/cfg/datasets/coco-pose.yaml +42 -0
- ultralytics/cfg/datasets/coco.yaml +118 -0
- ultralytics/cfg/datasets/coco128-seg.yaml +101 -0
- ultralytics/cfg/datasets/coco128.yaml +101 -0
- ultralytics/cfg/datasets/coco8-multispectral.yaml +104 -0
- ultralytics/cfg/datasets/coco8-pose.yaml +26 -0
- ultralytics/cfg/datasets/coco8-seg.yaml +101 -0
- ultralytics/cfg/datasets/coco8.yaml +101 -0
- ultralytics/cfg/datasets/crack-seg.yaml +22 -0
- ultralytics/cfg/datasets/dog-pose.yaml +24 -0
- ultralytics/cfg/datasets/dota8-multispectral.yaml +38 -0
- ultralytics/cfg/datasets/dota8.yaml +35 -0
- ultralytics/cfg/datasets/hand-keypoints.yaml +26 -0
- ultralytics/cfg/datasets/lvis.yaml +1240 -0
- ultralytics/cfg/datasets/medical-pills.yaml +22 -0
- ultralytics/cfg/datasets/open-images-v7.yaml +666 -0
- ultralytics/cfg/datasets/package-seg.yaml +22 -0
- ultralytics/cfg/datasets/signature.yaml +21 -0
- ultralytics/cfg/datasets/tiger-pose.yaml +25 -0
- ultralytics/cfg/datasets/xView.yaml +155 -0
- ultralytics/cfg/default.yaml +127 -0
- ultralytics/cfg/models/11/yolo11-cls-resnet18.yaml +17 -0
- ultralytics/cfg/models/11/yolo11-cls.yaml +33 -0
- ultralytics/cfg/models/11/yolo11-obb.yaml +50 -0
- ultralytics/cfg/models/11/yolo11-pose.yaml +51 -0
- ultralytics/cfg/models/11/yolo11-seg.yaml +50 -0
- ultralytics/cfg/models/11/yolo11.yaml +50 -0
- ultralytics/cfg/models/11/yoloe-11-seg.yaml +48 -0
- ultralytics/cfg/models/11/yoloe-11.yaml +48 -0
- ultralytics/cfg/models/12/yolo12-cls.yaml +32 -0
- ultralytics/cfg/models/12/yolo12-obb.yaml +48 -0
- ultralytics/cfg/models/12/yolo12-pose.yaml +49 -0
- ultralytics/cfg/models/12/yolo12-seg.yaml +48 -0
- ultralytics/cfg/models/12/yolo12.yaml +48 -0
- ultralytics/cfg/models/rt-detr/rtdetr-l.yaml +53 -0
- ultralytics/cfg/models/rt-detr/rtdetr-resnet101.yaml +45 -0
- ultralytics/cfg/models/rt-detr/rtdetr-resnet50.yaml +45 -0
- ultralytics/cfg/models/rt-detr/rtdetr-x.yaml +57 -0
- ultralytics/cfg/models/v10/yolov10b.yaml +45 -0
- ultralytics/cfg/models/v10/yolov10l.yaml +45 -0
- ultralytics/cfg/models/v10/yolov10m.yaml +45 -0
- ultralytics/cfg/models/v10/yolov10n.yaml +45 -0
- ultralytics/cfg/models/v10/yolov10s.yaml +45 -0
- ultralytics/cfg/models/v10/yolov10x.yaml +45 -0
- ultralytics/cfg/models/v3/yolov3-spp.yaml +49 -0
- ultralytics/cfg/models/v3/yolov3-tiny.yaml +40 -0
- ultralytics/cfg/models/v3/yolov3.yaml +49 -0
- ultralytics/cfg/models/v5/yolov5-p6.yaml +62 -0
- ultralytics/cfg/models/v5/yolov5.yaml +51 -0
- ultralytics/cfg/models/v6/yolov6.yaml +56 -0
- ultralytics/cfg/models/v8/yoloe-v8-seg.yaml +45 -0
- ultralytics/cfg/models/v8/yoloe-v8.yaml +45 -0
- ultralytics/cfg/models/v8/yolov8-cls-resnet101.yaml +28 -0
- ultralytics/cfg/models/v8/yolov8-cls-resnet50.yaml +28 -0
- ultralytics/cfg/models/v8/yolov8-cls.yaml +32 -0
- ultralytics/cfg/models/v8/yolov8-ghost-p2.yaml +58 -0
- ultralytics/cfg/models/v8/yolov8-ghost-p6.yaml +60 -0
- ultralytics/cfg/models/v8/yolov8-ghost.yaml +50 -0
- ultralytics/cfg/models/v8/yolov8-obb.yaml +49 -0
- ultralytics/cfg/models/v8/yolov8-p2.yaml +57 -0
- ultralytics/cfg/models/v8/yolov8-p6.yaml +59 -0
- ultralytics/cfg/models/v8/yolov8-pose-p6.yaml +60 -0
- ultralytics/cfg/models/v8/yolov8-pose.yaml +50 -0
- ultralytics/cfg/models/v8/yolov8-rtdetr.yaml +49 -0
- ultralytics/cfg/models/v8/yolov8-seg-p6.yaml +59 -0
- ultralytics/cfg/models/v8/yolov8-seg.yaml +49 -0
- ultralytics/cfg/models/v8/yolov8-world.yaml +51 -0
- ultralytics/cfg/models/v8/yolov8-worldv2.yaml +49 -0
- ultralytics/cfg/models/v8/yolov8.yaml +49 -0
- ultralytics/cfg/models/v9/yolov9c-seg.yaml +41 -0
- ultralytics/cfg/models/v9/yolov9c.yaml +41 -0
- ultralytics/cfg/models/v9/yolov9e-seg.yaml +64 -0
- ultralytics/cfg/models/v9/yolov9e.yaml +64 -0
- ultralytics/cfg/models/v9/yolov9m.yaml +41 -0
- ultralytics/cfg/models/v9/yolov9s.yaml +41 -0
- ultralytics/cfg/models/v9/yolov9t.yaml +41 -0
- ultralytics/cfg/trackers/botsort.yaml +22 -0
- ultralytics/cfg/trackers/bytetrack.yaml +14 -0
- ultralytics/data/__init__.py +26 -0
- ultralytics/data/annotator.py +66 -0
- ultralytics/data/augment.py +2945 -0
- ultralytics/data/base.py +438 -0
- ultralytics/data/build.py +258 -0
- ultralytics/data/converter.py +754 -0
- ultralytics/data/dataset.py +834 -0
- ultralytics/data/loaders.py +676 -0
- ultralytics/data/scripts/download_weights.sh +18 -0
- ultralytics/data/scripts/get_coco.sh +61 -0
- ultralytics/data/scripts/get_coco128.sh +18 -0
- ultralytics/data/scripts/get_imagenet.sh +52 -0
- ultralytics/data/split.py +125 -0
- ultralytics/data/split_dota.py +325 -0
- ultralytics/data/utils.py +777 -0
- ultralytics/engine/__init__.py +1 -0
- ultralytics/engine/exporter.py +1519 -0
- ultralytics/engine/model.py +1156 -0
- ultralytics/engine/predictor.py +502 -0
- ultralytics/engine/results.py +1840 -0
- ultralytics/engine/trainer.py +853 -0
- ultralytics/engine/tuner.py +243 -0
- ultralytics/engine/validator.py +377 -0
- ultralytics/hub/__init__.py +168 -0
- ultralytics/hub/auth.py +137 -0
- ultralytics/hub/google/__init__.py +176 -0
- ultralytics/hub/session.py +446 -0
- ultralytics/hub/utils.py +248 -0
- ultralytics/models/__init__.py +9 -0
- ultralytics/models/fastsam/__init__.py +7 -0
- ultralytics/models/fastsam/model.py +61 -0
- ultralytics/models/fastsam/predict.py +181 -0
- ultralytics/models/fastsam/utils.py +24 -0
- ultralytics/models/fastsam/val.py +40 -0
- ultralytics/models/nas/__init__.py +7 -0
- ultralytics/models/nas/model.py +102 -0
- ultralytics/models/nas/predict.py +58 -0
- ultralytics/models/nas/val.py +39 -0
- ultralytics/models/rtdetr/__init__.py +7 -0
- ultralytics/models/rtdetr/model.py +63 -0
- ultralytics/models/rtdetr/predict.py +84 -0
- ultralytics/models/rtdetr/train.py +85 -0
- ultralytics/models/rtdetr/val.py +191 -0
- ultralytics/models/sam/__init__.py +6 -0
- ultralytics/models/sam/amg.py +260 -0
- ultralytics/models/sam/build.py +358 -0
- ultralytics/models/sam/model.py +170 -0
- ultralytics/models/sam/modules/__init__.py +1 -0
- ultralytics/models/sam/modules/blocks.py +1129 -0
- ultralytics/models/sam/modules/decoders.py +515 -0
- ultralytics/models/sam/modules/encoders.py +854 -0
- ultralytics/models/sam/modules/memory_attention.py +299 -0
- ultralytics/models/sam/modules/sam.py +1006 -0
- ultralytics/models/sam/modules/tiny_encoder.py +1002 -0
- ultralytics/models/sam/modules/transformer.py +351 -0
- ultralytics/models/sam/modules/utils.py +394 -0
- ultralytics/models/sam/predict.py +1605 -0
- ultralytics/models/utils/__init__.py +1 -0
- ultralytics/models/utils/loss.py +455 -0
- ultralytics/models/utils/ops.py +268 -0
- ultralytics/models/yolo/__init__.py +7 -0
- ultralytics/models/yolo/classify/__init__.py +7 -0
- ultralytics/models/yolo/classify/predict.py +88 -0
- ultralytics/models/yolo/classify/train.py +233 -0
- ultralytics/models/yolo/classify/val.py +215 -0
- ultralytics/models/yolo/detect/__init__.py +7 -0
- ultralytics/models/yolo/detect/predict.py +124 -0
- ultralytics/models/yolo/detect/train.py +217 -0
- ultralytics/models/yolo/detect/val.py +451 -0
- ultralytics/models/yolo/model.py +354 -0
- ultralytics/models/yolo/obb/__init__.py +7 -0
- ultralytics/models/yolo/obb/predict.py +66 -0
- ultralytics/models/yolo/obb/train.py +81 -0
- ultralytics/models/yolo/obb/val.py +283 -0
- ultralytics/models/yolo/pose/__init__.py +7 -0
- ultralytics/models/yolo/pose/predict.py +79 -0
- ultralytics/models/yolo/pose/train.py +154 -0
- ultralytics/models/yolo/pose/val.py +394 -0
- ultralytics/models/yolo/segment/__init__.py +7 -0
- ultralytics/models/yolo/segment/predict.py +113 -0
- ultralytics/models/yolo/segment/train.py +123 -0
- ultralytics/models/yolo/segment/val.py +428 -0
- ultralytics/models/yolo/world/__init__.py +5 -0
- ultralytics/models/yolo/world/train.py +119 -0
- ultralytics/models/yolo/world/train_world.py +176 -0
- ultralytics/models/yolo/yoloe/__init__.py +22 -0
- ultralytics/models/yolo/yoloe/predict.py +169 -0
- ultralytics/models/yolo/yoloe/train.py +298 -0
- ultralytics/models/yolo/yoloe/train_seg.py +124 -0
- ultralytics/models/yolo/yoloe/val.py +191 -0
- ultralytics/nn/__init__.py +29 -0
- ultralytics/nn/autobackend.py +842 -0
- ultralytics/nn/modules/__init__.py +182 -0
- ultralytics/nn/modules/activation.py +53 -0
- ultralytics/nn/modules/block.py +1966 -0
- ultralytics/nn/modules/conv.py +712 -0
- ultralytics/nn/modules/head.py +880 -0
- ultralytics/nn/modules/transformer.py +713 -0
- ultralytics/nn/modules/utils.py +164 -0
- ultralytics/nn/tasks.py +1627 -0
- ultralytics/nn/text_model.py +351 -0
- ultralytics/solutions/__init__.py +41 -0
- ultralytics/solutions/ai_gym.py +116 -0
- ultralytics/solutions/analytics.py +252 -0
- ultralytics/solutions/config.py +106 -0
- ultralytics/solutions/distance_calculation.py +124 -0
- ultralytics/solutions/heatmap.py +127 -0
- ultralytics/solutions/instance_segmentation.py +84 -0
- ultralytics/solutions/object_blurrer.py +90 -0
- ultralytics/solutions/object_counter.py +195 -0
- ultralytics/solutions/object_cropper.py +84 -0
- ultralytics/solutions/parking_management.py +273 -0
- ultralytics/solutions/queue_management.py +93 -0
- ultralytics/solutions/region_counter.py +120 -0
- ultralytics/solutions/security_alarm.py +154 -0
- ultralytics/solutions/similarity_search.py +172 -0
- ultralytics/solutions/solutions.py +724 -0
- ultralytics/solutions/speed_estimation.py +110 -0
- ultralytics/solutions/streamlit_inference.py +196 -0
- ultralytics/solutions/templates/similarity-search.html +160 -0
- ultralytics/solutions/trackzone.py +88 -0
- ultralytics/solutions/vision_eye.py +68 -0
- ultralytics/trackers/__init__.py +7 -0
- ultralytics/trackers/basetrack.py +124 -0
- ultralytics/trackers/bot_sort.py +260 -0
- ultralytics/trackers/byte_tracker.py +480 -0
- ultralytics/trackers/track.py +125 -0
- ultralytics/trackers/utils/__init__.py +1 -0
- ultralytics/trackers/utils/gmc.py +376 -0
- ultralytics/trackers/utils/kalman_filter.py +493 -0
- ultralytics/trackers/utils/matching.py +157 -0
- ultralytics/utils/__init__.py +1435 -0
- ultralytics/utils/autobatch.py +106 -0
- ultralytics/utils/autodevice.py +174 -0
- ultralytics/utils/benchmarks.py +695 -0
- ultralytics/utils/callbacks/__init__.py +5 -0
- ultralytics/utils/callbacks/base.py +234 -0
- ultralytics/utils/callbacks/clearml.py +153 -0
- ultralytics/utils/callbacks/comet.py +552 -0
- ultralytics/utils/callbacks/dvc.py +205 -0
- ultralytics/utils/callbacks/hub.py +108 -0
- ultralytics/utils/callbacks/mlflow.py +138 -0
- ultralytics/utils/callbacks/neptune.py +140 -0
- ultralytics/utils/callbacks/raytune.py +43 -0
- ultralytics/utils/callbacks/tensorboard.py +132 -0
- ultralytics/utils/callbacks/wb.py +185 -0
- ultralytics/utils/checks.py +897 -0
- ultralytics/utils/dist.py +119 -0
- ultralytics/utils/downloads.py +499 -0
- ultralytics/utils/errors.py +43 -0
- ultralytics/utils/export.py +219 -0
- ultralytics/utils/files.py +221 -0
- ultralytics/utils/instance.py +499 -0
- ultralytics/utils/loss.py +813 -0
- ultralytics/utils/metrics.py +1356 -0
- ultralytics/utils/ops.py +885 -0
- ultralytics/utils/patches.py +143 -0
- ultralytics/utils/plotting.py +1011 -0
- ultralytics/utils/tal.py +416 -0
- ultralytics/utils/torch_utils.py +990 -0
- ultralytics/utils/triton.py +116 -0
- ultralytics/utils/tuner.py +159 -0
@@ -0,0 +1,695 @@
|
|
1
|
+
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
2
|
+
"""
|
3
|
+
Benchmark a YOLO model formats for speed and accuracy.
|
4
|
+
|
5
|
+
Usage:
|
6
|
+
from ultralytics.utils.benchmarks import ProfileModels, benchmark
|
7
|
+
ProfileModels(['yolo11n.yaml', 'yolov8s.yaml']).run()
|
8
|
+
benchmark(model='yolo11n.pt', imgsz=160)
|
9
|
+
|
10
|
+
Format | `format=argument` | Model
|
11
|
+
--- | --- | ---
|
12
|
+
PyTorch | - | yolo11n.pt
|
13
|
+
TorchScript | `torchscript` | yolo11n.torchscript
|
14
|
+
ONNX | `onnx` | yolo11n.onnx
|
15
|
+
OpenVINO | `openvino` | yolo11n_openvino_model/
|
16
|
+
TensorRT | `engine` | yolo11n.engine
|
17
|
+
CoreML | `coreml` | yolo11n.mlpackage
|
18
|
+
TensorFlow SavedModel | `saved_model` | yolo11n_saved_model/
|
19
|
+
TensorFlow GraphDef | `pb` | yolo11n.pb
|
20
|
+
TensorFlow Lite | `tflite` | yolo11n.tflite
|
21
|
+
TensorFlow Edge TPU | `edgetpu` | yolo11n_edgetpu.tflite
|
22
|
+
TensorFlow.js | `tfjs` | yolo11n_web_model/
|
23
|
+
PaddlePaddle | `paddle` | yolo11n_paddle_model/
|
24
|
+
MNN | `mnn` | yolo11n.mnn
|
25
|
+
NCNN | `ncnn` | yolo11n_ncnn_model/
|
26
|
+
RKNN | `rknn` | yolo11n_rknn_model/
|
27
|
+
"""
|
28
|
+
|
29
|
+
import glob
|
30
|
+
import os
|
31
|
+
import platform
|
32
|
+
import re
|
33
|
+
import shutil
|
34
|
+
import time
|
35
|
+
from pathlib import Path
|
36
|
+
|
37
|
+
import numpy as np
|
38
|
+
import torch.cuda
|
39
|
+
|
40
|
+
from ultralytics import YOLO, YOLOWorld
|
41
|
+
from ultralytics.cfg import TASK2DATA, TASK2METRIC
|
42
|
+
from ultralytics.engine.exporter import export_formats
|
43
|
+
from ultralytics.utils import ARM64, ASSETS, IS_JETSON, LINUX, LOGGER, MACOS, TQDM, WEIGHTS_DIR, YAML
|
44
|
+
from ultralytics.utils.checks import IS_PYTHON_3_13, check_imgsz, check_requirements, check_yolo, is_rockchip
|
45
|
+
from ultralytics.utils.downloads import safe_download
|
46
|
+
from ultralytics.utils.files import file_size
|
47
|
+
from ultralytics.utils.torch_utils import get_cpu_info, select_device
|
48
|
+
|
49
|
+
|
50
|
+
def benchmark(
|
51
|
+
model=WEIGHTS_DIR / "yolo11n.pt",
|
52
|
+
data=None,
|
53
|
+
imgsz=160,
|
54
|
+
half=False,
|
55
|
+
int8=False,
|
56
|
+
device="cpu",
|
57
|
+
verbose=False,
|
58
|
+
eps=1e-3,
|
59
|
+
format="",
|
60
|
+
):
|
61
|
+
"""
|
62
|
+
Benchmark a YOLO model across different formats for speed and accuracy.
|
63
|
+
|
64
|
+
Args:
|
65
|
+
model (str | Path): Path to the model file or directory.
|
66
|
+
data (str | None): Dataset to evaluate on, inherited from TASK2DATA if not passed.
|
67
|
+
imgsz (int): Image size for the benchmark.
|
68
|
+
half (bool): Use half-precision for the model if True.
|
69
|
+
int8 (bool): Use int8-precision for the model if True.
|
70
|
+
device (str): Device to run the benchmark on, either 'cpu' or 'cuda'.
|
71
|
+
verbose (bool | float): If True or a float, assert benchmarks pass with given metric.
|
72
|
+
eps (float): Epsilon value for divide by zero prevention.
|
73
|
+
format (str): Export format for benchmarking. If not supplied all formats are benchmarked.
|
74
|
+
|
75
|
+
Returns:
|
76
|
+
(pandas.DataFrame): A pandas DataFrame with benchmark results for each format, including file size, metric,
|
77
|
+
and inference time.
|
78
|
+
|
79
|
+
Examples:
|
80
|
+
Benchmark a YOLO model with default settings:
|
81
|
+
>>> from ultralytics.utils.benchmarks import benchmark
|
82
|
+
>>> benchmark(model="yolo11n.pt", imgsz=640)
|
83
|
+
"""
|
84
|
+
imgsz = check_imgsz(imgsz)
|
85
|
+
assert imgsz[0] == imgsz[1] if isinstance(imgsz, list) else True, "benchmark() only supports square imgsz."
|
86
|
+
|
87
|
+
import pandas as pd # scope for faster 'import ultralytics'
|
88
|
+
|
89
|
+
pd.options.display.max_columns = 10
|
90
|
+
pd.options.display.width = 120
|
91
|
+
device = select_device(device, verbose=False)
|
92
|
+
if isinstance(model, (str, Path)):
|
93
|
+
model = YOLO(model)
|
94
|
+
is_end2end = getattr(model.model.model[-1], "end2end", False)
|
95
|
+
data = data or TASK2DATA[model.task] # task to dataset, i.e. coco8.yaml for task=detect
|
96
|
+
key = TASK2METRIC[model.task] # task to metric, i.e. metrics/mAP50-95(B) for task=detect
|
97
|
+
|
98
|
+
y = []
|
99
|
+
t0 = time.time()
|
100
|
+
|
101
|
+
format_arg = format.lower()
|
102
|
+
if format_arg:
|
103
|
+
formats = frozenset(export_formats()["Argument"])
|
104
|
+
assert format in formats, f"Expected format to be one of {formats}, but got '{format_arg}'."
|
105
|
+
for i, (name, format, suffix, cpu, gpu, _) in enumerate(zip(*export_formats().values())):
|
106
|
+
emoji, filename = "❌", None # export defaults
|
107
|
+
try:
|
108
|
+
if format_arg and format_arg != format:
|
109
|
+
continue
|
110
|
+
|
111
|
+
# Checks
|
112
|
+
if i == 7: # TF GraphDef
|
113
|
+
assert model.task != "obb", "TensorFlow GraphDef not supported for OBB task"
|
114
|
+
elif i == 9: # Edge TPU
|
115
|
+
assert LINUX and not ARM64, "Edge TPU export only supported on non-aarch64 Linux"
|
116
|
+
elif i in {5, 10}: # CoreML and TF.js
|
117
|
+
assert MACOS or (LINUX and not ARM64), (
|
118
|
+
"CoreML and TF.js export only supported on macOS and non-aarch64 Linux"
|
119
|
+
)
|
120
|
+
if i in {5}: # CoreML
|
121
|
+
assert not IS_PYTHON_3_13, "CoreML not supported on Python 3.13"
|
122
|
+
if i in {6, 7, 8, 9, 10}: # TF SavedModel, TF GraphDef, and TFLite, TF EdgeTPU and TF.js
|
123
|
+
assert not isinstance(model, YOLOWorld), "YOLOWorldv2 TensorFlow exports not supported by onnx2tf yet"
|
124
|
+
# assert not IS_PYTHON_MINIMUM_3_12, "TFLite exports not supported on Python>=3.12 yet"
|
125
|
+
if i == 11: # Paddle
|
126
|
+
assert not isinstance(model, YOLOWorld), "YOLOWorldv2 Paddle exports not supported yet"
|
127
|
+
assert model.task != "obb", "Paddle OBB bug https://github.com/PaddlePaddle/Paddle/issues/72024"
|
128
|
+
assert not is_end2end, "End-to-end models not supported by PaddlePaddle yet"
|
129
|
+
assert (LINUX and not IS_JETSON) or MACOS, "Windows and Jetson Paddle exports not supported yet"
|
130
|
+
if i == 12: # MNN
|
131
|
+
assert not isinstance(model, YOLOWorld), "YOLOWorldv2 MNN exports not supported yet"
|
132
|
+
if i == 13: # NCNN
|
133
|
+
assert not isinstance(model, YOLOWorld), "YOLOWorldv2 NCNN exports not supported yet"
|
134
|
+
if i == 14: # IMX
|
135
|
+
assert not is_end2end
|
136
|
+
assert not isinstance(model, YOLOWorld), "YOLOWorldv2 IMX exports not supported"
|
137
|
+
assert model.task == "detect", "IMX only supported for detection task"
|
138
|
+
assert "C2f" in model.__str__(), "IMX only supported for YOLOv8" # TODO: enable for YOLO11
|
139
|
+
if i == 15: # RKNN
|
140
|
+
assert not isinstance(model, YOLOWorld), "YOLOWorldv2 RKNN exports not supported yet"
|
141
|
+
assert not is_end2end, "End-to-end models not supported by RKNN yet"
|
142
|
+
assert LINUX, "RKNN only supported on Linux"
|
143
|
+
assert not is_rockchip(), "RKNN Inference only supported on Rockchip devices"
|
144
|
+
if "cpu" in device.type:
|
145
|
+
assert cpu, "inference not supported on CPU"
|
146
|
+
if "cuda" in device.type:
|
147
|
+
assert gpu, "inference not supported on GPU"
|
148
|
+
|
149
|
+
# Export
|
150
|
+
if format == "-":
|
151
|
+
filename = model.pt_path or model.ckpt_path or model.model_name
|
152
|
+
exported_model = model # PyTorch format
|
153
|
+
else:
|
154
|
+
filename = model.export(
|
155
|
+
imgsz=imgsz, format=format, half=half, int8=int8, data=data, device=device, verbose=False
|
156
|
+
)
|
157
|
+
exported_model = YOLO(filename, task=model.task)
|
158
|
+
assert suffix in str(filename), "export failed"
|
159
|
+
emoji = "❎" # indicates export succeeded
|
160
|
+
|
161
|
+
# Predict
|
162
|
+
assert model.task != "pose" or i != 7, "GraphDef Pose inference is not supported"
|
163
|
+
assert i not in {9, 10}, "inference not supported" # Edge TPU and TF.js are unsupported
|
164
|
+
assert i != 5 or platform.system() == "Darwin", "inference only supported on macOS>=10.13" # CoreML
|
165
|
+
if i in {13}:
|
166
|
+
assert not is_end2end, "End-to-end torch.topk operation is not supported for NCNN prediction yet"
|
167
|
+
exported_model.predict(ASSETS / "bus.jpg", imgsz=imgsz, device=device, half=half, verbose=False)
|
168
|
+
|
169
|
+
# Validate
|
170
|
+
results = exported_model.val(
|
171
|
+
data=data, batch=1, imgsz=imgsz, plots=False, device=device, half=half, int8=int8, verbose=False
|
172
|
+
)
|
173
|
+
metric, speed = results.results_dict[key], results.speed["inference"]
|
174
|
+
fps = round(1000 / (speed + eps), 2) # frames per second
|
175
|
+
y.append([name, "✅", round(file_size(filename), 1), round(metric, 4), round(speed, 2), fps])
|
176
|
+
except Exception as e:
|
177
|
+
if verbose:
|
178
|
+
assert type(e) is AssertionError, f"Benchmark failure for {name}: {e}"
|
179
|
+
LOGGER.error(f"Benchmark failure for {name}: {e}")
|
180
|
+
y.append([name, emoji, round(file_size(filename), 1), None, None, None]) # mAP, t_inference
|
181
|
+
|
182
|
+
# Print results
|
183
|
+
check_yolo(device=device) # print system info
|
184
|
+
df = pd.DataFrame(y, columns=["Format", "Status❔", "Size (MB)", key, "Inference time (ms/im)", "FPS"])
|
185
|
+
|
186
|
+
name = model.model_name
|
187
|
+
dt = time.time() - t0
|
188
|
+
legend = "Benchmarks legend: - ✅ Success - ❎ Export passed but validation failed - ❌️ Export failed"
|
189
|
+
s = f"\nBenchmarks complete for {name} on {data} at imgsz={imgsz} ({dt:.2f}s)\n{legend}\n{df.fillna('-')}\n"
|
190
|
+
LOGGER.info(s)
|
191
|
+
with open("benchmarks.log", "a", errors="ignore", encoding="utf-8") as f:
|
192
|
+
f.write(s)
|
193
|
+
|
194
|
+
if verbose and isinstance(verbose, float):
|
195
|
+
metrics = df[key].array # values to compare to floor
|
196
|
+
floor = verbose # minimum metric floor to pass, i.e. = 0.29 mAP for YOLOv5n
|
197
|
+
assert all(x > floor for x in metrics if pd.notna(x)), f"Benchmark failure: metric(s) < floor {floor}"
|
198
|
+
|
199
|
+
return df
|
200
|
+
|
201
|
+
|
202
|
+
class RF100Benchmark:
|
203
|
+
"""
|
204
|
+
Benchmark YOLO model performance across various formats for speed and accuracy.
|
205
|
+
|
206
|
+
This class provides functionality to benchmark YOLO models on the RF100 dataset collection.
|
207
|
+
|
208
|
+
Attributes:
|
209
|
+
ds_names (List[str]): Names of datasets used for benchmarking.
|
210
|
+
ds_cfg_list (List[Path]): List of paths to dataset configuration files.
|
211
|
+
rf (Roboflow): Roboflow instance for accessing datasets.
|
212
|
+
val_metrics (List[str]): Metrics used for validation.
|
213
|
+
|
214
|
+
Methods:
|
215
|
+
set_key: Set Roboflow API key for accessing datasets.
|
216
|
+
parse_dataset: Parse dataset links and download datasets.
|
217
|
+
fix_yaml: Fix train and validation paths in YAML files.
|
218
|
+
evaluate: Evaluate model performance on validation results.
|
219
|
+
"""
|
220
|
+
|
221
|
+
def __init__(self):
|
222
|
+
"""Initialize the RF100Benchmark class for benchmarking YOLO model performance across various formats."""
|
223
|
+
self.ds_names = []
|
224
|
+
self.ds_cfg_list = []
|
225
|
+
self.rf = None
|
226
|
+
self.val_metrics = ["class", "images", "targets", "precision", "recall", "map50", "map95"]
|
227
|
+
|
228
|
+
def set_key(self, api_key):
|
229
|
+
"""
|
230
|
+
Set Roboflow API key for processing.
|
231
|
+
|
232
|
+
Args:
|
233
|
+
api_key (str): The API key.
|
234
|
+
|
235
|
+
Examples:
|
236
|
+
Set the Roboflow API key for accessing datasets:
|
237
|
+
>>> benchmark = RF100Benchmark()
|
238
|
+
>>> benchmark.set_key("your_roboflow_api_key")
|
239
|
+
"""
|
240
|
+
check_requirements("roboflow")
|
241
|
+
from roboflow import Roboflow
|
242
|
+
|
243
|
+
self.rf = Roboflow(api_key=api_key)
|
244
|
+
|
245
|
+
def parse_dataset(self, ds_link_txt="datasets_links.txt"):
|
246
|
+
"""
|
247
|
+
Parse dataset links and download datasets.
|
248
|
+
|
249
|
+
Args:
|
250
|
+
ds_link_txt (str): Path to the file containing dataset links.
|
251
|
+
|
252
|
+
Returns:
|
253
|
+
ds_names (List[str]): List of dataset names.
|
254
|
+
ds_cfg_list (List[Path]): List of paths to dataset configuration files.
|
255
|
+
|
256
|
+
Examples:
|
257
|
+
>>> benchmark = RF100Benchmark()
|
258
|
+
>>> benchmark.set_key("api_key")
|
259
|
+
>>> benchmark.parse_dataset("datasets_links.txt")
|
260
|
+
"""
|
261
|
+
(shutil.rmtree("rf-100"), os.mkdir("rf-100")) if os.path.exists("rf-100") else os.mkdir("rf-100")
|
262
|
+
os.chdir("rf-100")
|
263
|
+
os.mkdir("ultralytics-benchmarks")
|
264
|
+
safe_download("https://github.com/ultralytics/assets/releases/download/v0.0.0/datasets_links.txt")
|
265
|
+
|
266
|
+
with open(ds_link_txt, encoding="utf-8") as file:
|
267
|
+
for line in file:
|
268
|
+
try:
|
269
|
+
_, url, workspace, project, version = re.split("/+", line.strip())
|
270
|
+
self.ds_names.append(project)
|
271
|
+
proj_version = f"{project}-{version}"
|
272
|
+
if not Path(proj_version).exists():
|
273
|
+
self.rf.workspace(workspace).project(project).version(version).download("yolov8")
|
274
|
+
else:
|
275
|
+
LOGGER.info("Dataset already downloaded.")
|
276
|
+
self.ds_cfg_list.append(Path.cwd() / proj_version / "data.yaml")
|
277
|
+
except Exception:
|
278
|
+
continue
|
279
|
+
|
280
|
+
return self.ds_names, self.ds_cfg_list
|
281
|
+
|
282
|
+
@staticmethod
|
283
|
+
def fix_yaml(path):
|
284
|
+
"""Fix the train and validation paths in a given YAML file."""
|
285
|
+
yaml_data = YAML.load(path)
|
286
|
+
yaml_data["train"] = "train/images"
|
287
|
+
yaml_data["val"] = "valid/images"
|
288
|
+
YAML.dump(yaml_data, path)
|
289
|
+
|
290
|
+
def evaluate(self, yaml_path, val_log_file, eval_log_file, list_ind):
|
291
|
+
"""
|
292
|
+
Evaluate model performance on validation results.
|
293
|
+
|
294
|
+
Args:
|
295
|
+
yaml_path (str): Path to the YAML configuration file.
|
296
|
+
val_log_file (str): Path to the validation log file.
|
297
|
+
eval_log_file (str): Path to the evaluation log file.
|
298
|
+
list_ind (int): Index of the current dataset in the list.
|
299
|
+
|
300
|
+
Returns:
|
301
|
+
(float): The mean average precision (mAP) value for the evaluated model.
|
302
|
+
|
303
|
+
Examples:
|
304
|
+
Evaluate a model on a specific dataset
|
305
|
+
>>> benchmark = RF100Benchmark()
|
306
|
+
>>> benchmark.evaluate("path/to/data.yaml", "path/to/val_log.txt", "path/to/eval_log.txt", 0)
|
307
|
+
"""
|
308
|
+
skip_symbols = ["🚀", "⚠️", "💡", "❌"]
|
309
|
+
class_names = YAML.load(yaml_path)["names"]
|
310
|
+
with open(val_log_file, encoding="utf-8") as f:
|
311
|
+
lines = f.readlines()
|
312
|
+
eval_lines = []
|
313
|
+
for line in lines:
|
314
|
+
if any(symbol in line for symbol in skip_symbols):
|
315
|
+
continue
|
316
|
+
entries = line.split(" ")
|
317
|
+
entries = list(filter(lambda val: val != "", entries))
|
318
|
+
entries = [e.strip("\n") for e in entries]
|
319
|
+
eval_lines.extend(
|
320
|
+
{
|
321
|
+
"class": entries[0],
|
322
|
+
"images": entries[1],
|
323
|
+
"targets": entries[2],
|
324
|
+
"precision": entries[3],
|
325
|
+
"recall": entries[4],
|
326
|
+
"map50": entries[5],
|
327
|
+
"map95": entries[6],
|
328
|
+
}
|
329
|
+
for e in entries
|
330
|
+
if e in class_names or (e == "all" and "(AP)" not in entries and "(AR)" not in entries)
|
331
|
+
)
|
332
|
+
map_val = 0.0
|
333
|
+
if len(eval_lines) > 1:
|
334
|
+
LOGGER.info("Multiple dicts found")
|
335
|
+
for lst in eval_lines:
|
336
|
+
if lst["class"] == "all":
|
337
|
+
map_val = lst["map50"]
|
338
|
+
else:
|
339
|
+
LOGGER.info("Single dict found")
|
340
|
+
map_val = [res["map50"] for res in eval_lines][0]
|
341
|
+
|
342
|
+
with open(eval_log_file, "a", encoding="utf-8") as f:
|
343
|
+
f.write(f"{self.ds_names[list_ind]}: {map_val}\n")
|
344
|
+
|
345
|
+
|
346
|
+
class ProfileModels:
|
347
|
+
"""
|
348
|
+
ProfileModels class for profiling different models on ONNX and TensorRT.
|
349
|
+
|
350
|
+
This class profiles the performance of different models, returning results such as model speed and FLOPs.
|
351
|
+
|
352
|
+
Attributes:
|
353
|
+
paths (List[str]): Paths of the models to profile.
|
354
|
+
num_timed_runs (int): Number of timed runs for the profiling.
|
355
|
+
num_warmup_runs (int): Number of warmup runs before profiling.
|
356
|
+
min_time (float): Minimum number of seconds to profile for.
|
357
|
+
imgsz (int): Image size used in the models.
|
358
|
+
half (bool): Flag to indicate whether to use FP16 half-precision for TensorRT profiling.
|
359
|
+
trt (bool): Flag to indicate whether to profile using TensorRT.
|
360
|
+
device (torch.device): Device used for profiling.
|
361
|
+
|
362
|
+
Methods:
|
363
|
+
profile: Profiles the models and prints the result.
|
364
|
+
get_files: Gets all relevant model files.
|
365
|
+
get_onnx_model_info: Extracts metadata from an ONNX model.
|
366
|
+
iterative_sigma_clipping: Applies sigma clipping to remove outliers.
|
367
|
+
profile_tensorrt_model: Profiles a TensorRT model.
|
368
|
+
profile_onnx_model: Profiles an ONNX model.
|
369
|
+
generate_table_row: Generates a table row with model metrics.
|
370
|
+
generate_results_dict: Generates a dictionary of profiling results.
|
371
|
+
print_table: Prints a formatted table of results.
|
372
|
+
|
373
|
+
Examples:
|
374
|
+
Profile models and print results
|
375
|
+
>>> from ultralytics.utils.benchmarks import ProfileModels
|
376
|
+
>>> profiler = ProfileModels(["yolo11n.yaml", "yolov8s.yaml"], imgsz=640)
|
377
|
+
>>> profiler.run()
|
378
|
+
"""
|
379
|
+
|
380
|
+
def __init__(
|
381
|
+
self,
|
382
|
+
paths: list,
|
383
|
+
num_timed_runs=100,
|
384
|
+
num_warmup_runs=10,
|
385
|
+
min_time=60,
|
386
|
+
imgsz=640,
|
387
|
+
half=True,
|
388
|
+
trt=True,
|
389
|
+
device=None,
|
390
|
+
):
|
391
|
+
"""
|
392
|
+
Initialize the ProfileModels class for profiling models.
|
393
|
+
|
394
|
+
Args:
|
395
|
+
paths (List[str]): List of paths of the models to be profiled.
|
396
|
+
num_timed_runs (int): Number of timed runs for the profiling.
|
397
|
+
num_warmup_runs (int): Number of warmup runs before the actual profiling starts.
|
398
|
+
min_time (float): Minimum time in seconds for profiling a model.
|
399
|
+
imgsz (int): Size of the image used during profiling.
|
400
|
+
half (bool): Flag to indicate whether to use FP16 half-precision for TensorRT profiling.
|
401
|
+
trt (bool): Flag to indicate whether to profile using TensorRT.
|
402
|
+
device (torch.device | str | None): Device used for profiling. If None, it is determined automatically.
|
403
|
+
|
404
|
+
Notes:
|
405
|
+
FP16 'half' argument option removed for ONNX as slower on CPU than FP32.
|
406
|
+
|
407
|
+
Examples:
|
408
|
+
Initialize and profile models
|
409
|
+
>>> from ultralytics.utils.benchmarks import ProfileModels
|
410
|
+
>>> profiler = ProfileModels(["yolo11n.yaml", "yolov8s.yaml"], imgsz=640)
|
411
|
+
>>> profiler.run()
|
412
|
+
"""
|
413
|
+
self.paths = paths
|
414
|
+
self.num_timed_runs = num_timed_runs
|
415
|
+
self.num_warmup_runs = num_warmup_runs
|
416
|
+
self.min_time = min_time
|
417
|
+
self.imgsz = imgsz
|
418
|
+
self.half = half
|
419
|
+
self.trt = trt # run TensorRT profiling
|
420
|
+
self.device = device if isinstance(device, torch.device) else select_device(device)
|
421
|
+
|
422
|
+
def run(self):
|
423
|
+
"""
|
424
|
+
Profile YOLO models for speed and accuracy across various formats including ONNX and TensorRT.
|
425
|
+
|
426
|
+
Returns:
|
427
|
+
(List[Dict]): List of dictionaries containing profiling results for each model.
|
428
|
+
|
429
|
+
Examples:
|
430
|
+
Profile models and print results
|
431
|
+
>>> from ultralytics.utils.benchmarks import ProfileModels
|
432
|
+
>>> profiler = ProfileModels(["yolo11n.yaml", "yolov8s.yaml"])
|
433
|
+
>>> results = profiler.run()
|
434
|
+
"""
|
435
|
+
files = self.get_files()
|
436
|
+
|
437
|
+
if not files:
|
438
|
+
LOGGER.warning("No matching *.pt or *.onnx files found.")
|
439
|
+
return
|
440
|
+
|
441
|
+
table_rows = []
|
442
|
+
output = []
|
443
|
+
for file in files:
|
444
|
+
engine_file = file.with_suffix(".engine")
|
445
|
+
if file.suffix in {".pt", ".yaml", ".yml"}:
|
446
|
+
model = YOLO(str(file))
|
447
|
+
model.fuse() # to report correct params and GFLOPs in model.info()
|
448
|
+
model_info = model.info()
|
449
|
+
if self.trt and self.device.type != "cpu" and not engine_file.is_file():
|
450
|
+
engine_file = model.export(
|
451
|
+
format="engine",
|
452
|
+
half=self.half,
|
453
|
+
imgsz=self.imgsz,
|
454
|
+
device=self.device,
|
455
|
+
verbose=False,
|
456
|
+
)
|
457
|
+
onnx_file = model.export(
|
458
|
+
format="onnx",
|
459
|
+
imgsz=self.imgsz,
|
460
|
+
device=self.device,
|
461
|
+
verbose=False,
|
462
|
+
)
|
463
|
+
elif file.suffix == ".onnx":
|
464
|
+
model_info = self.get_onnx_model_info(file)
|
465
|
+
onnx_file = file
|
466
|
+
else:
|
467
|
+
continue
|
468
|
+
|
469
|
+
t_engine = self.profile_tensorrt_model(str(engine_file))
|
470
|
+
t_onnx = self.profile_onnx_model(str(onnx_file))
|
471
|
+
table_rows.append(self.generate_table_row(file.stem, t_onnx, t_engine, model_info))
|
472
|
+
output.append(self.generate_results_dict(file.stem, t_onnx, t_engine, model_info))
|
473
|
+
|
474
|
+
self.print_table(table_rows)
|
475
|
+
return output
|
476
|
+
|
477
|
+
def get_files(self):
|
478
|
+
"""
|
479
|
+
Return a list of paths for all relevant model files given by the user.
|
480
|
+
|
481
|
+
Returns:
|
482
|
+
(List[Path]): List of Path objects for the model files.
|
483
|
+
"""
|
484
|
+
files = []
|
485
|
+
for path in self.paths:
|
486
|
+
path = Path(path)
|
487
|
+
if path.is_dir():
|
488
|
+
extensions = ["*.pt", "*.onnx", "*.yaml"]
|
489
|
+
files.extend([file for ext in extensions for file in glob.glob(str(path / ext))])
|
490
|
+
elif path.suffix in {".pt", ".yaml", ".yml"}: # add non-existing
|
491
|
+
files.append(str(path))
|
492
|
+
else:
|
493
|
+
files.extend(glob.glob(str(path)))
|
494
|
+
|
495
|
+
LOGGER.info(f"Profiling: {sorted(files)}")
|
496
|
+
return [Path(file) for file in sorted(files)]
|
497
|
+
|
498
|
+
@staticmethod
|
499
|
+
def get_onnx_model_info(onnx_file: str):
|
500
|
+
"""Extracts metadata from an ONNX model file including parameters, GFLOPs, and input shape."""
|
501
|
+
return 0.0, 0.0, 0.0, 0.0 # return (num_layers, num_params, num_gradients, num_flops)
|
502
|
+
|
503
|
+
@staticmethod
|
504
|
+
def iterative_sigma_clipping(data, sigma=2, max_iters=3):
|
505
|
+
"""
|
506
|
+
Apply iterative sigma clipping to data to remove outliers.
|
507
|
+
|
508
|
+
Args:
|
509
|
+
data (numpy.ndarray): Input data array.
|
510
|
+
sigma (float): Number of standard deviations to use for clipping.
|
511
|
+
max_iters (int): Maximum number of iterations for the clipping process.
|
512
|
+
|
513
|
+
Returns:
|
514
|
+
(numpy.ndarray): Clipped data array with outliers removed.
|
515
|
+
"""
|
516
|
+
data = np.array(data)
|
517
|
+
for _ in range(max_iters):
|
518
|
+
mean, std = np.mean(data), np.std(data)
|
519
|
+
clipped_data = data[(data > mean - sigma * std) & (data < mean + sigma * std)]
|
520
|
+
if len(clipped_data) == len(data):
|
521
|
+
break
|
522
|
+
data = clipped_data
|
523
|
+
return data
|
524
|
+
|
525
|
+
def profile_tensorrt_model(self, engine_file: str, eps: float = 1e-3):
|
526
|
+
"""
|
527
|
+
Profile YOLO model performance with TensorRT, measuring average run time and standard deviation.
|
528
|
+
|
529
|
+
Args:
|
530
|
+
engine_file (str): Path to the TensorRT engine file.
|
531
|
+
eps (float): Small epsilon value to prevent division by zero.
|
532
|
+
|
533
|
+
Returns:
|
534
|
+
mean_time (float): Mean inference time in milliseconds.
|
535
|
+
std_time (float): Standard deviation of inference time in milliseconds.
|
536
|
+
"""
|
537
|
+
if not self.trt or not Path(engine_file).is_file():
|
538
|
+
return 0.0, 0.0
|
539
|
+
|
540
|
+
# Model and input
|
541
|
+
model = YOLO(engine_file)
|
542
|
+
input_data = np.zeros((self.imgsz, self.imgsz, 3), dtype=np.uint8) # use uint8 for Classify
|
543
|
+
|
544
|
+
# Warmup runs
|
545
|
+
elapsed = 0.0
|
546
|
+
for _ in range(3):
|
547
|
+
start_time = time.time()
|
548
|
+
for _ in range(self.num_warmup_runs):
|
549
|
+
model(input_data, imgsz=self.imgsz, verbose=False)
|
550
|
+
elapsed = time.time() - start_time
|
551
|
+
|
552
|
+
# Compute number of runs as higher of min_time or num_timed_runs
|
553
|
+
num_runs = max(round(self.min_time / (elapsed + eps) * self.num_warmup_runs), self.num_timed_runs * 50)
|
554
|
+
|
555
|
+
# Timed runs
|
556
|
+
run_times = []
|
557
|
+
for _ in TQDM(range(num_runs), desc=engine_file):
|
558
|
+
results = model(input_data, imgsz=self.imgsz, verbose=False)
|
559
|
+
run_times.append(results[0].speed["inference"]) # Convert to milliseconds
|
560
|
+
|
561
|
+
run_times = self.iterative_sigma_clipping(np.array(run_times), sigma=2, max_iters=3) # sigma clipping
|
562
|
+
return np.mean(run_times), np.std(run_times)
|
563
|
+
|
564
|
+
def profile_onnx_model(self, onnx_file: str, eps: float = 1e-3):
|
565
|
+
"""
|
566
|
+
Profile an ONNX model, measuring average inference time and standard deviation across multiple runs.
|
567
|
+
|
568
|
+
Args:
|
569
|
+
onnx_file (str): Path to the ONNX model file.
|
570
|
+
eps (float): Small epsilon value to prevent division by zero.
|
571
|
+
|
572
|
+
Returns:
|
573
|
+
mean_time (float): Mean inference time in milliseconds.
|
574
|
+
std_time (float): Standard deviation of inference time in milliseconds.
|
575
|
+
"""
|
576
|
+
check_requirements("onnxruntime")
|
577
|
+
import onnxruntime as ort
|
578
|
+
|
579
|
+
# Session with either 'TensorrtExecutionProvider', 'CUDAExecutionProvider', 'CPUExecutionProvider'
|
580
|
+
sess_options = ort.SessionOptions()
|
581
|
+
sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
|
582
|
+
sess_options.intra_op_num_threads = 8 # Limit the number of threads
|
583
|
+
sess = ort.InferenceSession(onnx_file, sess_options, providers=["CPUExecutionProvider"])
|
584
|
+
|
585
|
+
input_tensor = sess.get_inputs()[0]
|
586
|
+
input_type = input_tensor.type
|
587
|
+
dynamic = not all(isinstance(dim, int) and dim >= 0 for dim in input_tensor.shape) # dynamic input shape
|
588
|
+
input_shape = (1, 3, self.imgsz, self.imgsz) if dynamic else input_tensor.shape
|
589
|
+
|
590
|
+
# Mapping ONNX datatype to numpy datatype
|
591
|
+
if "float16" in input_type:
|
592
|
+
input_dtype = np.float16
|
593
|
+
elif "float" in input_type:
|
594
|
+
input_dtype = np.float32
|
595
|
+
elif "double" in input_type:
|
596
|
+
input_dtype = np.float64
|
597
|
+
elif "int64" in input_type:
|
598
|
+
input_dtype = np.int64
|
599
|
+
elif "int32" in input_type:
|
600
|
+
input_dtype = np.int32
|
601
|
+
else:
|
602
|
+
raise ValueError(f"Unsupported ONNX datatype {input_type}")
|
603
|
+
|
604
|
+
input_data = np.random.rand(*input_shape).astype(input_dtype)
|
605
|
+
input_name = input_tensor.name
|
606
|
+
output_name = sess.get_outputs()[0].name
|
607
|
+
|
608
|
+
# Warmup runs
|
609
|
+
elapsed = 0.0
|
610
|
+
for _ in range(3):
|
611
|
+
start_time = time.time()
|
612
|
+
for _ in range(self.num_warmup_runs):
|
613
|
+
sess.run([output_name], {input_name: input_data})
|
614
|
+
elapsed = time.time() - start_time
|
615
|
+
|
616
|
+
# Compute number of runs as higher of min_time or num_timed_runs
|
617
|
+
num_runs = max(round(self.min_time / (elapsed + eps) * self.num_warmup_runs), self.num_timed_runs)
|
618
|
+
|
619
|
+
# Timed runs
|
620
|
+
run_times = []
|
621
|
+
for _ in TQDM(range(num_runs), desc=onnx_file):
|
622
|
+
start_time = time.time()
|
623
|
+
sess.run([output_name], {input_name: input_data})
|
624
|
+
run_times.append((time.time() - start_time) * 1000) # Convert to milliseconds
|
625
|
+
|
626
|
+
run_times = self.iterative_sigma_clipping(np.array(run_times), sigma=2, max_iters=5) # sigma clipping
|
627
|
+
return np.mean(run_times), np.std(run_times)
|
628
|
+
|
629
|
+
def generate_table_row(self, model_name, t_onnx, t_engine, model_info):
|
630
|
+
"""
|
631
|
+
Generate a table row string with model performance metrics.
|
632
|
+
|
633
|
+
Args:
|
634
|
+
model_name (str): Name of the model.
|
635
|
+
t_onnx (tuple): ONNX model inference time statistics (mean, std).
|
636
|
+
t_engine (tuple): TensorRT engine inference time statistics (mean, std).
|
637
|
+
model_info (tuple): Model information (layers, params, gradients, flops).
|
638
|
+
|
639
|
+
Returns:
|
640
|
+
(str): Formatted table row string with model metrics.
|
641
|
+
"""
|
642
|
+
layers, params, gradients, flops = model_info
|
643
|
+
return (
|
644
|
+
f"| {model_name:18s} | {self.imgsz} | - | {t_onnx[0]:.1f}±{t_onnx[1]:.1f} ms | {t_engine[0]:.1f}±"
|
645
|
+
f"{t_engine[1]:.1f} ms | {params / 1e6:.1f} | {flops:.1f} |"
|
646
|
+
)
|
647
|
+
|
648
|
+
@staticmethod
|
649
|
+
def generate_results_dict(model_name, t_onnx, t_engine, model_info):
|
650
|
+
"""
|
651
|
+
Generate a dictionary of profiling results.
|
652
|
+
|
653
|
+
Args:
|
654
|
+
model_name (str): Name of the model.
|
655
|
+
t_onnx (tuple): ONNX model inference time statistics (mean, std).
|
656
|
+
t_engine (tuple): TensorRT engine inference time statistics (mean, std).
|
657
|
+
model_info (tuple): Model information (layers, params, gradients, flops).
|
658
|
+
|
659
|
+
Returns:
|
660
|
+
(dict): Dictionary containing profiling results.
|
661
|
+
"""
|
662
|
+
layers, params, gradients, flops = model_info
|
663
|
+
return {
|
664
|
+
"model/name": model_name,
|
665
|
+
"model/parameters": params,
|
666
|
+
"model/GFLOPs": round(flops, 3),
|
667
|
+
"model/speed_ONNX(ms)": round(t_onnx[0], 3),
|
668
|
+
"model/speed_TensorRT(ms)": round(t_engine[0], 3),
|
669
|
+
}
|
670
|
+
|
671
|
+
@staticmethod
|
672
|
+
def print_table(table_rows):
|
673
|
+
"""
|
674
|
+
Print a formatted table of model profiling results.
|
675
|
+
|
676
|
+
Args:
|
677
|
+
table_rows (List[str]): List of formatted table row strings.
|
678
|
+
"""
|
679
|
+
gpu = torch.cuda.get_device_name(0) if torch.cuda.is_available() else "GPU"
|
680
|
+
headers = [
|
681
|
+
"Model",
|
682
|
+
"size<br><sup>(pixels)",
|
683
|
+
"mAP<sup>val<br>50-95",
|
684
|
+
f"Speed<br><sup>CPU ({get_cpu_info()}) ONNX<br>(ms)",
|
685
|
+
f"Speed<br><sup>{gpu} TensorRT<br>(ms)",
|
686
|
+
"params<br><sup>(M)",
|
687
|
+
"FLOPs<br><sup>(B)",
|
688
|
+
]
|
689
|
+
header = "|" + "|".join(f" {h} " for h in headers) + "|"
|
690
|
+
separator = "|" + "|".join("-" * (len(h) + 2) for h in headers) + "|"
|
691
|
+
|
692
|
+
LOGGER.info(f"\n\n{header}")
|
693
|
+
LOGGER.info(separator)
|
694
|
+
for row in table_rows:
|
695
|
+
LOGGER.info(row)
|