dgenerate-ultralytics-headless 8.3.222__py3-none-any.whl → 8.3.225__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.
Files changed (158) hide show
  1. {dgenerate_ultralytics_headless-8.3.222.dist-info → dgenerate_ultralytics_headless-8.3.225.dist-info}/METADATA +2 -2
  2. dgenerate_ultralytics_headless-8.3.225.dist-info/RECORD +286 -0
  3. tests/conftest.py +5 -8
  4. tests/test_cli.py +1 -8
  5. tests/test_python.py +1 -2
  6. ultralytics/__init__.py +1 -1
  7. ultralytics/cfg/__init__.py +34 -49
  8. ultralytics/cfg/datasets/ImageNet.yaml +1 -1
  9. ultralytics/cfg/datasets/kitti.yaml +27 -0
  10. ultralytics/cfg/datasets/lvis.yaml +5 -5
  11. ultralytics/cfg/datasets/open-images-v7.yaml +1 -1
  12. ultralytics/data/annotator.py +3 -4
  13. ultralytics/data/augment.py +244 -323
  14. ultralytics/data/base.py +12 -22
  15. ultralytics/data/build.py +47 -40
  16. ultralytics/data/converter.py +32 -42
  17. ultralytics/data/dataset.py +43 -71
  18. ultralytics/data/loaders.py +22 -34
  19. ultralytics/data/split.py +5 -6
  20. ultralytics/data/split_dota.py +8 -15
  21. ultralytics/data/utils.py +27 -36
  22. ultralytics/engine/exporter.py +49 -116
  23. ultralytics/engine/model.py +144 -180
  24. ultralytics/engine/predictor.py +18 -29
  25. ultralytics/engine/results.py +165 -231
  26. ultralytics/engine/trainer.py +11 -19
  27. ultralytics/engine/tuner.py +13 -23
  28. ultralytics/engine/validator.py +6 -10
  29. ultralytics/hub/__init__.py +7 -12
  30. ultralytics/hub/auth.py +6 -12
  31. ultralytics/hub/google/__init__.py +7 -10
  32. ultralytics/hub/session.py +15 -25
  33. ultralytics/hub/utils.py +3 -6
  34. ultralytics/models/fastsam/model.py +6 -8
  35. ultralytics/models/fastsam/predict.py +5 -10
  36. ultralytics/models/fastsam/utils.py +1 -2
  37. ultralytics/models/fastsam/val.py +2 -4
  38. ultralytics/models/nas/model.py +5 -8
  39. ultralytics/models/nas/predict.py +7 -9
  40. ultralytics/models/nas/val.py +1 -2
  41. ultralytics/models/rtdetr/model.py +5 -8
  42. ultralytics/models/rtdetr/predict.py +15 -18
  43. ultralytics/models/rtdetr/train.py +10 -13
  44. ultralytics/models/rtdetr/val.py +13 -20
  45. ultralytics/models/sam/amg.py +12 -18
  46. ultralytics/models/sam/build.py +6 -9
  47. ultralytics/models/sam/model.py +16 -23
  48. ultralytics/models/sam/modules/blocks.py +62 -84
  49. ultralytics/models/sam/modules/decoders.py +17 -24
  50. ultralytics/models/sam/modules/encoders.py +40 -56
  51. ultralytics/models/sam/modules/memory_attention.py +10 -16
  52. ultralytics/models/sam/modules/sam.py +41 -47
  53. ultralytics/models/sam/modules/tiny_encoder.py +64 -83
  54. ultralytics/models/sam/modules/transformer.py +17 -27
  55. ultralytics/models/sam/modules/utils.py +31 -42
  56. ultralytics/models/sam/predict.py +172 -209
  57. ultralytics/models/utils/loss.py +14 -26
  58. ultralytics/models/utils/ops.py +13 -17
  59. ultralytics/models/yolo/classify/predict.py +8 -11
  60. ultralytics/models/yolo/classify/train.py +8 -16
  61. ultralytics/models/yolo/classify/val.py +13 -20
  62. ultralytics/models/yolo/detect/predict.py +4 -8
  63. ultralytics/models/yolo/detect/train.py +11 -20
  64. ultralytics/models/yolo/detect/val.py +38 -48
  65. ultralytics/models/yolo/model.py +35 -47
  66. ultralytics/models/yolo/obb/predict.py +5 -8
  67. ultralytics/models/yolo/obb/train.py +11 -14
  68. ultralytics/models/yolo/obb/val.py +20 -28
  69. ultralytics/models/yolo/pose/predict.py +5 -8
  70. ultralytics/models/yolo/pose/train.py +4 -8
  71. ultralytics/models/yolo/pose/val.py +31 -39
  72. ultralytics/models/yolo/segment/predict.py +9 -14
  73. ultralytics/models/yolo/segment/train.py +3 -6
  74. ultralytics/models/yolo/segment/val.py +16 -26
  75. ultralytics/models/yolo/world/train.py +8 -14
  76. ultralytics/models/yolo/world/train_world.py +11 -16
  77. ultralytics/models/yolo/yoloe/predict.py +16 -23
  78. ultralytics/models/yolo/yoloe/train.py +30 -43
  79. ultralytics/models/yolo/yoloe/train_seg.py +5 -10
  80. ultralytics/models/yolo/yoloe/val.py +15 -20
  81. ultralytics/nn/autobackend.py +10 -18
  82. ultralytics/nn/modules/activation.py +4 -6
  83. ultralytics/nn/modules/block.py +99 -185
  84. ultralytics/nn/modules/conv.py +45 -90
  85. ultralytics/nn/modules/head.py +44 -98
  86. ultralytics/nn/modules/transformer.py +44 -76
  87. ultralytics/nn/modules/utils.py +14 -19
  88. ultralytics/nn/tasks.py +86 -146
  89. ultralytics/nn/text_model.py +25 -40
  90. ultralytics/solutions/ai_gym.py +10 -16
  91. ultralytics/solutions/analytics.py +7 -10
  92. ultralytics/solutions/config.py +4 -5
  93. ultralytics/solutions/distance_calculation.py +9 -12
  94. ultralytics/solutions/heatmap.py +7 -13
  95. ultralytics/solutions/instance_segmentation.py +5 -8
  96. ultralytics/solutions/object_blurrer.py +7 -10
  97. ultralytics/solutions/object_counter.py +8 -12
  98. ultralytics/solutions/object_cropper.py +5 -8
  99. ultralytics/solutions/parking_management.py +12 -14
  100. ultralytics/solutions/queue_management.py +4 -6
  101. ultralytics/solutions/region_counter.py +7 -10
  102. ultralytics/solutions/security_alarm.py +14 -19
  103. ultralytics/solutions/similarity_search.py +7 -12
  104. ultralytics/solutions/solutions.py +31 -53
  105. ultralytics/solutions/speed_estimation.py +6 -9
  106. ultralytics/solutions/streamlit_inference.py +2 -4
  107. ultralytics/solutions/trackzone.py +7 -10
  108. ultralytics/solutions/vision_eye.py +5 -8
  109. ultralytics/trackers/basetrack.py +2 -4
  110. ultralytics/trackers/bot_sort.py +6 -11
  111. ultralytics/trackers/byte_tracker.py +10 -15
  112. ultralytics/trackers/track.py +3 -6
  113. ultralytics/trackers/utils/gmc.py +6 -12
  114. ultralytics/trackers/utils/kalman_filter.py +35 -43
  115. ultralytics/trackers/utils/matching.py +6 -10
  116. ultralytics/utils/__init__.py +61 -100
  117. ultralytics/utils/autobatch.py +2 -4
  118. ultralytics/utils/autodevice.py +11 -13
  119. ultralytics/utils/benchmarks.py +25 -35
  120. ultralytics/utils/callbacks/base.py +8 -10
  121. ultralytics/utils/callbacks/clearml.py +2 -4
  122. ultralytics/utils/callbacks/comet.py +30 -44
  123. ultralytics/utils/callbacks/dvc.py +13 -18
  124. ultralytics/utils/callbacks/mlflow.py +4 -5
  125. ultralytics/utils/callbacks/neptune.py +4 -6
  126. ultralytics/utils/callbacks/raytune.py +3 -4
  127. ultralytics/utils/callbacks/tensorboard.py +4 -6
  128. ultralytics/utils/callbacks/wb.py +10 -13
  129. ultralytics/utils/checks.py +29 -56
  130. ultralytics/utils/cpu.py +1 -2
  131. ultralytics/utils/dist.py +8 -12
  132. ultralytics/utils/downloads.py +17 -27
  133. ultralytics/utils/errors.py +6 -8
  134. ultralytics/utils/events.py +2 -4
  135. ultralytics/utils/export/__init__.py +4 -239
  136. ultralytics/utils/export/engine.py +237 -0
  137. ultralytics/utils/export/imx.py +11 -17
  138. ultralytics/utils/export/tensorflow.py +217 -0
  139. ultralytics/utils/files.py +10 -15
  140. ultralytics/utils/git.py +5 -7
  141. ultralytics/utils/instance.py +30 -51
  142. ultralytics/utils/logger.py +11 -15
  143. ultralytics/utils/loss.py +8 -14
  144. ultralytics/utils/metrics.py +98 -138
  145. ultralytics/utils/nms.py +13 -16
  146. ultralytics/utils/ops.py +47 -74
  147. ultralytics/utils/patches.py +11 -18
  148. ultralytics/utils/plotting.py +29 -42
  149. ultralytics/utils/tal.py +25 -39
  150. ultralytics/utils/torch_utils.py +45 -73
  151. ultralytics/utils/tqdm.py +6 -8
  152. ultralytics/utils/triton.py +9 -12
  153. ultralytics/utils/tuner.py +1 -2
  154. dgenerate_ultralytics_headless-8.3.222.dist-info/RECORD +0 -283
  155. {dgenerate_ultralytics_headless-8.3.222.dist-info → dgenerate_ultralytics_headless-8.3.225.dist-info}/WHEEL +0 -0
  156. {dgenerate_ultralytics_headless-8.3.222.dist-info → dgenerate_ultralytics_headless-8.3.225.dist-info}/entry_points.txt +0 -0
  157. {dgenerate_ultralytics_headless-8.3.222.dist-info → dgenerate_ultralytics_headless-8.3.225.dist-info}/licenses/LICENSE +0 -0
  158. {dgenerate_ultralytics_headless-8.3.222.dist-info → dgenerate_ultralytics_headless-8.3.225.dist-info}/top_level.txt +0 -0
@@ -1,242 +1,7 @@
1
1
  # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
2
 
3
- from __future__ import annotations
3
+ from .engine import onnx2engine, torch2onnx
4
+ from .imx import torch2imx
5
+ from .tensorflow import keras2pb, onnx2saved_model, pb2tfjs, tflite2edgetpu
4
6
 
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
- from .imx import torch2imx # noqa
14
-
15
-
16
- def torch2onnx(
17
- torch_model: torch.nn.Module,
18
- im: torch.Tensor,
19
- onnx_file: str,
20
- opset: int = 14,
21
- input_names: list[str] = ["images"],
22
- output_names: list[str] = ["output0"],
23
- dynamic: bool | dict = False,
24
- ) -> None:
25
- """
26
- Export a PyTorch model to ONNX format.
27
-
28
- Args:
29
- torch_model (torch.nn.Module): The PyTorch model to export.
30
- im (torch.Tensor): Example input tensor for the model.
31
- onnx_file (str): Path to save the exported ONNX file.
32
- opset (int): ONNX opset version to use for export.
33
- input_names (list[str]): List of input tensor names.
34
- output_names (list[str]): List of output tensor names.
35
- dynamic (bool | dict, optional): Whether to enable dynamic axes.
36
-
37
- Notes:
38
- Setting `do_constant_folding=True` may cause issues with DNN inference for torch>=1.12.
39
- """
40
- kwargs = {"dynamo": False} if TORCH_2_4 else {}
41
- torch.onnx.export(
42
- torch_model,
43
- im,
44
- onnx_file,
45
- verbose=False,
46
- opset_version=opset,
47
- do_constant_folding=True, # WARNING: DNN inference with torch>=1.12 may require do_constant_folding=False
48
- input_names=input_names,
49
- output_names=output_names,
50
- dynamic_axes=dynamic or None,
51
- **kwargs,
52
- )
53
-
54
-
55
- def onnx2engine(
56
- onnx_file: str,
57
- engine_file: str | None = None,
58
- workspace: int | None = None,
59
- half: bool = False,
60
- int8: bool = False,
61
- dynamic: bool = False,
62
- shape: tuple[int, int, int, int] = (1, 3, 640, 640),
63
- dla: int | None = None,
64
- dataset=None,
65
- metadata: dict | None = None,
66
- verbose: bool = False,
67
- prefix: str = "",
68
- ) -> None:
69
- """
70
- Export a YOLO model to TensorRT engine format.
71
-
72
- Args:
73
- onnx_file (str): Path to the ONNX file to be converted.
74
- engine_file (str, optional): Path to save the generated TensorRT engine file.
75
- workspace (int, optional): Workspace size in GB for TensorRT.
76
- half (bool, optional): Enable FP16 precision.
77
- int8 (bool, optional): Enable INT8 precision.
78
- dynamic (bool, optional): Enable dynamic input shapes.
79
- shape (tuple[int, int, int, int], optional): Input shape (batch, channels, height, width).
80
- dla (int, optional): DLA core to use (Jetson devices only).
81
- dataset (ultralytics.data.build.InfiniteDataLoader, optional): Dataset for INT8 calibration.
82
- metadata (dict, optional): Metadata to include in the engine file.
83
- verbose (bool, optional): Enable verbose logging.
84
- prefix (str, optional): Prefix for log messages.
85
-
86
- Raises:
87
- ValueError: If DLA is enabled on non-Jetson devices or required precision is not set.
88
- RuntimeError: If the ONNX file cannot be parsed.
89
-
90
- Notes:
91
- TensorRT version compatibility is handled for workspace size and engine building.
92
- INT8 calibration requires a dataset and generates a calibration cache.
93
- Metadata is serialized and written to the engine file if provided.
94
- """
95
- import tensorrt as trt
96
-
97
- engine_file = engine_file or Path(onnx_file).with_suffix(".engine")
98
-
99
- logger = trt.Logger(trt.Logger.INFO)
100
- if verbose:
101
- logger.min_severity = trt.Logger.Severity.VERBOSE
102
-
103
- # Engine builder
104
- builder = trt.Builder(logger)
105
- config = builder.create_builder_config()
106
- workspace_bytes = int((workspace or 0) * (1 << 30))
107
- is_trt10 = int(trt.__version__.split(".", 1)[0]) >= 10 # is TensorRT >= 10
108
- if is_trt10 and workspace_bytes > 0:
109
- config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, workspace_bytes)
110
- elif workspace_bytes > 0: # TensorRT versions 7, 8
111
- config.max_workspace_size = workspace_bytes
112
- flag = 1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)
113
- network = builder.create_network(flag)
114
- half = builder.platform_has_fast_fp16 and half
115
- int8 = builder.platform_has_fast_int8 and int8
116
-
117
- # Optionally switch to DLA if enabled
118
- if dla is not None:
119
- if not IS_JETSON:
120
- raise ValueError("DLA is only available on NVIDIA Jetson devices")
121
- LOGGER.info(f"{prefix} enabling DLA on core {dla}...")
122
- if not half and not int8:
123
- raise ValueError(
124
- "DLA requires either 'half=True' (FP16) or 'int8=True' (INT8) to be enabled. Please enable one of them and try again."
125
- )
126
- config.default_device_type = trt.DeviceType.DLA
127
- config.DLA_core = int(dla)
128
- config.set_flag(trt.BuilderFlag.GPU_FALLBACK)
129
-
130
- # Read ONNX file
131
- parser = trt.OnnxParser(network, logger)
132
- if not parser.parse_from_file(onnx_file):
133
- raise RuntimeError(f"failed to load ONNX file: {onnx_file}")
134
-
135
- # Network inputs
136
- inputs = [network.get_input(i) for i in range(network.num_inputs)]
137
- outputs = [network.get_output(i) for i in range(network.num_outputs)]
138
- for inp in inputs:
139
- LOGGER.info(f'{prefix} input "{inp.name}" with shape{inp.shape} {inp.dtype}')
140
- for out in outputs:
141
- LOGGER.info(f'{prefix} output "{out.name}" with shape{out.shape} {out.dtype}')
142
-
143
- if dynamic:
144
- profile = builder.create_optimization_profile()
145
- min_shape = (1, shape[1], 32, 32) # minimum input shape
146
- max_shape = (*shape[:2], *(int(max(2, workspace or 2) * d) for d in shape[2:])) # max input shape
147
- for inp in inputs:
148
- profile.set_shape(inp.name, min=min_shape, opt=shape, max=max_shape)
149
- config.add_optimization_profile(profile)
150
- if int8:
151
- config.set_calibration_profile(profile)
152
-
153
- LOGGER.info(f"{prefix} building {'INT8' if int8 else 'FP' + ('16' if half else '32')} engine as {engine_file}")
154
- if int8:
155
- config.set_flag(trt.BuilderFlag.INT8)
156
- config.profiling_verbosity = trt.ProfilingVerbosity.DETAILED
157
-
158
- class EngineCalibrator(trt.IInt8Calibrator):
159
- """
160
- Custom INT8 calibrator for TensorRT engine optimization.
161
-
162
- This calibrator provides the necessary interface for TensorRT to perform INT8 quantization calibration
163
- using a dataset. It handles batch generation, caching, and calibration algorithm selection.
164
-
165
- Attributes:
166
- dataset: Dataset for calibration.
167
- data_iter: Iterator over the calibration dataset.
168
- algo (trt.CalibrationAlgoType): Calibration algorithm type.
169
- batch (int): Batch size for calibration.
170
- cache (Path): Path to save the calibration cache.
171
-
172
- Methods:
173
- get_algorithm: Get the calibration algorithm to use.
174
- get_batch_size: Get the batch size to use for calibration.
175
- get_batch: Get the next batch to use for calibration.
176
- read_calibration_cache: Use existing cache instead of calibrating again.
177
- write_calibration_cache: Write calibration cache to disk.
178
- """
179
-
180
- def __init__(
181
- self,
182
- dataset, # ultralytics.data.build.InfiniteDataLoader
183
- cache: str = "",
184
- ) -> None:
185
- """Initialize the INT8 calibrator with dataset and cache path."""
186
- trt.IInt8Calibrator.__init__(self)
187
- self.dataset = dataset
188
- self.data_iter = iter(dataset)
189
- self.algo = (
190
- trt.CalibrationAlgoType.ENTROPY_CALIBRATION_2 # DLA quantization needs ENTROPY_CALIBRATION_2
191
- if dla is not None
192
- else trt.CalibrationAlgoType.MINMAX_CALIBRATION
193
- )
194
- self.batch = dataset.batch_size
195
- self.cache = Path(cache)
196
-
197
- def get_algorithm(self) -> trt.CalibrationAlgoType:
198
- """Get the calibration algorithm to use."""
199
- return self.algo
200
-
201
- def get_batch_size(self) -> int:
202
- """Get the batch size to use for calibration."""
203
- return self.batch or 1
204
-
205
- def get_batch(self, names) -> list[int] | None:
206
- """Get the next batch to use for calibration, as a list of device memory pointers."""
207
- try:
208
- im0s = next(self.data_iter)["img"] / 255.0
209
- im0s = im0s.to("cuda") if im0s.device.type == "cpu" else im0s
210
- return [int(im0s.data_ptr())]
211
- except StopIteration:
212
- # Return None to signal to TensorRT there is no calibration data remaining
213
- return None
214
-
215
- def read_calibration_cache(self) -> bytes | None:
216
- """Use existing cache instead of calibrating again, otherwise, implicitly return None."""
217
- if self.cache.exists() and self.cache.suffix == ".cache":
218
- return self.cache.read_bytes()
219
-
220
- def write_calibration_cache(self, cache: bytes) -> None:
221
- """Write calibration cache to disk."""
222
- _ = self.cache.write_bytes(cache)
223
-
224
- # Load dataset w/ builder (for batching) and calibrate
225
- config.int8_calibrator = EngineCalibrator(
226
- dataset=dataset,
227
- cache=str(Path(onnx_file).with_suffix(".cache")),
228
- )
229
-
230
- elif half:
231
- config.set_flag(trt.BuilderFlag.FP16)
232
-
233
- # Write file
234
- build = builder.build_serialized_network if is_trt10 else builder.build_engine
235
- with build(network, config) as engine, open(engine_file, "wb") as t:
236
- # Metadata
237
- if metadata is not None:
238
- meta = json.dumps(metadata)
239
- t.write(len(meta).to_bytes(4, byteorder="little", signed=True))
240
- t.write(meta.encode())
241
- # Model
242
- 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())
@@ -42,8 +42,7 @@ MCT_CONFIG = {
42
42
 
43
43
 
44
44
  class FXModel(torch.nn.Module):
45
- """
46
- A custom model class for torch.fx compatibility.
45
+ """A custom model class for torch.fx compatibility.
47
46
 
48
47
  This class extends `torch.nn.Module` and is designed to ensure compatibility with torch.fx for tracing and graph
49
48
  manipulation. It copies attributes from an existing model and explicitly sets the model attribute to ensure proper
@@ -54,8 +53,7 @@ class FXModel(torch.nn.Module):
54
53
  """
55
54
 
56
55
  def __init__(self, model, imgsz=(640, 640)):
57
- """
58
- Initialize the FXModel.
56
+ """Initialize the FXModel.
59
57
 
60
58
  Args:
61
59
  model (nn.Module): The original model to wrap for torch.fx compatibility.
@@ -68,8 +66,7 @@ class FXModel(torch.nn.Module):
68
66
  self.imgsz = imgsz
69
67
 
70
68
  def forward(self, x):
71
- """
72
- Forward pass through the model.
69
+ """Forward pass through the model.
73
70
 
74
71
  This method performs the forward pass through the model, handling the dependencies between layers and saving
75
72
  intermediate outputs.
@@ -128,8 +125,7 @@ class NMSWrapper(torch.nn.Module):
128
125
  max_detections: int = 300,
129
126
  task: str = "detect",
130
127
  ):
131
- """
132
- Initialize NMSWrapper with PyTorch Module and NMS parameters.
128
+ """Initialize NMSWrapper with PyTorch Module and NMS parameters.
133
129
 
134
130
  Args:
135
131
  model (torch.nn.Module): Model instance.
@@ -177,12 +173,10 @@ def torch2imx(
177
173
  dataset=None,
178
174
  prefix: str = "",
179
175
  ):
180
- """
181
- Export YOLO model to IMX format for deployment on Sony IMX500 devices.
176
+ """Export YOLO model to IMX format for deployment on Sony IMX500 devices.
182
177
 
183
- This function quantizes a YOLO model using Model Compression Toolkit (MCT) and exports it
184
- to IMX format compatible with Sony IMX500 edge devices. It supports both YOLOv8n and YOLO11n
185
- models for detection and pose estimation tasks.
178
+ This function quantizes a YOLO model using Model Compression Toolkit (MCT) and exports it to IMX format compatible
179
+ with Sony IMX500 edge devices. It supports both YOLOv8n and YOLO11n models for detection and pose estimation tasks.
186
180
 
187
181
  Args:
188
182
  model (torch.nn.Module): The YOLO model to export. Must be YOLOv8n or YOLO11n.
@@ -191,8 +185,8 @@ def torch2imx(
191
185
  iou (float): IoU threshold for NMS post-processing.
192
186
  max_det (int): Maximum number of detections to return.
193
187
  metadata (dict | None, optional): Metadata to embed in the ONNX model. Defaults to None.
194
- gptq (bool, optional): Whether to use Gradient-Based Post Training Quantization.
195
- If False, uses standard Post Training Quantization. Defaults to False.
188
+ gptq (bool, optional): Whether to use Gradient-Based Post Training Quantization. If False, uses standard Post
189
+ Training Quantization. Defaults to False.
196
190
  dataset (optional): Representative dataset for quantization calibration. Defaults to None.
197
191
  prefix (str, optional): Logging prefix string. Defaults to "".
198
192
 
@@ -202,12 +196,12 @@ def torch2imx(
202
196
  Raises:
203
197
  ValueError: If the model is not a supported YOLOv8n or YOLO11n variant.
204
198
 
205
- Example:
199
+ Examples:
206
200
  >>> from ultralytics import YOLO
207
201
  >>> model = YOLO("yolo11n.pt")
208
202
  >>> path, _ = export_imx(model, "model.imx", conf=0.25, iou=0.45, max_det=300)
209
203
 
210
- Note:
204
+ Notes:
211
205
  - Requires model_compression_toolkit, onnx, edgemdt_tpc, and sony_custom_layers packages
212
206
  - Only supports YOLOv8n and YOLO11n models (detection and pose tasks)
213
207
  - Output includes quantized ONNX model, IMX binary, and labels.txt file