dgenerate-ultralytics-headless 8.3.214__py3-none-any.whl → 8.3.248__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.214.dist-info → dgenerate_ultralytics_headless-8.3.248.dist-info}/METADATA +13 -14
- dgenerate_ultralytics_headless-8.3.248.dist-info/RECORD +298 -0
- tests/__init__.py +5 -7
- tests/conftest.py +8 -15
- tests/test_cli.py +1 -1
- tests/test_cuda.py +5 -8
- tests/test_engine.py +1 -1
- tests/test_exports.py +57 -12
- tests/test_integrations.py +4 -4
- tests/test_python.py +84 -53
- tests/test_solutions.py +160 -151
- ultralytics/__init__.py +1 -1
- ultralytics/cfg/__init__.py +56 -62
- ultralytics/cfg/datasets/Argoverse.yaml +7 -6
- ultralytics/cfg/datasets/DOTAv1.5.yaml +1 -1
- ultralytics/cfg/datasets/DOTAv1.yaml +1 -1
- ultralytics/cfg/datasets/ImageNet.yaml +1 -1
- ultralytics/cfg/datasets/VOC.yaml +15 -16
- ultralytics/cfg/datasets/african-wildlife.yaml +1 -1
- ultralytics/cfg/datasets/coco-pose.yaml +21 -0
- ultralytics/cfg/datasets/coco128-seg.yaml +1 -1
- ultralytics/cfg/datasets/coco8-pose.yaml +21 -0
- ultralytics/cfg/datasets/dog-pose.yaml +28 -0
- ultralytics/cfg/datasets/dota8-multispectral.yaml +1 -1
- ultralytics/cfg/datasets/dota8.yaml +2 -2
- ultralytics/cfg/datasets/hand-keypoints.yaml +26 -2
- ultralytics/cfg/datasets/kitti.yaml +27 -0
- ultralytics/cfg/datasets/lvis.yaml +5 -5
- ultralytics/cfg/datasets/open-images-v7.yaml +1 -1
- ultralytics/cfg/datasets/tiger-pose.yaml +16 -0
- ultralytics/cfg/datasets/xView.yaml +16 -16
- ultralytics/cfg/default.yaml +1 -1
- ultralytics/cfg/models/11/yolo11-pose.yaml +1 -1
- ultralytics/cfg/models/11/yoloe-11-seg.yaml +2 -2
- ultralytics/cfg/models/11/yoloe-11.yaml +2 -2
- ultralytics/cfg/models/rt-detr/rtdetr-l.yaml +1 -1
- ultralytics/cfg/models/rt-detr/rtdetr-resnet101.yaml +1 -1
- ultralytics/cfg/models/rt-detr/rtdetr-resnet50.yaml +1 -1
- ultralytics/cfg/models/rt-detr/rtdetr-x.yaml +1 -1
- ultralytics/cfg/models/v10/yolov10b.yaml +2 -2
- ultralytics/cfg/models/v10/yolov10l.yaml +2 -2
- ultralytics/cfg/models/v10/yolov10m.yaml +2 -2
- ultralytics/cfg/models/v10/yolov10n.yaml +2 -2
- ultralytics/cfg/models/v10/yolov10s.yaml +2 -2
- ultralytics/cfg/models/v10/yolov10x.yaml +2 -2
- ultralytics/cfg/models/v3/yolov3-tiny.yaml +1 -1
- ultralytics/cfg/models/v6/yolov6.yaml +1 -1
- ultralytics/cfg/models/v8/yoloe-v8-seg.yaml +9 -6
- ultralytics/cfg/models/v8/yoloe-v8.yaml +9 -6
- ultralytics/cfg/models/v8/yolov8-cls-resnet101.yaml +1 -1
- ultralytics/cfg/models/v8/yolov8-cls-resnet50.yaml +1 -1
- ultralytics/cfg/models/v8/yolov8-ghost-p2.yaml +2 -2
- ultralytics/cfg/models/v8/yolov8-ghost-p6.yaml +2 -2
- ultralytics/cfg/models/v8/yolov8-ghost.yaml +2 -2
- ultralytics/cfg/models/v8/yolov8-obb.yaml +1 -1
- ultralytics/cfg/models/v8/yolov8-p2.yaml +1 -1
- ultralytics/cfg/models/v8/yolov8-pose-p6.yaml +1 -1
- ultralytics/cfg/models/v8/yolov8-rtdetr.yaml +1 -1
- ultralytics/cfg/models/v8/yolov8-seg-p6.yaml +1 -1
- ultralytics/cfg/models/v8/yolov8-world.yaml +1 -1
- ultralytics/cfg/models/v8/yolov8-worldv2.yaml +6 -6
- ultralytics/cfg/models/v9/yolov9s.yaml +1 -1
- ultralytics/data/__init__.py +4 -4
- ultralytics/data/annotator.py +3 -4
- ultralytics/data/augment.py +285 -475
- ultralytics/data/base.py +18 -26
- ultralytics/data/build.py +147 -25
- ultralytics/data/converter.py +36 -46
- ultralytics/data/dataset.py +46 -74
- ultralytics/data/loaders.py +42 -49
- ultralytics/data/split.py +5 -6
- ultralytics/data/split_dota.py +8 -15
- ultralytics/data/utils.py +34 -43
- ultralytics/engine/exporter.py +319 -237
- ultralytics/engine/model.py +148 -188
- ultralytics/engine/predictor.py +29 -38
- ultralytics/engine/results.py +177 -311
- ultralytics/engine/trainer.py +83 -59
- ultralytics/engine/tuner.py +23 -34
- ultralytics/engine/validator.py +39 -22
- ultralytics/hub/__init__.py +16 -19
- ultralytics/hub/auth.py +6 -12
- ultralytics/hub/google/__init__.py +7 -10
- ultralytics/hub/session.py +15 -25
- ultralytics/hub/utils.py +5 -8
- ultralytics/models/__init__.py +1 -1
- ultralytics/models/fastsam/__init__.py +1 -1
- ultralytics/models/fastsam/model.py +8 -10
- ultralytics/models/fastsam/predict.py +17 -29
- ultralytics/models/fastsam/utils.py +1 -2
- ultralytics/models/fastsam/val.py +5 -7
- ultralytics/models/nas/__init__.py +1 -1
- ultralytics/models/nas/model.py +5 -8
- ultralytics/models/nas/predict.py +7 -9
- ultralytics/models/nas/val.py +1 -2
- ultralytics/models/rtdetr/__init__.py +1 -1
- ultralytics/models/rtdetr/model.py +5 -8
- ultralytics/models/rtdetr/predict.py +15 -19
- ultralytics/models/rtdetr/train.py +10 -13
- ultralytics/models/rtdetr/val.py +21 -23
- ultralytics/models/sam/__init__.py +15 -2
- ultralytics/models/sam/amg.py +14 -20
- ultralytics/models/sam/build.py +26 -19
- ultralytics/models/sam/build_sam3.py +377 -0
- ultralytics/models/sam/model.py +29 -32
- ultralytics/models/sam/modules/blocks.py +83 -144
- ultralytics/models/sam/modules/decoders.py +19 -37
- ultralytics/models/sam/modules/encoders.py +44 -101
- ultralytics/models/sam/modules/memory_attention.py +16 -30
- ultralytics/models/sam/modules/sam.py +200 -73
- ultralytics/models/sam/modules/tiny_encoder.py +64 -83
- ultralytics/models/sam/modules/transformer.py +18 -28
- ultralytics/models/sam/modules/utils.py +174 -50
- ultralytics/models/sam/predict.py +2248 -350
- ultralytics/models/sam/sam3/__init__.py +3 -0
- ultralytics/models/sam/sam3/decoder.py +546 -0
- ultralytics/models/sam/sam3/encoder.py +529 -0
- ultralytics/models/sam/sam3/geometry_encoders.py +415 -0
- ultralytics/models/sam/sam3/maskformer_segmentation.py +286 -0
- ultralytics/models/sam/sam3/model_misc.py +199 -0
- ultralytics/models/sam/sam3/necks.py +129 -0
- ultralytics/models/sam/sam3/sam3_image.py +339 -0
- ultralytics/models/sam/sam3/text_encoder_ve.py +307 -0
- ultralytics/models/sam/sam3/vitdet.py +547 -0
- ultralytics/models/sam/sam3/vl_combiner.py +160 -0
- ultralytics/models/utils/loss.py +14 -26
- ultralytics/models/utils/ops.py +13 -17
- ultralytics/models/yolo/__init__.py +1 -1
- ultralytics/models/yolo/classify/predict.py +9 -12
- ultralytics/models/yolo/classify/train.py +11 -32
- ultralytics/models/yolo/classify/val.py +29 -28
- ultralytics/models/yolo/detect/predict.py +7 -10
- ultralytics/models/yolo/detect/train.py +11 -20
- ultralytics/models/yolo/detect/val.py +70 -58
- ultralytics/models/yolo/model.py +36 -53
- ultralytics/models/yolo/obb/predict.py +5 -14
- ultralytics/models/yolo/obb/train.py +11 -14
- ultralytics/models/yolo/obb/val.py +39 -36
- ultralytics/models/yolo/pose/__init__.py +1 -1
- ultralytics/models/yolo/pose/predict.py +6 -21
- ultralytics/models/yolo/pose/train.py +10 -15
- ultralytics/models/yolo/pose/val.py +38 -57
- ultralytics/models/yolo/segment/predict.py +14 -18
- ultralytics/models/yolo/segment/train.py +3 -6
- ultralytics/models/yolo/segment/val.py +93 -45
- ultralytics/models/yolo/world/train.py +8 -14
- ultralytics/models/yolo/world/train_world.py +11 -34
- ultralytics/models/yolo/yoloe/__init__.py +7 -7
- ultralytics/models/yolo/yoloe/predict.py +16 -23
- ultralytics/models/yolo/yoloe/train.py +30 -43
- ultralytics/models/yolo/yoloe/train_seg.py +5 -10
- ultralytics/models/yolo/yoloe/val.py +15 -20
- ultralytics/nn/__init__.py +7 -7
- ultralytics/nn/autobackend.py +145 -77
- ultralytics/nn/modules/__init__.py +60 -60
- ultralytics/nn/modules/activation.py +4 -6
- ultralytics/nn/modules/block.py +132 -216
- ultralytics/nn/modules/conv.py +52 -97
- ultralytics/nn/modules/head.py +50 -103
- ultralytics/nn/modules/transformer.py +76 -88
- ultralytics/nn/modules/utils.py +16 -21
- ultralytics/nn/tasks.py +94 -154
- ultralytics/nn/text_model.py +40 -67
- ultralytics/solutions/__init__.py +12 -12
- ultralytics/solutions/ai_gym.py +11 -17
- ultralytics/solutions/analytics.py +15 -16
- ultralytics/solutions/config.py +5 -6
- ultralytics/solutions/distance_calculation.py +10 -13
- ultralytics/solutions/heatmap.py +7 -13
- ultralytics/solutions/instance_segmentation.py +5 -8
- ultralytics/solutions/object_blurrer.py +7 -10
- ultralytics/solutions/object_counter.py +12 -19
- ultralytics/solutions/object_cropper.py +8 -14
- ultralytics/solutions/parking_management.py +33 -31
- ultralytics/solutions/queue_management.py +10 -12
- ultralytics/solutions/region_counter.py +9 -12
- ultralytics/solutions/security_alarm.py +15 -20
- ultralytics/solutions/similarity_search.py +10 -15
- ultralytics/solutions/solutions.py +75 -74
- ultralytics/solutions/speed_estimation.py +7 -10
- ultralytics/solutions/streamlit_inference.py +2 -4
- ultralytics/solutions/templates/similarity-search.html +7 -18
- ultralytics/solutions/trackzone.py +7 -10
- ultralytics/solutions/vision_eye.py +5 -8
- ultralytics/trackers/__init__.py +1 -1
- ultralytics/trackers/basetrack.py +3 -5
- ultralytics/trackers/bot_sort.py +10 -27
- ultralytics/trackers/byte_tracker.py +14 -30
- ultralytics/trackers/track.py +3 -6
- ultralytics/trackers/utils/gmc.py +11 -22
- ultralytics/trackers/utils/kalman_filter.py +37 -48
- ultralytics/trackers/utils/matching.py +12 -15
- ultralytics/utils/__init__.py +116 -116
- ultralytics/utils/autobatch.py +2 -4
- ultralytics/utils/autodevice.py +17 -18
- ultralytics/utils/benchmarks.py +32 -46
- ultralytics/utils/callbacks/base.py +8 -10
- ultralytics/utils/callbacks/clearml.py +5 -13
- ultralytics/utils/callbacks/comet.py +32 -46
- ultralytics/utils/callbacks/dvc.py +13 -18
- ultralytics/utils/callbacks/mlflow.py +4 -5
- ultralytics/utils/callbacks/neptune.py +7 -15
- ultralytics/utils/callbacks/platform.py +314 -38
- ultralytics/utils/callbacks/raytune.py +3 -4
- ultralytics/utils/callbacks/tensorboard.py +23 -31
- ultralytics/utils/callbacks/wb.py +10 -13
- ultralytics/utils/checks.py +99 -76
- ultralytics/utils/cpu.py +3 -8
- ultralytics/utils/dist.py +8 -12
- ultralytics/utils/downloads.py +20 -30
- ultralytics/utils/errors.py +6 -14
- ultralytics/utils/events.py +2 -4
- ultralytics/utils/export/__init__.py +4 -236
- ultralytics/utils/export/engine.py +237 -0
- ultralytics/utils/export/imx.py +91 -55
- ultralytics/utils/export/tensorflow.py +231 -0
- ultralytics/utils/files.py +24 -28
- ultralytics/utils/git.py +9 -11
- ultralytics/utils/instance.py +30 -51
- ultralytics/utils/logger.py +212 -114
- ultralytics/utils/loss.py +14 -22
- ultralytics/utils/metrics.py +126 -155
- ultralytics/utils/nms.py +13 -16
- ultralytics/utils/ops.py +107 -165
- ultralytics/utils/patches.py +33 -21
- ultralytics/utils/plotting.py +72 -80
- ultralytics/utils/tal.py +25 -39
- ultralytics/utils/torch_utils.py +52 -78
- ultralytics/utils/tqdm.py +20 -20
- ultralytics/utils/triton.py +13 -19
- ultralytics/utils/tuner.py +17 -5
- dgenerate_ultralytics_headless-8.3.214.dist-info/RECORD +0 -283
- {dgenerate_ultralytics_headless-8.3.214.dist-info → dgenerate_ultralytics_headless-8.3.248.dist-info}/WHEEL +0 -0
- {dgenerate_ultralytics_headless-8.3.214.dist-info → dgenerate_ultralytics_headless-8.3.248.dist-info}/entry_points.txt +0 -0
- {dgenerate_ultralytics_headless-8.3.214.dist-info → dgenerate_ultralytics_headless-8.3.248.dist-info}/licenses/LICENSE +0 -0
- {dgenerate_ultralytics_headless-8.3.214.dist-info → dgenerate_ultralytics_headless-8.3.248.dist-info}/top_level.txt +0 -0
ultralytics/utils/downloads.py
CHANGED
|
@@ -43,8 +43,7 @@ GITHUB_ASSETS_STEMS = frozenset(k.rpartition(".")[0] for k in GITHUB_ASSETS_NAME
|
|
|
43
43
|
|
|
44
44
|
|
|
45
45
|
def is_url(url: str | Path, check: bool = False) -> bool:
|
|
46
|
-
"""
|
|
47
|
-
Validate if the given string is a URL and optionally check if the URL exists online.
|
|
46
|
+
"""Validate if the given string is a URL and optionally check if the URL exists online.
|
|
48
47
|
|
|
49
48
|
Args:
|
|
50
49
|
url (str): The string to be validated as a URL.
|
|
@@ -71,8 +70,7 @@ def is_url(url: str | Path, check: bool = False) -> bool:
|
|
|
71
70
|
|
|
72
71
|
|
|
73
72
|
def delete_dsstore(path: str | Path, files_to_delete: tuple[str, ...] = (".DS_Store", "__MACOSX")) -> None:
|
|
74
|
-
"""
|
|
75
|
-
Delete all specified system files in a directory.
|
|
73
|
+
"""Delete all specified system files in a directory.
|
|
76
74
|
|
|
77
75
|
Args:
|
|
78
76
|
path (str | Path): The directory path where the files should be deleted.
|
|
@@ -83,7 +81,7 @@ def delete_dsstore(path: str | Path, files_to_delete: tuple[str, ...] = (".DS_St
|
|
|
83
81
|
>>> delete_dsstore("path/to/dir")
|
|
84
82
|
|
|
85
83
|
Notes:
|
|
86
|
-
".
|
|
84
|
+
".DS_Store" files are created by the Apple operating system and contain metadata about folders and files. They
|
|
87
85
|
are hidden system files and can cause issues when transferring files between different operating systems.
|
|
88
86
|
"""
|
|
89
87
|
for file in files_to_delete:
|
|
@@ -99,8 +97,7 @@ def zip_directory(
|
|
|
99
97
|
exclude: tuple[str, ...] = (".DS_Store", "__MACOSX"),
|
|
100
98
|
progress: bool = True,
|
|
101
99
|
) -> Path:
|
|
102
|
-
"""
|
|
103
|
-
Zip the contents of a directory, excluding specified files.
|
|
100
|
+
"""Zip the contents of a directory, excluding specified files.
|
|
104
101
|
|
|
105
102
|
The resulting zip file is named after the directory and placed alongside it.
|
|
106
103
|
|
|
@@ -142,12 +139,11 @@ def unzip_file(
|
|
|
142
139
|
exist_ok: bool = False,
|
|
143
140
|
progress: bool = True,
|
|
144
141
|
) -> Path:
|
|
145
|
-
"""
|
|
146
|
-
Unzip a *.zip file to the specified path, excluding specified files.
|
|
142
|
+
"""Unzip a *.zip file to the specified path, excluding specified files.
|
|
147
143
|
|
|
148
|
-
If the zipfile does not contain a single top-level directory, the function will create a new
|
|
149
|
-
|
|
150
|
-
|
|
144
|
+
If the zipfile does not contain a single top-level directory, the function will create a new directory with the same
|
|
145
|
+
name as the zipfile (without the extension) to extract its contents. If a path is not provided, the function will
|
|
146
|
+
use the parent directory of the zipfile as the default path.
|
|
151
147
|
|
|
152
148
|
Args:
|
|
153
149
|
file (str | Path): The path to the zipfile to be extracted.
|
|
@@ -183,7 +179,7 @@ def unzip_file(
|
|
|
183
179
|
if unzip_as_dir:
|
|
184
180
|
# Zip has 1 top-level directory
|
|
185
181
|
extract_path = path # i.e. ../datasets
|
|
186
|
-
path = Path(path) /
|
|
182
|
+
path = Path(path) / next(iter(top_level_dirs)) # i.e. extract coco8/ dir to ../datasets/
|
|
187
183
|
else:
|
|
188
184
|
# Zip has multiple files at top level
|
|
189
185
|
path = extract_path = Path(path) / Path(file).stem # i.e. extract multiple files to ../datasets/coco8/
|
|
@@ -210,8 +206,7 @@ def check_disk_space(
|
|
|
210
206
|
sf: float = 1.5,
|
|
211
207
|
hard: bool = True,
|
|
212
208
|
) -> bool:
|
|
213
|
-
"""
|
|
214
|
-
Check if there is sufficient disk space to download and store a file.
|
|
209
|
+
"""Check if there is sufficient disk space to download and store a file.
|
|
215
210
|
|
|
216
211
|
Args:
|
|
217
212
|
file_bytes (int): The file size in bytes.
|
|
@@ -222,7 +217,7 @@ def check_disk_space(
|
|
|
222
217
|
Returns:
|
|
223
218
|
(bool): True if there is sufficient disk space, False otherwise.
|
|
224
219
|
"""
|
|
225
|
-
|
|
220
|
+
_total, _used, free = shutil.disk_usage(path) # bytes
|
|
226
221
|
if file_bytes * sf < free:
|
|
227
222
|
return True # sufficient space
|
|
228
223
|
|
|
@@ -238,8 +233,7 @@ def check_disk_space(
|
|
|
238
233
|
|
|
239
234
|
|
|
240
235
|
def get_google_drive_file_info(link: str) -> tuple[str, str | None]:
|
|
241
|
-
"""
|
|
242
|
-
Retrieve the direct download link and filename for a shareable Google Drive file link.
|
|
236
|
+
"""Retrieve the direct download link and filename for a shareable Google Drive file link.
|
|
243
237
|
|
|
244
238
|
Args:
|
|
245
239
|
link (str): The shareable link of the Google Drive file.
|
|
@@ -289,16 +283,15 @@ def safe_download(
|
|
|
289
283
|
exist_ok: bool = False,
|
|
290
284
|
progress: bool = True,
|
|
291
285
|
) -> Path | str:
|
|
292
|
-
"""
|
|
293
|
-
Download files from a URL with options for retrying, unzipping, and deleting the downloaded file. Enhanced with
|
|
286
|
+
"""Download files from a URL with options for retrying, unzipping, and deleting the downloaded file. Enhanced with
|
|
294
287
|
robust partial download detection using Content-Length validation.
|
|
295
288
|
|
|
296
289
|
Args:
|
|
297
290
|
url (str): The URL of the file to be downloaded.
|
|
298
|
-
file (str, optional): The filename of the downloaded file.
|
|
299
|
-
|
|
300
|
-
dir (str | Path, optional): The directory to save the downloaded file.
|
|
301
|
-
|
|
291
|
+
file (str, optional): The filename of the downloaded file. If not provided, the file will be saved with the same
|
|
292
|
+
name as the URL.
|
|
293
|
+
dir (str | Path, optional): The directory to save the downloaded file. If not provided, the file will be saved
|
|
294
|
+
in the current working directory.
|
|
302
295
|
unzip (bool, optional): Whether to unzip the downloaded file.
|
|
303
296
|
delete (bool, optional): Whether to delete the downloaded file after unzipping.
|
|
304
297
|
curl (bool, optional): Whether to use curl command line tool for downloading.
|
|
@@ -397,8 +390,7 @@ def get_github_assets(
|
|
|
397
390
|
version: str = "latest",
|
|
398
391
|
retry: bool = False,
|
|
399
392
|
) -> tuple[str, list[str]]:
|
|
400
|
-
"""
|
|
401
|
-
Retrieve the specified version's tag and assets from a GitHub repository.
|
|
393
|
+
"""Retrieve the specified version's tag and assets from a GitHub repository.
|
|
402
394
|
|
|
403
395
|
If the version is not specified, the function fetches the latest release assets.
|
|
404
396
|
|
|
@@ -435,8 +427,7 @@ def attempt_download_asset(
|
|
|
435
427
|
release: str = "v8.3.0",
|
|
436
428
|
**kwargs,
|
|
437
429
|
) -> str:
|
|
438
|
-
"""
|
|
439
|
-
Attempt to download a file from GitHub release assets if it is not found locally.
|
|
430
|
+
"""Attempt to download a file from GitHub release assets if it is not found locally.
|
|
440
431
|
|
|
441
432
|
Args:
|
|
442
433
|
file (str | Path): The filename or file path to be downloaded.
|
|
@@ -495,8 +486,7 @@ def download(
|
|
|
495
486
|
retry: int = 3,
|
|
496
487
|
exist_ok: bool = False,
|
|
497
488
|
) -> None:
|
|
498
|
-
"""
|
|
499
|
-
Download files from specified URLs to a given directory.
|
|
489
|
+
"""Download files from specified URLs to a given directory.
|
|
500
490
|
|
|
501
491
|
Supports concurrent downloads if multiple threads are specified.
|
|
502
492
|
|
ultralytics/utils/errors.py
CHANGED
|
@@ -4,11 +4,10 @@ from ultralytics.utils import emojis
|
|
|
4
4
|
|
|
5
5
|
|
|
6
6
|
class HUBModelError(Exception):
|
|
7
|
-
"""
|
|
8
|
-
Exception raised when a model cannot be found or retrieved from Ultralytics HUB.
|
|
7
|
+
"""Exception raised when a model cannot be found or retrieved from Ultralytics HUB.
|
|
9
8
|
|
|
10
|
-
This custom exception is used specifically for handling errors related to model fetching in Ultralytics YOLO.
|
|
11
|
-
|
|
9
|
+
This custom exception is used specifically for handling errors related to model fetching in Ultralytics YOLO. The
|
|
10
|
+
error message is processed to include emojis for better user experience.
|
|
12
11
|
|
|
13
12
|
Attributes:
|
|
14
13
|
message (str): The error message displayed when the exception is raised.
|
|
@@ -25,19 +24,12 @@ class HUBModelError(Exception):
|
|
|
25
24
|
"""
|
|
26
25
|
|
|
27
26
|
def __init__(self, message: str = "Model not found. Please check model URL and try again."):
|
|
28
|
-
"""
|
|
29
|
-
Initialize a HUBModelError exception.
|
|
27
|
+
"""Initialize a HUBModelError exception.
|
|
30
28
|
|
|
31
|
-
This exception is raised when a requested model is not found or cannot be retrieved from Ultralytics HUB.
|
|
32
|
-
|
|
29
|
+
This exception is raised when a requested model is not found or cannot be retrieved from Ultralytics HUB. The
|
|
30
|
+
message is processed to include emojis for better user experience.
|
|
33
31
|
|
|
34
32
|
Args:
|
|
35
33
|
message (str, optional): The error message to display when the exception is raised.
|
|
36
|
-
|
|
37
|
-
Examples:
|
|
38
|
-
>>> try:
|
|
39
|
-
... raise HUBModelError("Custom model error message")
|
|
40
|
-
... except HUBModelError as e:
|
|
41
|
-
... print(e)
|
|
42
34
|
"""
|
|
43
35
|
super().__init__(emojis(message))
|
ultralytics/utils/events.py
CHANGED
|
@@ -24,8 +24,7 @@ def _post(url: str, data: dict, timeout: float = 5.0) -> None:
|
|
|
24
24
|
|
|
25
25
|
|
|
26
26
|
class Events:
|
|
27
|
-
"""
|
|
28
|
-
Collect and send anonymous usage analytics with rate-limiting.
|
|
27
|
+
"""Collect and send anonymous usage analytics with rate-limiting.
|
|
29
28
|
|
|
30
29
|
Event collection and transmission are enabled when sync is enabled in settings, the current process is rank -1 or 0,
|
|
31
30
|
tests are not running, the environment is online, and the installation source is either pip or the official
|
|
@@ -71,8 +70,7 @@ class Events:
|
|
|
71
70
|
)
|
|
72
71
|
|
|
73
72
|
def __call__(self, cfg, device=None) -> None:
|
|
74
|
-
"""
|
|
75
|
-
Queue an event and flush the queue asynchronously when the rate limit elapses.
|
|
73
|
+
"""Queue an event and flush the queue asynchronously when the rate limit elapses.
|
|
76
74
|
|
|
77
75
|
Args:
|
|
78
76
|
cfg (IterableSimpleNamespace): The configuration object containing mode and task information.
|
|
@@ -1,239 +1,7 @@
|
|
|
1
1
|
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
|
2
2
|
|
|
3
|
-
from
|
|
3
|
+
from .engine import onnx2engine, torch2onnx
|
|
4
|
+
from .imx import torch2imx
|
|
5
|
+
from .tensorflow import keras2pb, onnx2saved_model, pb2tfjs, tflite2edgetpu
|
|
4
6
|
|
|
5
|
-
|
|
6
|
-
from pathlib import Path
|
|
7
|
-
|
|
8
|
-
import torch
|
|
9
|
-
|
|
10
|
-
from ultralytics.utils import IS_JETSON, LOGGER
|
|
11
|
-
|
|
12
|
-
from .imx import torch2imx # noqa
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
def torch2onnx(
|
|
16
|
-
torch_model: torch.nn.Module,
|
|
17
|
-
im: torch.Tensor,
|
|
18
|
-
onnx_file: str,
|
|
19
|
-
opset: int = 14,
|
|
20
|
-
input_names: list[str] = ["images"],
|
|
21
|
-
output_names: list[str] = ["output0"],
|
|
22
|
-
dynamic: bool | dict = False,
|
|
23
|
-
) -> None:
|
|
24
|
-
"""
|
|
25
|
-
Export a PyTorch model to ONNX format.
|
|
26
|
-
|
|
27
|
-
Args:
|
|
28
|
-
torch_model (torch.nn.Module): The PyTorch model to export.
|
|
29
|
-
im (torch.Tensor): Example input tensor for the model.
|
|
30
|
-
onnx_file (str): Path to save the exported ONNX file.
|
|
31
|
-
opset (int): ONNX opset version to use for export.
|
|
32
|
-
input_names (list[str]): List of input tensor names.
|
|
33
|
-
output_names (list[str]): List of output tensor names.
|
|
34
|
-
dynamic (bool | dict, optional): Whether to enable dynamic axes.
|
|
35
|
-
|
|
36
|
-
Notes:
|
|
37
|
-
Setting `do_constant_folding=True` may cause issues with DNN inference for torch>=1.12.
|
|
38
|
-
"""
|
|
39
|
-
torch.onnx.export(
|
|
40
|
-
torch_model,
|
|
41
|
-
im,
|
|
42
|
-
onnx_file,
|
|
43
|
-
verbose=False,
|
|
44
|
-
opset_version=opset,
|
|
45
|
-
do_constant_folding=True, # WARNING: DNN inference with torch>=1.12 may require do_constant_folding=False
|
|
46
|
-
input_names=input_names,
|
|
47
|
-
output_names=output_names,
|
|
48
|
-
dynamic_axes=dynamic or None,
|
|
49
|
-
)
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
def onnx2engine(
|
|
53
|
-
onnx_file: str,
|
|
54
|
-
engine_file: str | None = None,
|
|
55
|
-
workspace: int | None = None,
|
|
56
|
-
half: bool = False,
|
|
57
|
-
int8: bool = False,
|
|
58
|
-
dynamic: bool = False,
|
|
59
|
-
shape: tuple[int, int, int, int] = (1, 3, 640, 640),
|
|
60
|
-
dla: int | None = None,
|
|
61
|
-
dataset=None,
|
|
62
|
-
metadata: dict | None = None,
|
|
63
|
-
verbose: bool = False,
|
|
64
|
-
prefix: str = "",
|
|
65
|
-
) -> None:
|
|
66
|
-
"""
|
|
67
|
-
Export a YOLO model to TensorRT engine format.
|
|
68
|
-
|
|
69
|
-
Args:
|
|
70
|
-
onnx_file (str): Path to the ONNX file to be converted.
|
|
71
|
-
engine_file (str, optional): Path to save the generated TensorRT engine file.
|
|
72
|
-
workspace (int, optional): Workspace size in GB for TensorRT.
|
|
73
|
-
half (bool, optional): Enable FP16 precision.
|
|
74
|
-
int8 (bool, optional): Enable INT8 precision.
|
|
75
|
-
dynamic (bool, optional): Enable dynamic input shapes.
|
|
76
|
-
shape (tuple[int, int, int, int], optional): Input shape (batch, channels, height, width).
|
|
77
|
-
dla (int, optional): DLA core to use (Jetson devices only).
|
|
78
|
-
dataset (ultralytics.data.build.InfiniteDataLoader, optional): Dataset for INT8 calibration.
|
|
79
|
-
metadata (dict, optional): Metadata to include in the engine file.
|
|
80
|
-
verbose (bool, optional): Enable verbose logging.
|
|
81
|
-
prefix (str, optional): Prefix for log messages.
|
|
82
|
-
|
|
83
|
-
Raises:
|
|
84
|
-
ValueError: If DLA is enabled on non-Jetson devices or required precision is not set.
|
|
85
|
-
RuntimeError: If the ONNX file cannot be parsed.
|
|
86
|
-
|
|
87
|
-
Notes:
|
|
88
|
-
TensorRT version compatibility is handled for workspace size and engine building.
|
|
89
|
-
INT8 calibration requires a dataset and generates a calibration cache.
|
|
90
|
-
Metadata is serialized and written to the engine file if provided.
|
|
91
|
-
"""
|
|
92
|
-
import tensorrt as trt # noqa
|
|
93
|
-
|
|
94
|
-
engine_file = engine_file or Path(onnx_file).with_suffix(".engine")
|
|
95
|
-
|
|
96
|
-
logger = trt.Logger(trt.Logger.INFO)
|
|
97
|
-
if verbose:
|
|
98
|
-
logger.min_severity = trt.Logger.Severity.VERBOSE
|
|
99
|
-
|
|
100
|
-
# Engine builder
|
|
101
|
-
builder = trt.Builder(logger)
|
|
102
|
-
config = builder.create_builder_config()
|
|
103
|
-
workspace_bytes = int((workspace or 0) * (1 << 30))
|
|
104
|
-
is_trt10 = int(trt.__version__.split(".", 1)[0]) >= 10 # is TensorRT >= 10
|
|
105
|
-
if is_trt10 and workspace_bytes > 0:
|
|
106
|
-
config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, workspace_bytes)
|
|
107
|
-
elif workspace_bytes > 0: # TensorRT versions 7, 8
|
|
108
|
-
config.max_workspace_size = workspace_bytes
|
|
109
|
-
flag = 1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)
|
|
110
|
-
network = builder.create_network(flag)
|
|
111
|
-
half = builder.platform_has_fast_fp16 and half
|
|
112
|
-
int8 = builder.platform_has_fast_int8 and int8
|
|
113
|
-
|
|
114
|
-
# Optionally switch to DLA if enabled
|
|
115
|
-
if dla is not None:
|
|
116
|
-
if not IS_JETSON:
|
|
117
|
-
raise ValueError("DLA is only available on NVIDIA Jetson devices")
|
|
118
|
-
LOGGER.info(f"{prefix} enabling DLA on core {dla}...")
|
|
119
|
-
if not half and not int8:
|
|
120
|
-
raise ValueError(
|
|
121
|
-
"DLA requires either 'half=True' (FP16) or 'int8=True' (INT8) to be enabled. Please enable one of them and try again."
|
|
122
|
-
)
|
|
123
|
-
config.default_device_type = trt.DeviceType.DLA
|
|
124
|
-
config.DLA_core = int(dla)
|
|
125
|
-
config.set_flag(trt.BuilderFlag.GPU_FALLBACK)
|
|
126
|
-
|
|
127
|
-
# Read ONNX file
|
|
128
|
-
parser = trt.OnnxParser(network, logger)
|
|
129
|
-
if not parser.parse_from_file(onnx_file):
|
|
130
|
-
raise RuntimeError(f"failed to load ONNX file: {onnx_file}")
|
|
131
|
-
|
|
132
|
-
# Network inputs
|
|
133
|
-
inputs = [network.get_input(i) for i in range(network.num_inputs)]
|
|
134
|
-
outputs = [network.get_output(i) for i in range(network.num_outputs)]
|
|
135
|
-
for inp in inputs:
|
|
136
|
-
LOGGER.info(f'{prefix} input "{inp.name}" with shape{inp.shape} {inp.dtype}')
|
|
137
|
-
for out in outputs:
|
|
138
|
-
LOGGER.info(f'{prefix} output "{out.name}" with shape{out.shape} {out.dtype}')
|
|
139
|
-
|
|
140
|
-
if dynamic:
|
|
141
|
-
profile = builder.create_optimization_profile()
|
|
142
|
-
min_shape = (1, shape[1], 32, 32) # minimum input shape
|
|
143
|
-
max_shape = (*shape[:2], *(int(max(2, workspace or 2) * d) for d in shape[2:])) # max input shape
|
|
144
|
-
for inp in inputs:
|
|
145
|
-
profile.set_shape(inp.name, min=min_shape, opt=shape, max=max_shape)
|
|
146
|
-
config.add_optimization_profile(profile)
|
|
147
|
-
if int8:
|
|
148
|
-
config.set_calibration_profile(profile)
|
|
149
|
-
|
|
150
|
-
LOGGER.info(f"{prefix} building {'INT8' if int8 else 'FP' + ('16' if half else '32')} engine as {engine_file}")
|
|
151
|
-
if int8:
|
|
152
|
-
config.set_flag(trt.BuilderFlag.INT8)
|
|
153
|
-
config.profiling_verbosity = trt.ProfilingVerbosity.DETAILED
|
|
154
|
-
|
|
155
|
-
class EngineCalibrator(trt.IInt8Calibrator):
|
|
156
|
-
"""
|
|
157
|
-
Custom INT8 calibrator for TensorRT engine optimization.
|
|
158
|
-
|
|
159
|
-
This calibrator provides the necessary interface for TensorRT to perform INT8 quantization calibration
|
|
160
|
-
using a dataset. It handles batch generation, caching, and calibration algorithm selection.
|
|
161
|
-
|
|
162
|
-
Attributes:
|
|
163
|
-
dataset: Dataset for calibration.
|
|
164
|
-
data_iter: Iterator over the calibration dataset.
|
|
165
|
-
algo (trt.CalibrationAlgoType): Calibration algorithm type.
|
|
166
|
-
batch (int): Batch size for calibration.
|
|
167
|
-
cache (Path): Path to save the calibration cache.
|
|
168
|
-
|
|
169
|
-
Methods:
|
|
170
|
-
get_algorithm: Get the calibration algorithm to use.
|
|
171
|
-
get_batch_size: Get the batch size to use for calibration.
|
|
172
|
-
get_batch: Get the next batch to use for calibration.
|
|
173
|
-
read_calibration_cache: Use existing cache instead of calibrating again.
|
|
174
|
-
write_calibration_cache: Write calibration cache to disk.
|
|
175
|
-
"""
|
|
176
|
-
|
|
177
|
-
def __init__(
|
|
178
|
-
self,
|
|
179
|
-
dataset, # ultralytics.data.build.InfiniteDataLoader
|
|
180
|
-
cache: str = "",
|
|
181
|
-
) -> None:
|
|
182
|
-
"""Initialize the INT8 calibrator with dataset and cache path."""
|
|
183
|
-
trt.IInt8Calibrator.__init__(self)
|
|
184
|
-
self.dataset = dataset
|
|
185
|
-
self.data_iter = iter(dataset)
|
|
186
|
-
self.algo = (
|
|
187
|
-
trt.CalibrationAlgoType.ENTROPY_CALIBRATION_2 # DLA quantization needs ENTROPY_CALIBRATION_2
|
|
188
|
-
if dla is not None
|
|
189
|
-
else trt.CalibrationAlgoType.MINMAX_CALIBRATION
|
|
190
|
-
)
|
|
191
|
-
self.batch = dataset.batch_size
|
|
192
|
-
self.cache = Path(cache)
|
|
193
|
-
|
|
194
|
-
def get_algorithm(self) -> trt.CalibrationAlgoType:
|
|
195
|
-
"""Get the calibration algorithm to use."""
|
|
196
|
-
return self.algo
|
|
197
|
-
|
|
198
|
-
def get_batch_size(self) -> int:
|
|
199
|
-
"""Get the batch size to use for calibration."""
|
|
200
|
-
return self.batch or 1
|
|
201
|
-
|
|
202
|
-
def get_batch(self, names) -> list[int] | None:
|
|
203
|
-
"""Get the next batch to use for calibration, as a list of device memory pointers."""
|
|
204
|
-
try:
|
|
205
|
-
im0s = next(self.data_iter)["img"] / 255.0
|
|
206
|
-
im0s = im0s.to("cuda") if im0s.device.type == "cpu" else im0s
|
|
207
|
-
return [int(im0s.data_ptr())]
|
|
208
|
-
except StopIteration:
|
|
209
|
-
# Return None to signal to TensorRT there is no calibration data remaining
|
|
210
|
-
return None
|
|
211
|
-
|
|
212
|
-
def read_calibration_cache(self) -> bytes | None:
|
|
213
|
-
"""Use existing cache instead of calibrating again, otherwise, implicitly return None."""
|
|
214
|
-
if self.cache.exists() and self.cache.suffix == ".cache":
|
|
215
|
-
return self.cache.read_bytes()
|
|
216
|
-
|
|
217
|
-
def write_calibration_cache(self, cache: bytes) -> None:
|
|
218
|
-
"""Write calibration cache to disk."""
|
|
219
|
-
_ = self.cache.write_bytes(cache)
|
|
220
|
-
|
|
221
|
-
# Load dataset w/ builder (for batching) and calibrate
|
|
222
|
-
config.int8_calibrator = EngineCalibrator(
|
|
223
|
-
dataset=dataset,
|
|
224
|
-
cache=str(Path(onnx_file).with_suffix(".cache")),
|
|
225
|
-
)
|
|
226
|
-
|
|
227
|
-
elif half:
|
|
228
|
-
config.set_flag(trt.BuilderFlag.FP16)
|
|
229
|
-
|
|
230
|
-
# Write file
|
|
231
|
-
build = builder.build_serialized_network if is_trt10 else builder.build_engine
|
|
232
|
-
with build(network, config) as engine, open(engine_file, "wb") as t:
|
|
233
|
-
# Metadata
|
|
234
|
-
if metadata is not None:
|
|
235
|
-
meta = json.dumps(metadata)
|
|
236
|
-
t.write(len(meta).to_bytes(4, byteorder="little", signed=True))
|
|
237
|
-
t.write(meta.encode())
|
|
238
|
-
# Model
|
|
239
|
-
t.write(engine if is_trt10 else engine.serialize())
|
|
7
|
+
__all__ = ["keras2pb", "onnx2engine", "onnx2saved_model", "pb2tfjs", "tflite2edgetpu", "torch2imx", "torch2onnx"]
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
import torch
|
|
9
|
+
|
|
10
|
+
from ultralytics.utils import IS_JETSON, LOGGER
|
|
11
|
+
from ultralytics.utils.torch_utils import TORCH_2_4
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def torch2onnx(
|
|
15
|
+
torch_model: torch.nn.Module,
|
|
16
|
+
im: torch.Tensor,
|
|
17
|
+
onnx_file: str,
|
|
18
|
+
opset: int = 14,
|
|
19
|
+
input_names: list[str] = ["images"],
|
|
20
|
+
output_names: list[str] = ["output0"],
|
|
21
|
+
dynamic: bool | dict = False,
|
|
22
|
+
) -> None:
|
|
23
|
+
"""Export a PyTorch model to ONNX format.
|
|
24
|
+
|
|
25
|
+
Args:
|
|
26
|
+
torch_model (torch.nn.Module): The PyTorch model to export.
|
|
27
|
+
im (torch.Tensor): Example input tensor for the model.
|
|
28
|
+
onnx_file (str): Path to save the exported ONNX file.
|
|
29
|
+
opset (int): ONNX opset version to use for export.
|
|
30
|
+
input_names (list[str]): List of input tensor names.
|
|
31
|
+
output_names (list[str]): List of output tensor names.
|
|
32
|
+
dynamic (bool | dict, optional): Whether to enable dynamic axes.
|
|
33
|
+
|
|
34
|
+
Notes:
|
|
35
|
+
Setting `do_constant_folding=True` may cause issues with DNN inference for torch>=1.12.
|
|
36
|
+
"""
|
|
37
|
+
kwargs = {"dynamo": False} if TORCH_2_4 else {}
|
|
38
|
+
torch.onnx.export(
|
|
39
|
+
torch_model,
|
|
40
|
+
im,
|
|
41
|
+
onnx_file,
|
|
42
|
+
verbose=False,
|
|
43
|
+
opset_version=opset,
|
|
44
|
+
do_constant_folding=True, # WARNING: DNN inference with torch>=1.12 may require do_constant_folding=False
|
|
45
|
+
input_names=input_names,
|
|
46
|
+
output_names=output_names,
|
|
47
|
+
dynamic_axes=dynamic or None,
|
|
48
|
+
**kwargs,
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def onnx2engine(
|
|
53
|
+
onnx_file: str,
|
|
54
|
+
engine_file: str | None = None,
|
|
55
|
+
workspace: int | None = None,
|
|
56
|
+
half: bool = False,
|
|
57
|
+
int8: bool = False,
|
|
58
|
+
dynamic: bool = False,
|
|
59
|
+
shape: tuple[int, int, int, int] = (1, 3, 640, 640),
|
|
60
|
+
dla: int | None = None,
|
|
61
|
+
dataset=None,
|
|
62
|
+
metadata: dict | None = None,
|
|
63
|
+
verbose: bool = False,
|
|
64
|
+
prefix: str = "",
|
|
65
|
+
) -> None:
|
|
66
|
+
"""Export a YOLO model to TensorRT engine format.
|
|
67
|
+
|
|
68
|
+
Args:
|
|
69
|
+
onnx_file (str): Path to the ONNX file to be converted.
|
|
70
|
+
engine_file (str, optional): Path to save the generated TensorRT engine file.
|
|
71
|
+
workspace (int, optional): Workspace size in GB for TensorRT.
|
|
72
|
+
half (bool, optional): Enable FP16 precision.
|
|
73
|
+
int8 (bool, optional): Enable INT8 precision.
|
|
74
|
+
dynamic (bool, optional): Enable dynamic input shapes.
|
|
75
|
+
shape (tuple[int, int, int, int], optional): Input shape (batch, channels, height, width).
|
|
76
|
+
dla (int, optional): DLA core to use (Jetson devices only).
|
|
77
|
+
dataset (ultralytics.data.build.InfiniteDataLoader, optional): Dataset for INT8 calibration.
|
|
78
|
+
metadata (dict, optional): Metadata to include in the engine file.
|
|
79
|
+
verbose (bool, optional): Enable verbose logging.
|
|
80
|
+
prefix (str, optional): Prefix for log messages.
|
|
81
|
+
|
|
82
|
+
Raises:
|
|
83
|
+
ValueError: If DLA is enabled on non-Jetson devices or required precision is not set.
|
|
84
|
+
RuntimeError: If the ONNX file cannot be parsed.
|
|
85
|
+
|
|
86
|
+
Notes:
|
|
87
|
+
TensorRT version compatibility is handled for workspace size and engine building.
|
|
88
|
+
INT8 calibration requires a dataset and generates a calibration cache.
|
|
89
|
+
Metadata is serialized and written to the engine file if provided.
|
|
90
|
+
"""
|
|
91
|
+
import tensorrt as trt
|
|
92
|
+
|
|
93
|
+
engine_file = engine_file or Path(onnx_file).with_suffix(".engine")
|
|
94
|
+
|
|
95
|
+
logger = trt.Logger(trt.Logger.INFO)
|
|
96
|
+
if verbose:
|
|
97
|
+
logger.min_severity = trt.Logger.Severity.VERBOSE
|
|
98
|
+
|
|
99
|
+
# Engine builder
|
|
100
|
+
builder = trt.Builder(logger)
|
|
101
|
+
config = builder.create_builder_config()
|
|
102
|
+
workspace_bytes = int((workspace or 0) * (1 << 30))
|
|
103
|
+
is_trt10 = int(trt.__version__.split(".", 1)[0]) >= 10 # is TensorRT >= 10
|
|
104
|
+
if is_trt10 and workspace_bytes > 0:
|
|
105
|
+
config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, workspace_bytes)
|
|
106
|
+
elif workspace_bytes > 0: # TensorRT versions 7, 8
|
|
107
|
+
config.max_workspace_size = workspace_bytes
|
|
108
|
+
flag = 1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)
|
|
109
|
+
network = builder.create_network(flag)
|
|
110
|
+
half = builder.platform_has_fast_fp16 and half
|
|
111
|
+
int8 = builder.platform_has_fast_int8 and int8
|
|
112
|
+
|
|
113
|
+
# Optionally switch to DLA if enabled
|
|
114
|
+
if dla is not None:
|
|
115
|
+
if not IS_JETSON:
|
|
116
|
+
raise ValueError("DLA is only available on NVIDIA Jetson devices")
|
|
117
|
+
LOGGER.info(f"{prefix} enabling DLA on core {dla}...")
|
|
118
|
+
if not half and not int8:
|
|
119
|
+
raise ValueError(
|
|
120
|
+
"DLA requires either 'half=True' (FP16) or 'int8=True' (INT8) to be enabled. Please enable one of them and try again."
|
|
121
|
+
)
|
|
122
|
+
config.default_device_type = trt.DeviceType.DLA
|
|
123
|
+
config.DLA_core = int(dla)
|
|
124
|
+
config.set_flag(trt.BuilderFlag.GPU_FALLBACK)
|
|
125
|
+
|
|
126
|
+
# Read ONNX file
|
|
127
|
+
parser = trt.OnnxParser(network, logger)
|
|
128
|
+
if not parser.parse_from_file(onnx_file):
|
|
129
|
+
raise RuntimeError(f"failed to load ONNX file: {onnx_file}")
|
|
130
|
+
|
|
131
|
+
# Network inputs
|
|
132
|
+
inputs = [network.get_input(i) for i in range(network.num_inputs)]
|
|
133
|
+
outputs = [network.get_output(i) for i in range(network.num_outputs)]
|
|
134
|
+
for inp in inputs:
|
|
135
|
+
LOGGER.info(f'{prefix} input "{inp.name}" with shape{inp.shape} {inp.dtype}')
|
|
136
|
+
for out in outputs:
|
|
137
|
+
LOGGER.info(f'{prefix} output "{out.name}" with shape{out.shape} {out.dtype}')
|
|
138
|
+
|
|
139
|
+
if dynamic:
|
|
140
|
+
profile = builder.create_optimization_profile()
|
|
141
|
+
min_shape = (1, shape[1], 32, 32) # minimum input shape
|
|
142
|
+
max_shape = (*shape[:2], *(int(max(2, workspace or 2) * d) for d in shape[2:])) # max input shape
|
|
143
|
+
for inp in inputs:
|
|
144
|
+
profile.set_shape(inp.name, min=min_shape, opt=shape, max=max_shape)
|
|
145
|
+
config.add_optimization_profile(profile)
|
|
146
|
+
if int8:
|
|
147
|
+
config.set_calibration_profile(profile)
|
|
148
|
+
|
|
149
|
+
LOGGER.info(f"{prefix} building {'INT8' if int8 else 'FP' + ('16' if half else '32')} engine as {engine_file}")
|
|
150
|
+
if int8:
|
|
151
|
+
config.set_flag(trt.BuilderFlag.INT8)
|
|
152
|
+
config.profiling_verbosity = trt.ProfilingVerbosity.DETAILED
|
|
153
|
+
|
|
154
|
+
class EngineCalibrator(trt.IInt8Calibrator):
|
|
155
|
+
"""Custom INT8 calibrator for TensorRT engine optimization.
|
|
156
|
+
|
|
157
|
+
This calibrator provides the necessary interface for TensorRT to perform INT8 quantization calibration using
|
|
158
|
+
a dataset. It handles batch generation, caching, and calibration algorithm selection.
|
|
159
|
+
|
|
160
|
+
Attributes:
|
|
161
|
+
dataset: Dataset for calibration.
|
|
162
|
+
data_iter: Iterator over the calibration dataset.
|
|
163
|
+
algo (trt.CalibrationAlgoType): Calibration algorithm type.
|
|
164
|
+
batch (int): Batch size for calibration.
|
|
165
|
+
cache (Path): Path to save the calibration cache.
|
|
166
|
+
|
|
167
|
+
Methods:
|
|
168
|
+
get_algorithm: Get the calibration algorithm to use.
|
|
169
|
+
get_batch_size: Get the batch size to use for calibration.
|
|
170
|
+
get_batch: Get the next batch to use for calibration.
|
|
171
|
+
read_calibration_cache: Use existing cache instead of calibrating again.
|
|
172
|
+
write_calibration_cache: Write calibration cache to disk.
|
|
173
|
+
"""
|
|
174
|
+
|
|
175
|
+
def __init__(
|
|
176
|
+
self,
|
|
177
|
+
dataset, # ultralytics.data.build.InfiniteDataLoader
|
|
178
|
+
cache: str = "",
|
|
179
|
+
) -> None:
|
|
180
|
+
"""Initialize the INT8 calibrator with dataset and cache path."""
|
|
181
|
+
trt.IInt8Calibrator.__init__(self)
|
|
182
|
+
self.dataset = dataset
|
|
183
|
+
self.data_iter = iter(dataset)
|
|
184
|
+
self.algo = (
|
|
185
|
+
trt.CalibrationAlgoType.ENTROPY_CALIBRATION_2 # DLA quantization needs ENTROPY_CALIBRATION_2
|
|
186
|
+
if dla is not None
|
|
187
|
+
else trt.CalibrationAlgoType.MINMAX_CALIBRATION
|
|
188
|
+
)
|
|
189
|
+
self.batch = dataset.batch_size
|
|
190
|
+
self.cache = Path(cache)
|
|
191
|
+
|
|
192
|
+
def get_algorithm(self) -> trt.CalibrationAlgoType:
|
|
193
|
+
"""Get the calibration algorithm to use."""
|
|
194
|
+
return self.algo
|
|
195
|
+
|
|
196
|
+
def get_batch_size(self) -> int:
|
|
197
|
+
"""Get the batch size to use for calibration."""
|
|
198
|
+
return self.batch or 1
|
|
199
|
+
|
|
200
|
+
def get_batch(self, names) -> list[int] | None:
|
|
201
|
+
"""Get the next batch to use for calibration, as a list of device memory pointers."""
|
|
202
|
+
try:
|
|
203
|
+
im0s = next(self.data_iter)["img"] / 255.0
|
|
204
|
+
im0s = im0s.to("cuda") if im0s.device.type == "cpu" else im0s
|
|
205
|
+
return [int(im0s.data_ptr())]
|
|
206
|
+
except StopIteration:
|
|
207
|
+
# Return None to signal to TensorRT there is no calibration data remaining
|
|
208
|
+
return None
|
|
209
|
+
|
|
210
|
+
def read_calibration_cache(self) -> bytes | None:
|
|
211
|
+
"""Use existing cache instead of calibrating again, otherwise, implicitly return None."""
|
|
212
|
+
if self.cache.exists() and self.cache.suffix == ".cache":
|
|
213
|
+
return self.cache.read_bytes()
|
|
214
|
+
|
|
215
|
+
def write_calibration_cache(self, cache: bytes) -> None:
|
|
216
|
+
"""Write calibration cache to disk."""
|
|
217
|
+
_ = self.cache.write_bytes(cache)
|
|
218
|
+
|
|
219
|
+
# Load dataset w/ builder (for batching) and calibrate
|
|
220
|
+
config.int8_calibrator = EngineCalibrator(
|
|
221
|
+
dataset=dataset,
|
|
222
|
+
cache=str(Path(onnx_file).with_suffix(".cache")),
|
|
223
|
+
)
|
|
224
|
+
|
|
225
|
+
elif half:
|
|
226
|
+
config.set_flag(trt.BuilderFlag.FP16)
|
|
227
|
+
|
|
228
|
+
# Write file
|
|
229
|
+
build = builder.build_serialized_network if is_trt10 else builder.build_engine
|
|
230
|
+
with build(network, config) as engine, open(engine_file, "wb") as t:
|
|
231
|
+
# Metadata
|
|
232
|
+
if metadata is not None:
|
|
233
|
+
meta = json.dumps(metadata)
|
|
234
|
+
t.write(len(meta).to_bytes(4, byteorder="little", signed=True))
|
|
235
|
+
t.write(meta.encode())
|
|
236
|
+
# Model
|
|
237
|
+
t.write(engine if is_trt10 else engine.serialize())
|