ultralytics-opencv-headless 8.3.242__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.
- tests/__init__.py +23 -0
- tests/conftest.py +59 -0
- tests/test_cli.py +131 -0
- tests/test_cuda.py +216 -0
- tests/test_engine.py +157 -0
- tests/test_exports.py +309 -0
- tests/test_integrations.py +151 -0
- tests/test_python.py +777 -0
- tests/test_solutions.py +371 -0
- ultralytics/__init__.py +48 -0
- ultralytics/assets/bus.jpg +0 -0
- ultralytics/assets/zidane.jpg +0 -0
- ultralytics/cfg/__init__.py +1026 -0
- ultralytics/cfg/datasets/Argoverse.yaml +78 -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 +32 -0
- ultralytics/cfg/datasets/ImageNet.yaml +2025 -0
- ultralytics/cfg/datasets/Objects365.yaml +447 -0
- ultralytics/cfg/datasets/SKU-110K.yaml +58 -0
- ultralytics/cfg/datasets/VOC.yaml +102 -0
- ultralytics/cfg/datasets/VisDrone.yaml +87 -0
- ultralytics/cfg/datasets/african-wildlife.yaml +25 -0
- ultralytics/cfg/datasets/brain-tumor.yaml +22 -0
- ultralytics/cfg/datasets/carparts-seg.yaml +44 -0
- ultralytics/cfg/datasets/coco-pose.yaml +64 -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-grayscale.yaml +103 -0
- ultralytics/cfg/datasets/coco8-multispectral.yaml +104 -0
- ultralytics/cfg/datasets/coco8-pose.yaml +47 -0
- ultralytics/cfg/datasets/coco8-seg.yaml +101 -0
- ultralytics/cfg/datasets/coco8.yaml +101 -0
- ultralytics/cfg/datasets/construction-ppe.yaml +32 -0
- ultralytics/cfg/datasets/crack-seg.yaml +22 -0
- ultralytics/cfg/datasets/dog-pose.yaml +52 -0
- ultralytics/cfg/datasets/dota8-multispectral.yaml +38 -0
- ultralytics/cfg/datasets/dota8.yaml +35 -0
- ultralytics/cfg/datasets/hand-keypoints.yaml +50 -0
- ultralytics/cfg/datasets/kitti.yaml +27 -0
- ultralytics/cfg/datasets/lvis.yaml +1240 -0
- ultralytics/cfg/datasets/medical-pills.yaml +21 -0
- ultralytics/cfg/datasets/open-images-v7.yaml +663 -0
- ultralytics/cfg/datasets/package-seg.yaml +22 -0
- ultralytics/cfg/datasets/signature.yaml +21 -0
- ultralytics/cfg/datasets/tiger-pose.yaml +41 -0
- ultralytics/cfg/datasets/xView.yaml +155 -0
- ultralytics/cfg/default.yaml +130 -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 +48 -0
- ultralytics/cfg/models/v8/yoloe-v8.yaml +48 -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 +21 -0
- ultralytics/cfg/trackers/bytetrack.yaml +12 -0
- ultralytics/data/__init__.py +26 -0
- ultralytics/data/annotator.py +66 -0
- ultralytics/data/augment.py +2801 -0
- ultralytics/data/base.py +435 -0
- ultralytics/data/build.py +437 -0
- ultralytics/data/converter.py +855 -0
- ultralytics/data/dataset.py +834 -0
- ultralytics/data/loaders.py +704 -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 +138 -0
- ultralytics/data/split_dota.py +344 -0
- ultralytics/data/utils.py +798 -0
- ultralytics/engine/__init__.py +1 -0
- ultralytics/engine/exporter.py +1574 -0
- ultralytics/engine/model.py +1124 -0
- ultralytics/engine/predictor.py +508 -0
- ultralytics/engine/results.py +1522 -0
- ultralytics/engine/trainer.py +974 -0
- ultralytics/engine/tuner.py +448 -0
- ultralytics/engine/validator.py +384 -0
- ultralytics/hub/__init__.py +166 -0
- ultralytics/hub/auth.py +151 -0
- ultralytics/hub/google/__init__.py +174 -0
- ultralytics/hub/session.py +422 -0
- ultralytics/hub/utils.py +162 -0
- ultralytics/models/__init__.py +9 -0
- ultralytics/models/fastsam/__init__.py +7 -0
- ultralytics/models/fastsam/model.py +79 -0
- ultralytics/models/fastsam/predict.py +169 -0
- ultralytics/models/fastsam/utils.py +23 -0
- ultralytics/models/fastsam/val.py +38 -0
- ultralytics/models/nas/__init__.py +7 -0
- ultralytics/models/nas/model.py +98 -0
- ultralytics/models/nas/predict.py +56 -0
- ultralytics/models/nas/val.py +38 -0
- ultralytics/models/rtdetr/__init__.py +7 -0
- ultralytics/models/rtdetr/model.py +63 -0
- ultralytics/models/rtdetr/predict.py +88 -0
- ultralytics/models/rtdetr/train.py +89 -0
- ultralytics/models/rtdetr/val.py +216 -0
- ultralytics/models/sam/__init__.py +25 -0
- ultralytics/models/sam/amg.py +275 -0
- ultralytics/models/sam/build.py +365 -0
- ultralytics/models/sam/build_sam3.py +377 -0
- ultralytics/models/sam/model.py +169 -0
- ultralytics/models/sam/modules/__init__.py +1 -0
- ultralytics/models/sam/modules/blocks.py +1067 -0
- ultralytics/models/sam/modules/decoders.py +495 -0
- ultralytics/models/sam/modules/encoders.py +794 -0
- ultralytics/models/sam/modules/memory_attention.py +298 -0
- ultralytics/models/sam/modules/sam.py +1160 -0
- ultralytics/models/sam/modules/tiny_encoder.py +979 -0
- ultralytics/models/sam/modules/transformer.py +344 -0
- ultralytics/models/sam/modules/utils.py +512 -0
- ultralytics/models/sam/predict.py +3940 -0
- 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/__init__.py +1 -0
- ultralytics/models/utils/loss.py +466 -0
- ultralytics/models/utils/ops.py +315 -0
- ultralytics/models/yolo/__init__.py +7 -0
- ultralytics/models/yolo/classify/__init__.py +7 -0
- ultralytics/models/yolo/classify/predict.py +90 -0
- ultralytics/models/yolo/classify/train.py +202 -0
- ultralytics/models/yolo/classify/val.py +216 -0
- ultralytics/models/yolo/detect/__init__.py +7 -0
- ultralytics/models/yolo/detect/predict.py +122 -0
- ultralytics/models/yolo/detect/train.py +227 -0
- ultralytics/models/yolo/detect/val.py +507 -0
- ultralytics/models/yolo/model.py +430 -0
- ultralytics/models/yolo/obb/__init__.py +7 -0
- ultralytics/models/yolo/obb/predict.py +56 -0
- ultralytics/models/yolo/obb/train.py +79 -0
- ultralytics/models/yolo/obb/val.py +302 -0
- ultralytics/models/yolo/pose/__init__.py +7 -0
- ultralytics/models/yolo/pose/predict.py +65 -0
- ultralytics/models/yolo/pose/train.py +110 -0
- ultralytics/models/yolo/pose/val.py +248 -0
- ultralytics/models/yolo/segment/__init__.py +7 -0
- ultralytics/models/yolo/segment/predict.py +109 -0
- ultralytics/models/yolo/segment/train.py +69 -0
- ultralytics/models/yolo/segment/val.py +307 -0
- ultralytics/models/yolo/world/__init__.py +5 -0
- ultralytics/models/yolo/world/train.py +173 -0
- ultralytics/models/yolo/world/train_world.py +178 -0
- ultralytics/models/yolo/yoloe/__init__.py +22 -0
- ultralytics/models/yolo/yoloe/predict.py +162 -0
- ultralytics/models/yolo/yoloe/train.py +287 -0
- ultralytics/models/yolo/yoloe/train_seg.py +122 -0
- ultralytics/models/yolo/yoloe/val.py +206 -0
- ultralytics/nn/__init__.py +27 -0
- ultralytics/nn/autobackend.py +958 -0
- ultralytics/nn/modules/__init__.py +182 -0
- ultralytics/nn/modules/activation.py +54 -0
- ultralytics/nn/modules/block.py +1947 -0
- ultralytics/nn/modules/conv.py +669 -0
- ultralytics/nn/modules/head.py +1183 -0
- ultralytics/nn/modules/transformer.py +793 -0
- ultralytics/nn/modules/utils.py +159 -0
- ultralytics/nn/tasks.py +1768 -0
- ultralytics/nn/text_model.py +356 -0
- ultralytics/py.typed +1 -0
- ultralytics/solutions/__init__.py +41 -0
- ultralytics/solutions/ai_gym.py +108 -0
- ultralytics/solutions/analytics.py +264 -0
- ultralytics/solutions/config.py +107 -0
- ultralytics/solutions/distance_calculation.py +123 -0
- ultralytics/solutions/heatmap.py +125 -0
- ultralytics/solutions/instance_segmentation.py +86 -0
- ultralytics/solutions/object_blurrer.py +89 -0
- ultralytics/solutions/object_counter.py +190 -0
- ultralytics/solutions/object_cropper.py +87 -0
- ultralytics/solutions/parking_management.py +280 -0
- ultralytics/solutions/queue_management.py +93 -0
- ultralytics/solutions/region_counter.py +133 -0
- ultralytics/solutions/security_alarm.py +151 -0
- ultralytics/solutions/similarity_search.py +219 -0
- ultralytics/solutions/solutions.py +828 -0
- ultralytics/solutions/speed_estimation.py +114 -0
- ultralytics/solutions/streamlit_inference.py +260 -0
- ultralytics/solutions/templates/similarity-search.html +156 -0
- ultralytics/solutions/trackzone.py +88 -0
- ultralytics/solutions/vision_eye.py +67 -0
- ultralytics/trackers/__init__.py +7 -0
- ultralytics/trackers/basetrack.py +115 -0
- ultralytics/trackers/bot_sort.py +257 -0
- ultralytics/trackers/byte_tracker.py +469 -0
- ultralytics/trackers/track.py +116 -0
- ultralytics/trackers/utils/__init__.py +1 -0
- ultralytics/trackers/utils/gmc.py +339 -0
- ultralytics/trackers/utils/kalman_filter.py +482 -0
- ultralytics/trackers/utils/matching.py +154 -0
- ultralytics/utils/__init__.py +1450 -0
- ultralytics/utils/autobatch.py +118 -0
- ultralytics/utils/autodevice.py +205 -0
- ultralytics/utils/benchmarks.py +728 -0
- ultralytics/utils/callbacks/__init__.py +5 -0
- ultralytics/utils/callbacks/base.py +233 -0
- ultralytics/utils/callbacks/clearml.py +146 -0
- ultralytics/utils/callbacks/comet.py +625 -0
- ultralytics/utils/callbacks/dvc.py +197 -0
- ultralytics/utils/callbacks/hub.py +110 -0
- ultralytics/utils/callbacks/mlflow.py +134 -0
- ultralytics/utils/callbacks/neptune.py +126 -0
- ultralytics/utils/callbacks/platform.py +73 -0
- ultralytics/utils/callbacks/raytune.py +42 -0
- ultralytics/utils/callbacks/tensorboard.py +123 -0
- ultralytics/utils/callbacks/wb.py +188 -0
- ultralytics/utils/checks.py +998 -0
- ultralytics/utils/cpu.py +85 -0
- ultralytics/utils/dist.py +123 -0
- ultralytics/utils/downloads.py +529 -0
- ultralytics/utils/errors.py +35 -0
- ultralytics/utils/events.py +113 -0
- ultralytics/utils/export/__init__.py +7 -0
- ultralytics/utils/export/engine.py +237 -0
- ultralytics/utils/export/imx.py +315 -0
- ultralytics/utils/export/tensorflow.py +231 -0
- ultralytics/utils/files.py +219 -0
- ultralytics/utils/git.py +137 -0
- ultralytics/utils/instance.py +484 -0
- ultralytics/utils/logger.py +444 -0
- ultralytics/utils/loss.py +849 -0
- ultralytics/utils/metrics.py +1560 -0
- ultralytics/utils/nms.py +337 -0
- ultralytics/utils/ops.py +664 -0
- ultralytics/utils/patches.py +201 -0
- ultralytics/utils/plotting.py +1045 -0
- ultralytics/utils/tal.py +403 -0
- ultralytics/utils/torch_utils.py +984 -0
- ultralytics/utils/tqdm.py +440 -0
- ultralytics/utils/triton.py +112 -0
- ultralytics/utils/tuner.py +160 -0
- ultralytics_opencv_headless-8.3.242.dist-info/METADATA +374 -0
- ultralytics_opencv_headless-8.3.242.dist-info/RECORD +298 -0
- ultralytics_opencv_headless-8.3.242.dist-info/WHEEL +5 -0
- ultralytics_opencv_headless-8.3.242.dist-info/entry_points.txt +3 -0
- ultralytics_opencv_headless-8.3.242.dist-info/licenses/LICENSE +661 -0
- ultralytics_opencv_headless-8.3.242.dist-info/top_level.txt +1 -0
|
@@ -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())
|
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import subprocess
|
|
6
|
+
import types
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
import torch
|
|
11
|
+
|
|
12
|
+
from ultralytics.nn.modules import Detect, Pose, Segment
|
|
13
|
+
from ultralytics.utils import LOGGER
|
|
14
|
+
from ultralytics.utils.patches import onnx_export_patch
|
|
15
|
+
from ultralytics.utils.tal import make_anchors
|
|
16
|
+
from ultralytics.utils.torch_utils import copy_attr
|
|
17
|
+
|
|
18
|
+
# Configuration for Model Compression Toolkit (MCT) quantization
|
|
19
|
+
MCT_CONFIG = {
|
|
20
|
+
"YOLO11": {
|
|
21
|
+
"detect": {
|
|
22
|
+
"layer_names": ["sub", "mul_2", "add_14", "cat_21"],
|
|
23
|
+
"weights_memory": 2585350.2439,
|
|
24
|
+
"n_layers": 238,
|
|
25
|
+
},
|
|
26
|
+
"pose": {
|
|
27
|
+
"layer_names": ["sub", "mul_2", "add_14", "cat_22", "cat_23", "mul_4", "add_15"],
|
|
28
|
+
"weights_memory": 2437771.67,
|
|
29
|
+
"n_layers": 257,
|
|
30
|
+
},
|
|
31
|
+
"classify": {"layer_names": [], "weights_memory": np.inf, "n_layers": 112},
|
|
32
|
+
"segment": {"layer_names": ["sub", "mul_2", "add_14", "cat_22"], "weights_memory": 2466604.8, "n_layers": 265},
|
|
33
|
+
},
|
|
34
|
+
"YOLOv8": {
|
|
35
|
+
"detect": {"layer_names": ["sub", "mul", "add_6", "cat_17"], "weights_memory": 2550540.8, "n_layers": 168},
|
|
36
|
+
"pose": {
|
|
37
|
+
"layer_names": ["add_7", "mul_2", "cat_19", "mul", "sub", "add_6", "cat_18"],
|
|
38
|
+
"weights_memory": 2482451.85,
|
|
39
|
+
"n_layers": 187,
|
|
40
|
+
},
|
|
41
|
+
"classify": {"layer_names": [], "weights_memory": np.inf, "n_layers": 73},
|
|
42
|
+
"segment": {"layer_names": ["sub", "mul", "add_6", "cat_18"], "weights_memory": 2580060.0, "n_layers": 195},
|
|
43
|
+
},
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class FXModel(torch.nn.Module):
|
|
48
|
+
"""A custom model class for torch.fx compatibility.
|
|
49
|
+
|
|
50
|
+
This class extends `torch.nn.Module` and is designed to ensure compatibility with torch.fx for tracing and graph
|
|
51
|
+
manipulation. It copies attributes from an existing model and explicitly sets the model attribute to ensure proper
|
|
52
|
+
copying.
|
|
53
|
+
|
|
54
|
+
Attributes:
|
|
55
|
+
model (nn.Module): The original model's layers.
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
def __init__(self, model, imgsz=(640, 640)):
|
|
59
|
+
"""Initialize the FXModel.
|
|
60
|
+
|
|
61
|
+
Args:
|
|
62
|
+
model (nn.Module): The original model to wrap for torch.fx compatibility.
|
|
63
|
+
imgsz (tuple[int, int]): The input image size (height, width). Default is (640, 640).
|
|
64
|
+
"""
|
|
65
|
+
super().__init__()
|
|
66
|
+
copy_attr(self, model)
|
|
67
|
+
# Explicitly set `model` since `copy_attr` somehow does not copy it.
|
|
68
|
+
self.model = model.model
|
|
69
|
+
self.imgsz = imgsz
|
|
70
|
+
|
|
71
|
+
def forward(self, x):
|
|
72
|
+
"""Forward pass through the model.
|
|
73
|
+
|
|
74
|
+
This method performs the forward pass through the model, handling the dependencies between layers and saving
|
|
75
|
+
intermediate outputs.
|
|
76
|
+
|
|
77
|
+
Args:
|
|
78
|
+
x (torch.Tensor): The input tensor to the model.
|
|
79
|
+
|
|
80
|
+
Returns:
|
|
81
|
+
(torch.Tensor): The output tensor from the model.
|
|
82
|
+
"""
|
|
83
|
+
y = [] # outputs
|
|
84
|
+
for m in self.model:
|
|
85
|
+
if m.f != -1: # if not from previous layer
|
|
86
|
+
# from earlier layers
|
|
87
|
+
x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f]
|
|
88
|
+
if isinstance(m, Detect):
|
|
89
|
+
m._inference = types.MethodType(_inference, m) # bind method to Detect
|
|
90
|
+
m.anchors, m.strides = (
|
|
91
|
+
x.transpose(0, 1)
|
|
92
|
+
for x in make_anchors(
|
|
93
|
+
torch.cat([s / m.stride.unsqueeze(-1) for s in self.imgsz], dim=1), m.stride, 0.5
|
|
94
|
+
)
|
|
95
|
+
)
|
|
96
|
+
if type(m) is Pose:
|
|
97
|
+
m.forward = types.MethodType(pose_forward, m) # bind method to Detect
|
|
98
|
+
if type(m) is Segment:
|
|
99
|
+
m.forward = types.MethodType(segment_forward, m) # bind method to Detect
|
|
100
|
+
x = m(x) # run
|
|
101
|
+
y.append(x) # save output
|
|
102
|
+
return x
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _inference(self, x: list[torch.Tensor]) -> tuple[torch.Tensor]:
|
|
106
|
+
"""Decode boxes and cls scores for imx object detection."""
|
|
107
|
+
x_cat = torch.cat([xi.view(x[0].shape[0], self.no, -1) for xi in x], 2)
|
|
108
|
+
box, cls = x_cat.split((self.reg_max * 4, self.nc), 1)
|
|
109
|
+
dbox = self.decode_bboxes(self.dfl(box), self.anchors.unsqueeze(0)) * self.strides
|
|
110
|
+
return dbox.transpose(1, 2), cls.sigmoid().permute(0, 2, 1)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def pose_forward(self, x: list[torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
|
114
|
+
"""Forward pass for imx pose estimation, including keypoint decoding."""
|
|
115
|
+
bs = x[0].shape[0] # batch size
|
|
116
|
+
kpt = torch.cat([self.cv4[i](x[i]).view(bs, self.nk, -1) for i in range(self.nl)], -1) # (bs, 17*3, h*w)
|
|
117
|
+
x = Detect.forward(self, x)
|
|
118
|
+
pred_kpt = self.kpts_decode(bs, kpt)
|
|
119
|
+
return *x, pred_kpt.permute(0, 2, 1)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def segment_forward(self, x: list[torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
|
123
|
+
"""Forward pass for imx segmentation."""
|
|
124
|
+
p = self.proto(x[0]) # mask protos
|
|
125
|
+
bs = p.shape[0] # batch size
|
|
126
|
+
mc = torch.cat([self.cv4[i](x[i]).view(bs, self.nm, -1) for i in range(self.nl)], 2) # mask coefficients
|
|
127
|
+
x = Detect.forward(self, x)
|
|
128
|
+
return *x, mc.transpose(1, 2), p
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
class NMSWrapper(torch.nn.Module):
|
|
132
|
+
"""Wrap PyTorch Module with multiclass_nms layer from edge-mdt-cl."""
|
|
133
|
+
|
|
134
|
+
def __init__(
|
|
135
|
+
self,
|
|
136
|
+
model: torch.nn.Module,
|
|
137
|
+
score_threshold: float = 0.001,
|
|
138
|
+
iou_threshold: float = 0.7,
|
|
139
|
+
max_detections: int = 300,
|
|
140
|
+
task: str = "detect",
|
|
141
|
+
):
|
|
142
|
+
"""Initialize NMSWrapper with PyTorch Module and NMS parameters.
|
|
143
|
+
|
|
144
|
+
Args:
|
|
145
|
+
model (torch.nn.Module): Model instance.
|
|
146
|
+
score_threshold (float): Score threshold for non-maximum suppression.
|
|
147
|
+
iou_threshold (float): Intersection over union threshold for non-maximum suppression.
|
|
148
|
+
max_detections (int): The number of detections to return.
|
|
149
|
+
task (str): Task type, either 'detect' or 'pose'.
|
|
150
|
+
"""
|
|
151
|
+
super().__init__()
|
|
152
|
+
self.model = model
|
|
153
|
+
self.score_threshold = score_threshold
|
|
154
|
+
self.iou_threshold = iou_threshold
|
|
155
|
+
self.max_detections = max_detections
|
|
156
|
+
self.task = task
|
|
157
|
+
|
|
158
|
+
def forward(self, images):
|
|
159
|
+
"""Forward pass with model inference and NMS post-processing."""
|
|
160
|
+
from edgemdt_cl.pytorch.nms.nms_with_indices import multiclass_nms_with_indices
|
|
161
|
+
|
|
162
|
+
# model inference
|
|
163
|
+
outputs = self.model(images)
|
|
164
|
+
boxes, scores = outputs[0], outputs[1]
|
|
165
|
+
nms_outputs = multiclass_nms_with_indices(
|
|
166
|
+
boxes=boxes,
|
|
167
|
+
scores=scores,
|
|
168
|
+
score_threshold=self.score_threshold,
|
|
169
|
+
iou_threshold=self.iou_threshold,
|
|
170
|
+
max_detections=self.max_detections,
|
|
171
|
+
)
|
|
172
|
+
if self.task == "pose":
|
|
173
|
+
kpts = outputs[2] # (bs, max_detections, kpts 17*3)
|
|
174
|
+
out_kpts = torch.gather(kpts, 1, nms_outputs.indices.unsqueeze(-1).expand(-1, -1, kpts.size(-1)))
|
|
175
|
+
return nms_outputs.boxes, nms_outputs.scores, nms_outputs.labels, out_kpts
|
|
176
|
+
if self.task == "segment":
|
|
177
|
+
mc, proto = outputs[2], outputs[3]
|
|
178
|
+
out_mc = torch.gather(mc, 1, nms_outputs.indices.unsqueeze(-1).expand(-1, -1, mc.size(-1)))
|
|
179
|
+
return nms_outputs.boxes, nms_outputs.scores, nms_outputs.labels, out_mc, proto
|
|
180
|
+
return nms_outputs.boxes, nms_outputs.scores, nms_outputs.labels, nms_outputs.n_valid
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def torch2imx(
|
|
184
|
+
model: torch.nn.Module,
|
|
185
|
+
file: Path | str,
|
|
186
|
+
conf: float,
|
|
187
|
+
iou: float,
|
|
188
|
+
max_det: int,
|
|
189
|
+
metadata: dict | None = None,
|
|
190
|
+
gptq: bool = False,
|
|
191
|
+
dataset=None,
|
|
192
|
+
prefix: str = "",
|
|
193
|
+
):
|
|
194
|
+
"""Export YOLO model to IMX format for deployment on Sony IMX500 devices.
|
|
195
|
+
|
|
196
|
+
This function quantizes a YOLO model using Model Compression Toolkit (MCT) and exports it to IMX format compatible
|
|
197
|
+
with Sony IMX500 edge devices. It supports both YOLOv8n and YOLO11n models for detection and pose estimation tasks.
|
|
198
|
+
|
|
199
|
+
Args:
|
|
200
|
+
model (torch.nn.Module): The YOLO model to export. Must be YOLOv8n or YOLO11n.
|
|
201
|
+
file (Path | str): Output file path for the exported model.
|
|
202
|
+
conf (float): Confidence threshold for NMS post-processing.
|
|
203
|
+
iou (float): IoU threshold for NMS post-processing.
|
|
204
|
+
max_det (int): Maximum number of detections to return.
|
|
205
|
+
metadata (dict | None, optional): Metadata to embed in the ONNX model. Defaults to None.
|
|
206
|
+
gptq (bool, optional): Whether to use Gradient-Based Post Training Quantization. If False, uses standard Post
|
|
207
|
+
Training Quantization. Defaults to False.
|
|
208
|
+
dataset (optional): Representative dataset for quantization calibration. Defaults to None.
|
|
209
|
+
prefix (str, optional): Logging prefix string. Defaults to "".
|
|
210
|
+
|
|
211
|
+
Returns:
|
|
212
|
+
f (Path): Path to the exported IMX model directory
|
|
213
|
+
|
|
214
|
+
Raises:
|
|
215
|
+
ValueError: If the model is not a supported YOLOv8n or YOLO11n variant.
|
|
216
|
+
|
|
217
|
+
Examples:
|
|
218
|
+
>>> from ultralytics import YOLO
|
|
219
|
+
>>> model = YOLO("yolo11n.pt")
|
|
220
|
+
>>> path, _ = export_imx(model, "model.imx", conf=0.25, iou=0.45, max_det=300)
|
|
221
|
+
|
|
222
|
+
Notes:
|
|
223
|
+
- Requires model_compression_toolkit, onnx, edgemdt_tpc, and edge-mdt-cl packages
|
|
224
|
+
- Only supports YOLOv8n and YOLO11n models (detection and pose tasks)
|
|
225
|
+
- Output includes quantized ONNX model, IMX binary, and labels.txt file
|
|
226
|
+
"""
|
|
227
|
+
import model_compression_toolkit as mct
|
|
228
|
+
import onnx
|
|
229
|
+
from edgemdt_tpc import get_target_platform_capabilities
|
|
230
|
+
|
|
231
|
+
LOGGER.info(f"\n{prefix} starting export with model_compression_toolkit {mct.__version__}...")
|
|
232
|
+
|
|
233
|
+
def representative_dataset_gen(dataloader=dataset):
|
|
234
|
+
for batch in dataloader:
|
|
235
|
+
img = batch["img"]
|
|
236
|
+
img = img / 255.0
|
|
237
|
+
yield [img]
|
|
238
|
+
|
|
239
|
+
# NOTE: need tpc_version to be "4.0" for IMX500 Pose estimation models
|
|
240
|
+
tpc = get_target_platform_capabilities(tpc_version="4.0", device_type="imx500")
|
|
241
|
+
|
|
242
|
+
bit_cfg = mct.core.BitWidthConfig()
|
|
243
|
+
mct_config = MCT_CONFIG["YOLO11" if "C2PSA" in model.__str__() else "YOLOv8"][model.task]
|
|
244
|
+
|
|
245
|
+
# Check if the model has the expected number of layers
|
|
246
|
+
if len(list(model.modules())) != mct_config["n_layers"]:
|
|
247
|
+
raise ValueError("IMX export only supported for YOLOv8n and YOLO11n models.")
|
|
248
|
+
|
|
249
|
+
for layer_name in mct_config["layer_names"]:
|
|
250
|
+
bit_cfg.set_manual_activation_bit_width([mct.core.common.network_editors.NodeNameFilter(layer_name)], 16)
|
|
251
|
+
|
|
252
|
+
config = mct.core.CoreConfig(
|
|
253
|
+
mixed_precision_config=mct.core.MixedPrecisionQuantizationConfig(num_of_images=10),
|
|
254
|
+
quantization_config=mct.core.QuantizationConfig(concat_threshold_update=True),
|
|
255
|
+
bit_width_config=bit_cfg,
|
|
256
|
+
)
|
|
257
|
+
|
|
258
|
+
resource_utilization = mct.core.ResourceUtilization(weights_memory=mct_config["weights_memory"])
|
|
259
|
+
|
|
260
|
+
quant_model = (
|
|
261
|
+
mct.gptq.pytorch_gradient_post_training_quantization( # Perform Gradient-Based Post Training Quantization
|
|
262
|
+
model=model,
|
|
263
|
+
representative_data_gen=representative_dataset_gen,
|
|
264
|
+
target_resource_utilization=resource_utilization,
|
|
265
|
+
gptq_config=mct.gptq.get_pytorch_gptq_config(
|
|
266
|
+
n_epochs=1000, use_hessian_based_weights=False, use_hessian_sample_attention=False
|
|
267
|
+
),
|
|
268
|
+
core_config=config,
|
|
269
|
+
target_platform_capabilities=tpc,
|
|
270
|
+
)[0]
|
|
271
|
+
if gptq
|
|
272
|
+
else mct.ptq.pytorch_post_training_quantization( # Perform post training quantization
|
|
273
|
+
in_module=model,
|
|
274
|
+
representative_data_gen=representative_dataset_gen,
|
|
275
|
+
target_resource_utilization=resource_utilization,
|
|
276
|
+
core_config=config,
|
|
277
|
+
target_platform_capabilities=tpc,
|
|
278
|
+
)[0]
|
|
279
|
+
)
|
|
280
|
+
|
|
281
|
+
if model.task != "classify":
|
|
282
|
+
quant_model = NMSWrapper(
|
|
283
|
+
model=quant_model,
|
|
284
|
+
score_threshold=conf or 0.001,
|
|
285
|
+
iou_threshold=iou,
|
|
286
|
+
max_detections=max_det,
|
|
287
|
+
task=model.task,
|
|
288
|
+
)
|
|
289
|
+
|
|
290
|
+
f = Path(str(file).replace(file.suffix, "_imx_model"))
|
|
291
|
+
f.mkdir(exist_ok=True)
|
|
292
|
+
onnx_model = f / Path(str(file.name).replace(file.suffix, "_imx.onnx")) # js dir
|
|
293
|
+
|
|
294
|
+
with onnx_export_patch():
|
|
295
|
+
mct.exporter.pytorch_export_model(
|
|
296
|
+
model=quant_model, save_model_path=onnx_model, repr_dataset=representative_dataset_gen
|
|
297
|
+
)
|
|
298
|
+
|
|
299
|
+
model_onnx = onnx.load(onnx_model) # load onnx model
|
|
300
|
+
for k, v in metadata.items():
|
|
301
|
+
meta = model_onnx.metadata_props.add()
|
|
302
|
+
meta.key, meta.value = k, str(v)
|
|
303
|
+
|
|
304
|
+
onnx.save(model_onnx, onnx_model)
|
|
305
|
+
|
|
306
|
+
subprocess.run(
|
|
307
|
+
["imxconv-pt", "-i", str(onnx_model), "-o", str(f), "--no-input-persistency", "--overwrite-output"],
|
|
308
|
+
check=True,
|
|
309
|
+
)
|
|
310
|
+
|
|
311
|
+
# Needed for imx models.
|
|
312
|
+
with open(f / "labels.txt", "w", encoding="utf-8") as file:
|
|
313
|
+
file.writelines([f"{name}\n" for _, name in model.names.items()])
|
|
314
|
+
|
|
315
|
+
return f
|