dgenerate-ultralytics-headless 8.3.134__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (272) hide show
  1. dgenerate_ultralytics_headless-8.3.134.dist-info/METADATA +400 -0
  2. dgenerate_ultralytics_headless-8.3.134.dist-info/RECORD +272 -0
  3. dgenerate_ultralytics_headless-8.3.134.dist-info/WHEEL +5 -0
  4. dgenerate_ultralytics_headless-8.3.134.dist-info/entry_points.txt +3 -0
  5. dgenerate_ultralytics_headless-8.3.134.dist-info/licenses/LICENSE +661 -0
  6. dgenerate_ultralytics_headless-8.3.134.dist-info/top_level.txt +1 -0
  7. tests/__init__.py +22 -0
  8. tests/conftest.py +83 -0
  9. tests/test_cli.py +138 -0
  10. tests/test_cuda.py +215 -0
  11. tests/test_engine.py +131 -0
  12. tests/test_exports.py +236 -0
  13. tests/test_integrations.py +154 -0
  14. tests/test_python.py +694 -0
  15. tests/test_solutions.py +187 -0
  16. ultralytics/__init__.py +30 -0
  17. ultralytics/assets/bus.jpg +0 -0
  18. ultralytics/assets/zidane.jpg +0 -0
  19. ultralytics/cfg/__init__.py +1023 -0
  20. ultralytics/cfg/datasets/Argoverse.yaml +77 -0
  21. ultralytics/cfg/datasets/DOTAv1.5.yaml +37 -0
  22. ultralytics/cfg/datasets/DOTAv1.yaml +36 -0
  23. ultralytics/cfg/datasets/GlobalWheat2020.yaml +68 -0
  24. ultralytics/cfg/datasets/HomeObjects-3K.yaml +33 -0
  25. ultralytics/cfg/datasets/ImageNet.yaml +2025 -0
  26. ultralytics/cfg/datasets/Objects365.yaml +443 -0
  27. ultralytics/cfg/datasets/SKU-110K.yaml +58 -0
  28. ultralytics/cfg/datasets/VOC.yaml +106 -0
  29. ultralytics/cfg/datasets/VisDrone.yaml +77 -0
  30. ultralytics/cfg/datasets/african-wildlife.yaml +25 -0
  31. ultralytics/cfg/datasets/brain-tumor.yaml +23 -0
  32. ultralytics/cfg/datasets/carparts-seg.yaml +44 -0
  33. ultralytics/cfg/datasets/coco-pose.yaml +42 -0
  34. ultralytics/cfg/datasets/coco.yaml +118 -0
  35. ultralytics/cfg/datasets/coco128-seg.yaml +101 -0
  36. ultralytics/cfg/datasets/coco128.yaml +101 -0
  37. ultralytics/cfg/datasets/coco8-multispectral.yaml +104 -0
  38. ultralytics/cfg/datasets/coco8-pose.yaml +26 -0
  39. ultralytics/cfg/datasets/coco8-seg.yaml +101 -0
  40. ultralytics/cfg/datasets/coco8.yaml +101 -0
  41. ultralytics/cfg/datasets/crack-seg.yaml +22 -0
  42. ultralytics/cfg/datasets/dog-pose.yaml +24 -0
  43. ultralytics/cfg/datasets/dota8-multispectral.yaml +38 -0
  44. ultralytics/cfg/datasets/dota8.yaml +35 -0
  45. ultralytics/cfg/datasets/hand-keypoints.yaml +26 -0
  46. ultralytics/cfg/datasets/lvis.yaml +1240 -0
  47. ultralytics/cfg/datasets/medical-pills.yaml +22 -0
  48. ultralytics/cfg/datasets/open-images-v7.yaml +666 -0
  49. ultralytics/cfg/datasets/package-seg.yaml +22 -0
  50. ultralytics/cfg/datasets/signature.yaml +21 -0
  51. ultralytics/cfg/datasets/tiger-pose.yaml +25 -0
  52. ultralytics/cfg/datasets/xView.yaml +155 -0
  53. ultralytics/cfg/default.yaml +127 -0
  54. ultralytics/cfg/models/11/yolo11-cls-resnet18.yaml +17 -0
  55. ultralytics/cfg/models/11/yolo11-cls.yaml +33 -0
  56. ultralytics/cfg/models/11/yolo11-obb.yaml +50 -0
  57. ultralytics/cfg/models/11/yolo11-pose.yaml +51 -0
  58. ultralytics/cfg/models/11/yolo11-seg.yaml +50 -0
  59. ultralytics/cfg/models/11/yolo11.yaml +50 -0
  60. ultralytics/cfg/models/11/yoloe-11-seg.yaml +48 -0
  61. ultralytics/cfg/models/11/yoloe-11.yaml +48 -0
  62. ultralytics/cfg/models/12/yolo12-cls.yaml +32 -0
  63. ultralytics/cfg/models/12/yolo12-obb.yaml +48 -0
  64. ultralytics/cfg/models/12/yolo12-pose.yaml +49 -0
  65. ultralytics/cfg/models/12/yolo12-seg.yaml +48 -0
  66. ultralytics/cfg/models/12/yolo12.yaml +48 -0
  67. ultralytics/cfg/models/rt-detr/rtdetr-l.yaml +53 -0
  68. ultralytics/cfg/models/rt-detr/rtdetr-resnet101.yaml +45 -0
  69. ultralytics/cfg/models/rt-detr/rtdetr-resnet50.yaml +45 -0
  70. ultralytics/cfg/models/rt-detr/rtdetr-x.yaml +57 -0
  71. ultralytics/cfg/models/v10/yolov10b.yaml +45 -0
  72. ultralytics/cfg/models/v10/yolov10l.yaml +45 -0
  73. ultralytics/cfg/models/v10/yolov10m.yaml +45 -0
  74. ultralytics/cfg/models/v10/yolov10n.yaml +45 -0
  75. ultralytics/cfg/models/v10/yolov10s.yaml +45 -0
  76. ultralytics/cfg/models/v10/yolov10x.yaml +45 -0
  77. ultralytics/cfg/models/v3/yolov3-spp.yaml +49 -0
  78. ultralytics/cfg/models/v3/yolov3-tiny.yaml +40 -0
  79. ultralytics/cfg/models/v3/yolov3.yaml +49 -0
  80. ultralytics/cfg/models/v5/yolov5-p6.yaml +62 -0
  81. ultralytics/cfg/models/v5/yolov5.yaml +51 -0
  82. ultralytics/cfg/models/v6/yolov6.yaml +56 -0
  83. ultralytics/cfg/models/v8/yoloe-v8-seg.yaml +45 -0
  84. ultralytics/cfg/models/v8/yoloe-v8.yaml +45 -0
  85. ultralytics/cfg/models/v8/yolov8-cls-resnet101.yaml +28 -0
  86. ultralytics/cfg/models/v8/yolov8-cls-resnet50.yaml +28 -0
  87. ultralytics/cfg/models/v8/yolov8-cls.yaml +32 -0
  88. ultralytics/cfg/models/v8/yolov8-ghost-p2.yaml +58 -0
  89. ultralytics/cfg/models/v8/yolov8-ghost-p6.yaml +60 -0
  90. ultralytics/cfg/models/v8/yolov8-ghost.yaml +50 -0
  91. ultralytics/cfg/models/v8/yolov8-obb.yaml +49 -0
  92. ultralytics/cfg/models/v8/yolov8-p2.yaml +57 -0
  93. ultralytics/cfg/models/v8/yolov8-p6.yaml +59 -0
  94. ultralytics/cfg/models/v8/yolov8-pose-p6.yaml +60 -0
  95. ultralytics/cfg/models/v8/yolov8-pose.yaml +50 -0
  96. ultralytics/cfg/models/v8/yolov8-rtdetr.yaml +49 -0
  97. ultralytics/cfg/models/v8/yolov8-seg-p6.yaml +59 -0
  98. ultralytics/cfg/models/v8/yolov8-seg.yaml +49 -0
  99. ultralytics/cfg/models/v8/yolov8-world.yaml +51 -0
  100. ultralytics/cfg/models/v8/yolov8-worldv2.yaml +49 -0
  101. ultralytics/cfg/models/v8/yolov8.yaml +49 -0
  102. ultralytics/cfg/models/v9/yolov9c-seg.yaml +41 -0
  103. ultralytics/cfg/models/v9/yolov9c.yaml +41 -0
  104. ultralytics/cfg/models/v9/yolov9e-seg.yaml +64 -0
  105. ultralytics/cfg/models/v9/yolov9e.yaml +64 -0
  106. ultralytics/cfg/models/v9/yolov9m.yaml +41 -0
  107. ultralytics/cfg/models/v9/yolov9s.yaml +41 -0
  108. ultralytics/cfg/models/v9/yolov9t.yaml +41 -0
  109. ultralytics/cfg/trackers/botsort.yaml +22 -0
  110. ultralytics/cfg/trackers/bytetrack.yaml +14 -0
  111. ultralytics/data/__init__.py +26 -0
  112. ultralytics/data/annotator.py +66 -0
  113. ultralytics/data/augment.py +2945 -0
  114. ultralytics/data/base.py +438 -0
  115. ultralytics/data/build.py +258 -0
  116. ultralytics/data/converter.py +754 -0
  117. ultralytics/data/dataset.py +834 -0
  118. ultralytics/data/loaders.py +676 -0
  119. ultralytics/data/scripts/download_weights.sh +18 -0
  120. ultralytics/data/scripts/get_coco.sh +61 -0
  121. ultralytics/data/scripts/get_coco128.sh +18 -0
  122. ultralytics/data/scripts/get_imagenet.sh +52 -0
  123. ultralytics/data/split.py +125 -0
  124. ultralytics/data/split_dota.py +325 -0
  125. ultralytics/data/utils.py +777 -0
  126. ultralytics/engine/__init__.py +1 -0
  127. ultralytics/engine/exporter.py +1519 -0
  128. ultralytics/engine/model.py +1156 -0
  129. ultralytics/engine/predictor.py +502 -0
  130. ultralytics/engine/results.py +1840 -0
  131. ultralytics/engine/trainer.py +853 -0
  132. ultralytics/engine/tuner.py +243 -0
  133. ultralytics/engine/validator.py +377 -0
  134. ultralytics/hub/__init__.py +168 -0
  135. ultralytics/hub/auth.py +137 -0
  136. ultralytics/hub/google/__init__.py +176 -0
  137. ultralytics/hub/session.py +446 -0
  138. ultralytics/hub/utils.py +248 -0
  139. ultralytics/models/__init__.py +9 -0
  140. ultralytics/models/fastsam/__init__.py +7 -0
  141. ultralytics/models/fastsam/model.py +61 -0
  142. ultralytics/models/fastsam/predict.py +181 -0
  143. ultralytics/models/fastsam/utils.py +24 -0
  144. ultralytics/models/fastsam/val.py +40 -0
  145. ultralytics/models/nas/__init__.py +7 -0
  146. ultralytics/models/nas/model.py +102 -0
  147. ultralytics/models/nas/predict.py +58 -0
  148. ultralytics/models/nas/val.py +39 -0
  149. ultralytics/models/rtdetr/__init__.py +7 -0
  150. ultralytics/models/rtdetr/model.py +63 -0
  151. ultralytics/models/rtdetr/predict.py +84 -0
  152. ultralytics/models/rtdetr/train.py +85 -0
  153. ultralytics/models/rtdetr/val.py +191 -0
  154. ultralytics/models/sam/__init__.py +6 -0
  155. ultralytics/models/sam/amg.py +260 -0
  156. ultralytics/models/sam/build.py +358 -0
  157. ultralytics/models/sam/model.py +170 -0
  158. ultralytics/models/sam/modules/__init__.py +1 -0
  159. ultralytics/models/sam/modules/blocks.py +1129 -0
  160. ultralytics/models/sam/modules/decoders.py +515 -0
  161. ultralytics/models/sam/modules/encoders.py +854 -0
  162. ultralytics/models/sam/modules/memory_attention.py +299 -0
  163. ultralytics/models/sam/modules/sam.py +1006 -0
  164. ultralytics/models/sam/modules/tiny_encoder.py +1002 -0
  165. ultralytics/models/sam/modules/transformer.py +351 -0
  166. ultralytics/models/sam/modules/utils.py +394 -0
  167. ultralytics/models/sam/predict.py +1605 -0
  168. ultralytics/models/utils/__init__.py +1 -0
  169. ultralytics/models/utils/loss.py +455 -0
  170. ultralytics/models/utils/ops.py +268 -0
  171. ultralytics/models/yolo/__init__.py +7 -0
  172. ultralytics/models/yolo/classify/__init__.py +7 -0
  173. ultralytics/models/yolo/classify/predict.py +88 -0
  174. ultralytics/models/yolo/classify/train.py +233 -0
  175. ultralytics/models/yolo/classify/val.py +215 -0
  176. ultralytics/models/yolo/detect/__init__.py +7 -0
  177. ultralytics/models/yolo/detect/predict.py +124 -0
  178. ultralytics/models/yolo/detect/train.py +217 -0
  179. ultralytics/models/yolo/detect/val.py +451 -0
  180. ultralytics/models/yolo/model.py +354 -0
  181. ultralytics/models/yolo/obb/__init__.py +7 -0
  182. ultralytics/models/yolo/obb/predict.py +66 -0
  183. ultralytics/models/yolo/obb/train.py +81 -0
  184. ultralytics/models/yolo/obb/val.py +283 -0
  185. ultralytics/models/yolo/pose/__init__.py +7 -0
  186. ultralytics/models/yolo/pose/predict.py +79 -0
  187. ultralytics/models/yolo/pose/train.py +154 -0
  188. ultralytics/models/yolo/pose/val.py +394 -0
  189. ultralytics/models/yolo/segment/__init__.py +7 -0
  190. ultralytics/models/yolo/segment/predict.py +113 -0
  191. ultralytics/models/yolo/segment/train.py +123 -0
  192. ultralytics/models/yolo/segment/val.py +428 -0
  193. ultralytics/models/yolo/world/__init__.py +5 -0
  194. ultralytics/models/yolo/world/train.py +119 -0
  195. ultralytics/models/yolo/world/train_world.py +176 -0
  196. ultralytics/models/yolo/yoloe/__init__.py +22 -0
  197. ultralytics/models/yolo/yoloe/predict.py +169 -0
  198. ultralytics/models/yolo/yoloe/train.py +298 -0
  199. ultralytics/models/yolo/yoloe/train_seg.py +124 -0
  200. ultralytics/models/yolo/yoloe/val.py +191 -0
  201. ultralytics/nn/__init__.py +29 -0
  202. ultralytics/nn/autobackend.py +842 -0
  203. ultralytics/nn/modules/__init__.py +182 -0
  204. ultralytics/nn/modules/activation.py +53 -0
  205. ultralytics/nn/modules/block.py +1966 -0
  206. ultralytics/nn/modules/conv.py +712 -0
  207. ultralytics/nn/modules/head.py +880 -0
  208. ultralytics/nn/modules/transformer.py +713 -0
  209. ultralytics/nn/modules/utils.py +164 -0
  210. ultralytics/nn/tasks.py +1627 -0
  211. ultralytics/nn/text_model.py +351 -0
  212. ultralytics/solutions/__init__.py +41 -0
  213. ultralytics/solutions/ai_gym.py +116 -0
  214. ultralytics/solutions/analytics.py +252 -0
  215. ultralytics/solutions/config.py +106 -0
  216. ultralytics/solutions/distance_calculation.py +124 -0
  217. ultralytics/solutions/heatmap.py +127 -0
  218. ultralytics/solutions/instance_segmentation.py +84 -0
  219. ultralytics/solutions/object_blurrer.py +90 -0
  220. ultralytics/solutions/object_counter.py +195 -0
  221. ultralytics/solutions/object_cropper.py +84 -0
  222. ultralytics/solutions/parking_management.py +273 -0
  223. ultralytics/solutions/queue_management.py +93 -0
  224. ultralytics/solutions/region_counter.py +120 -0
  225. ultralytics/solutions/security_alarm.py +154 -0
  226. ultralytics/solutions/similarity_search.py +172 -0
  227. ultralytics/solutions/solutions.py +724 -0
  228. ultralytics/solutions/speed_estimation.py +110 -0
  229. ultralytics/solutions/streamlit_inference.py +196 -0
  230. ultralytics/solutions/templates/similarity-search.html +160 -0
  231. ultralytics/solutions/trackzone.py +88 -0
  232. ultralytics/solutions/vision_eye.py +68 -0
  233. ultralytics/trackers/__init__.py +7 -0
  234. ultralytics/trackers/basetrack.py +124 -0
  235. ultralytics/trackers/bot_sort.py +260 -0
  236. ultralytics/trackers/byte_tracker.py +480 -0
  237. ultralytics/trackers/track.py +125 -0
  238. ultralytics/trackers/utils/__init__.py +1 -0
  239. ultralytics/trackers/utils/gmc.py +376 -0
  240. ultralytics/trackers/utils/kalman_filter.py +493 -0
  241. ultralytics/trackers/utils/matching.py +157 -0
  242. ultralytics/utils/__init__.py +1435 -0
  243. ultralytics/utils/autobatch.py +106 -0
  244. ultralytics/utils/autodevice.py +174 -0
  245. ultralytics/utils/benchmarks.py +695 -0
  246. ultralytics/utils/callbacks/__init__.py +5 -0
  247. ultralytics/utils/callbacks/base.py +234 -0
  248. ultralytics/utils/callbacks/clearml.py +153 -0
  249. ultralytics/utils/callbacks/comet.py +552 -0
  250. ultralytics/utils/callbacks/dvc.py +205 -0
  251. ultralytics/utils/callbacks/hub.py +108 -0
  252. ultralytics/utils/callbacks/mlflow.py +138 -0
  253. ultralytics/utils/callbacks/neptune.py +140 -0
  254. ultralytics/utils/callbacks/raytune.py +43 -0
  255. ultralytics/utils/callbacks/tensorboard.py +132 -0
  256. ultralytics/utils/callbacks/wb.py +185 -0
  257. ultralytics/utils/checks.py +897 -0
  258. ultralytics/utils/dist.py +119 -0
  259. ultralytics/utils/downloads.py +499 -0
  260. ultralytics/utils/errors.py +43 -0
  261. ultralytics/utils/export.py +219 -0
  262. ultralytics/utils/files.py +221 -0
  263. ultralytics/utils/instance.py +499 -0
  264. ultralytics/utils/loss.py +813 -0
  265. ultralytics/utils/metrics.py +1356 -0
  266. ultralytics/utils/ops.py +885 -0
  267. ultralytics/utils/patches.py +143 -0
  268. ultralytics/utils/plotting.py +1011 -0
  269. ultralytics/utils/tal.py +416 -0
  270. ultralytics/utils/torch_utils.py +990 -0
  271. ultralytics/utils/triton.py +116 -0
  272. ultralytics/utils/tuner.py +159 -0
@@ -0,0 +1,219 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+ import json
4
+ from pathlib import Path
5
+
6
+ import torch
7
+
8
+ from ultralytics.utils import IS_JETSON, LOGGER
9
+
10
+
11
+ def export_onnx(
12
+ torch_model,
13
+ im,
14
+ onnx_file,
15
+ opset=14,
16
+ input_names=["images"],
17
+ output_names=["output0"],
18
+ dynamic=False,
19
+ ):
20
+ """
21
+ Exports a PyTorch model to ONNX format.
22
+
23
+ Args:
24
+ torch_model (torch.nn.Module): The PyTorch model to export.
25
+ im (torch.Tensor): Example input tensor for the model.
26
+ onnx_file (str): Path to save the exported ONNX file.
27
+ opset (int): ONNX opset version to use for export.
28
+ input_names (list): List of input tensor names.
29
+ output_names (list): List of output tensor names.
30
+ dynamic (bool | dict, optional): Whether to enable dynamic axes. Defaults to False.
31
+
32
+ Notes:
33
+ - Setting `do_constant_folding=True` may cause issues with DNN inference for torch>=1.12.
34
+ """
35
+ torch.onnx.export(
36
+ torch_model,
37
+ im,
38
+ onnx_file,
39
+ verbose=False,
40
+ opset_version=opset,
41
+ do_constant_folding=True, # WARNING: DNN inference with torch>=1.12 may require do_constant_folding=False
42
+ input_names=input_names,
43
+ output_names=output_names,
44
+ dynamic_axes=dynamic or None,
45
+ )
46
+
47
+
48
+ def export_engine(
49
+ onnx_file,
50
+ engine_file=None,
51
+ workspace=None,
52
+ half=False,
53
+ int8=False,
54
+ dynamic=False,
55
+ shape=(1, 3, 640, 640),
56
+ dla=None,
57
+ dataset=None,
58
+ metadata=None,
59
+ verbose=False,
60
+ prefix="",
61
+ ):
62
+ """
63
+ Exports a YOLO model to TensorRT engine format.
64
+
65
+ Args:
66
+ onnx_file (str): Path to the ONNX file to be converted.
67
+ engine_file (str, optional): Path to save the generated TensorRT engine file.
68
+ workspace (int, optional): Workspace size in GB for TensorRT. Defaults to None.
69
+ half (bool, optional): Enable FP16 precision. Defaults to False.
70
+ int8 (bool, optional): Enable INT8 precision. Defaults to False.
71
+ dynamic (bool, optional): Enable dynamic input shapes. Defaults to False.
72
+ shape (tuple, optional): Input shape (batch, channels, height, width). Defaults to (1, 3, 640, 640).
73
+ dla (int, optional): DLA core to use (Jetson devices only). Defaults to None.
74
+ dataset (ultralytics.data.build.InfiniteDataLoader, optional): Dataset for INT8 calibration. Defaults to None.
75
+ metadata (dict, optional): Metadata to include in the engine file. Defaults to None.
76
+ verbose (bool, optional): Enable verbose logging. Defaults to False.
77
+ prefix (str, optional): Prefix for log messages. Defaults to "".
78
+
79
+ Raises:
80
+ ValueError: If DLA is enabled on non-Jetson devices or required precision is not set.
81
+ RuntimeError: If the ONNX file cannot be parsed.
82
+
83
+ Notes:
84
+ - TensorRT version compatibility is handled for workspace size and engine building.
85
+ - INT8 calibration requires a dataset and generates a calibration cache.
86
+ - Metadata is serialized and written to the engine file if provided.
87
+ """
88
+ import tensorrt as trt # noqa
89
+
90
+ engine_file = engine_file or Path(onnx_file).with_suffix(".engine")
91
+
92
+ logger = trt.Logger(trt.Logger.INFO)
93
+ if verbose:
94
+ logger.min_severity = trt.Logger.Severity.VERBOSE
95
+
96
+ # Engine builder
97
+ builder = trt.Builder(logger)
98
+ config = builder.create_builder_config()
99
+ workspace = int((workspace or 0) * (1 << 30))
100
+ is_trt10 = int(trt.__version__.split(".")[0]) >= 10 # is TensorRT >= 10
101
+ if is_trt10 and workspace > 0:
102
+ config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, workspace)
103
+ elif workspace > 0: # TensorRT versions 7, 8
104
+ config.max_workspace_size = workspace
105
+ flag = 1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)
106
+ network = builder.create_network(flag)
107
+ half = builder.platform_has_fast_fp16 and half
108
+ int8 = builder.platform_has_fast_int8 and int8
109
+
110
+ # Optionally switch to DLA if enabled
111
+ if dla is not None:
112
+ if not IS_JETSON:
113
+ raise ValueError("DLA is only available on NVIDIA Jetson devices")
114
+ LOGGER.info(f"{prefix} enabling DLA on core {dla}...")
115
+ if not half and not int8:
116
+ raise ValueError(
117
+ "DLA requires either 'half=True' (FP16) or 'int8=True' (INT8) to be enabled. Please enable one of them and try again."
118
+ )
119
+ config.default_device_type = trt.DeviceType.DLA
120
+ config.DLA_core = int(dla)
121
+ config.set_flag(trt.BuilderFlag.GPU_FALLBACK)
122
+
123
+ # Read ONNX file
124
+ parser = trt.OnnxParser(network, logger)
125
+ if not parser.parse_from_file(onnx_file):
126
+ raise RuntimeError(f"failed to load ONNX file: {onnx_file}")
127
+
128
+ # Network inputs
129
+ inputs = [network.get_input(i) for i in range(network.num_inputs)]
130
+ outputs = [network.get_output(i) for i in range(network.num_outputs)]
131
+ for inp in inputs:
132
+ LOGGER.info(f'{prefix} input "{inp.name}" with shape{inp.shape} {inp.dtype}')
133
+ for out in outputs:
134
+ LOGGER.info(f'{prefix} output "{out.name}" with shape{out.shape} {out.dtype}')
135
+
136
+ if dynamic:
137
+ if shape[0] <= 1:
138
+ LOGGER.warning(f"{prefix} 'dynamic=True' model requires max batch size, i.e. 'batch=16'")
139
+ profile = builder.create_optimization_profile()
140
+ min_shape = (1, shape[1], 32, 32) # minimum input shape
141
+ max_shape = (*shape[:2], *(int(max(2, workspace or 2) * d) for d in shape[2:])) # max input shape
142
+ for inp in inputs:
143
+ profile.set_shape(inp.name, min=min_shape, opt=shape, max=max_shape)
144
+ config.add_optimization_profile(profile)
145
+
146
+ LOGGER.info(f"{prefix} building {'INT8' if int8 else 'FP' + ('16' if half else '32')} engine as {engine_file}")
147
+ if int8:
148
+ config.set_flag(trt.BuilderFlag.INT8)
149
+ config.set_calibration_profile(profile)
150
+ config.profiling_verbosity = trt.ProfilingVerbosity.DETAILED
151
+
152
+ class EngineCalibrator(trt.IInt8Calibrator):
153
+ """
154
+ Custom INT8 calibrator for TensorRT.
155
+
156
+ Args:
157
+ dataset (object): Dataset for calibration.
158
+ batch (int): Batch size for calibration.
159
+ cache (str, optional): Path to save the calibration cache. Defaults to "".
160
+ """
161
+
162
+ def __init__(
163
+ self,
164
+ dataset, # ultralytics.data.build.InfiniteDataLoader
165
+ cache: str = "",
166
+ ) -> None:
167
+ trt.IInt8Calibrator.__init__(self)
168
+ self.dataset = dataset
169
+ self.data_iter = iter(dataset)
170
+ self.algo = trt.CalibrationAlgoType.MINMAX_CALIBRATION
171
+ self.batch = dataset.batch_size
172
+ self.cache = Path(cache)
173
+
174
+ def get_algorithm(self) -> trt.CalibrationAlgoType:
175
+ """Get the calibration algorithm to use."""
176
+ return self.algo
177
+
178
+ def get_batch_size(self) -> int:
179
+ """Get the batch size to use for calibration."""
180
+ return self.batch or 1
181
+
182
+ def get_batch(self, names) -> list:
183
+ """Get the next batch to use for calibration, as a list of device memory pointers."""
184
+ try:
185
+ im0s = next(self.data_iter)["img"] / 255.0
186
+ im0s = im0s.to("cuda") if im0s.device.type == "cpu" else im0s
187
+ return [int(im0s.data_ptr())]
188
+ except StopIteration:
189
+ # Return [] or None, signal to TensorRT there is no calibration data remaining
190
+ return None
191
+
192
+ def read_calibration_cache(self) -> bytes:
193
+ """Use existing cache instead of calibrating again, otherwise, implicitly return None."""
194
+ if self.cache.exists() and self.cache.suffix == ".cache":
195
+ return self.cache.read_bytes()
196
+
197
+ def write_calibration_cache(self, cache) -> None:
198
+ """Write calibration cache to disk."""
199
+ _ = self.cache.write_bytes(cache)
200
+
201
+ # Load dataset w/ builder (for batching) and calibrate
202
+ config.int8_calibrator = EngineCalibrator(
203
+ dataset=dataset,
204
+ cache=str(Path(onnx_file).with_suffix(".cache")),
205
+ )
206
+
207
+ elif half:
208
+ config.set_flag(trt.BuilderFlag.FP16)
209
+
210
+ # Write file
211
+ build = builder.build_serialized_network if is_trt10 else builder.build_engine
212
+ with build(network, config) as engine, open(engine_file, "wb") as t:
213
+ # Metadata
214
+ if metadata is not None:
215
+ meta = json.dumps(metadata)
216
+ t.write(len(meta).to_bytes(4, byteorder="little", signed=True))
217
+ t.write(meta.encode())
218
+ # Model
219
+ t.write(engine if is_trt10 else engine.serialize())
@@ -0,0 +1,221 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+ import contextlib
4
+ import glob
5
+ import os
6
+ import shutil
7
+ import tempfile
8
+ from contextlib import contextmanager
9
+ from datetime import datetime
10
+ from pathlib import Path
11
+
12
+
13
+ class WorkingDirectory(contextlib.ContextDecorator):
14
+ """
15
+ A context manager and decorator for temporarily changing the working directory.
16
+
17
+ This class allows for the temporary change of the working directory using a context manager or decorator.
18
+ It ensures that the original working directory is restored after the context or decorated function completes.
19
+
20
+ Attributes:
21
+ dir (Path | str): The new directory to switch to.
22
+ cwd (Path): The original current working directory before the switch.
23
+
24
+ Methods:
25
+ __enter__: Changes the current directory to the specified directory.
26
+ __exit__: Restores the original working directory on context exit.
27
+
28
+ Examples:
29
+ Using as a context manager:
30
+ >>> with WorkingDirectory('/path/to/new/dir'):
31
+ >>> # Perform operations in the new directory
32
+ >>> pass
33
+
34
+ Using as a decorator:
35
+ >>> @WorkingDirectory('/path/to/new/dir')
36
+ >>> def some_function():
37
+ >>> # Perform operations in the new directory
38
+ >>> pass
39
+ """
40
+
41
+ def __init__(self, new_dir):
42
+ """Sets the working directory to 'new_dir' upon instantiation for use with context managers or decorators."""
43
+ self.dir = new_dir # new dir
44
+ self.cwd = Path.cwd().resolve() # current dir
45
+
46
+ def __enter__(self):
47
+ """Changes the current working directory to the specified directory upon entering the context."""
48
+ os.chdir(self.dir)
49
+
50
+ def __exit__(self, exc_type, exc_val, exc_tb): # noqa
51
+ """Restores the original working directory when exiting the context."""
52
+ os.chdir(self.cwd)
53
+
54
+
55
+ @contextmanager
56
+ def spaces_in_path(path):
57
+ """
58
+ Context manager to handle paths with spaces in their names.
59
+
60
+ If a path contains spaces, it replaces them with underscores, copies the file/directory to the new path, executes
61
+ the context code block, then copies the file/directory back to its original location.
62
+
63
+ Args:
64
+ path (str | Path): The original path that may contain spaces.
65
+
66
+ Yields:
67
+ (Path | str): Temporary path with spaces replaced by underscores if spaces were present, otherwise the original path.
68
+
69
+ Examples:
70
+ >>> with spaces_in_path('/path/with spaces') as new_path:
71
+ >>> # Your code here
72
+ >>> pass
73
+ """
74
+ # If path has spaces, replace them with underscores
75
+ if " " in str(path):
76
+ string = isinstance(path, str) # input type
77
+ path = Path(path)
78
+
79
+ # Create a temporary directory and construct the new path
80
+ with tempfile.TemporaryDirectory() as tmp_dir:
81
+ tmp_path = Path(tmp_dir) / path.name.replace(" ", "_")
82
+
83
+ # Copy file/directory
84
+ if path.is_dir():
85
+ # tmp_path.mkdir(parents=True, exist_ok=True)
86
+ shutil.copytree(path, tmp_path)
87
+ elif path.is_file():
88
+ tmp_path.parent.mkdir(parents=True, exist_ok=True)
89
+ shutil.copy2(path, tmp_path)
90
+
91
+ try:
92
+ # Yield the temporary path
93
+ yield str(tmp_path) if string else tmp_path
94
+
95
+ finally:
96
+ # Copy file/directory back
97
+ if tmp_path.is_dir():
98
+ shutil.copytree(tmp_path, path, dirs_exist_ok=True)
99
+ elif tmp_path.is_file():
100
+ shutil.copy2(tmp_path, path) # Copy back the file
101
+
102
+ else:
103
+ # If there are no spaces, just yield the original path
104
+ yield path
105
+
106
+
107
+ def increment_path(path, exist_ok=False, sep="", mkdir=False):
108
+ """
109
+ Increment a file or directory path, i.e., runs/exp --> runs/exp{sep}2, runs/exp{sep}3, ... etc.
110
+
111
+ If the path exists and `exist_ok` is not True, the path will be incremented by appending a number and `sep` to
112
+ the end of the path. If the path is a file, the file extension will be preserved. If the path is a directory, the
113
+ number will be appended directly to the end of the path.
114
+
115
+ Args:
116
+ path (str | Path): Path to increment.
117
+ exist_ok (bool): If True, the path will not be incremented and returned as-is.
118
+ sep (str): Separator to use between the path and the incrementation number.
119
+ mkdir (bool): Create a directory if it does not exist.
120
+
121
+ Returns:
122
+ (Path): Incremented path.
123
+
124
+ Examples:
125
+ Increment a directory path:
126
+ >>> from pathlib import Path
127
+ >>> path = Path("runs/exp")
128
+ >>> new_path = increment_path(path)
129
+ >>> print(new_path)
130
+ runs/exp2
131
+
132
+ Increment a file path:
133
+ >>> path = Path("runs/exp/results.txt")
134
+ >>> new_path = increment_path(path)
135
+ >>> print(new_path)
136
+ runs/exp/results2.txt
137
+ """
138
+ path = Path(path) # os-agnostic
139
+ if path.exists() and not exist_ok:
140
+ path, suffix = (path.with_suffix(""), path.suffix) if path.is_file() else (path, "")
141
+
142
+ # Method 1
143
+ for n in range(2, 9999):
144
+ p = f"{path}{sep}{n}{suffix}" # increment path
145
+ if not os.path.exists(p):
146
+ break
147
+ path = Path(p)
148
+
149
+ if mkdir:
150
+ path.mkdir(parents=True, exist_ok=True) # make directory
151
+
152
+ return path
153
+
154
+
155
+ def file_age(path=__file__):
156
+ """Return days since the last modification of the specified file."""
157
+ dt = datetime.now() - datetime.fromtimestamp(Path(path).stat().st_mtime) # delta
158
+ return dt.days # + dt.seconds / 86400 # fractional days
159
+
160
+
161
+ def file_date(path=__file__):
162
+ """Returns the file modification date in 'YYYY-M-D' format."""
163
+ t = datetime.fromtimestamp(Path(path).stat().st_mtime)
164
+ return f"{t.year}-{t.month}-{t.day}"
165
+
166
+
167
+ def file_size(path):
168
+ """Returns the size of a file or directory in megabytes (MB)."""
169
+ if isinstance(path, (str, Path)):
170
+ mb = 1 << 20 # bytes to MiB (1024 ** 2)
171
+ path = Path(path)
172
+ if path.is_file():
173
+ return path.stat().st_size / mb
174
+ elif path.is_dir():
175
+ return sum(f.stat().st_size for f in path.glob("**/*") if f.is_file()) / mb
176
+ return 0.0
177
+
178
+
179
+ def get_latest_run(search_dir="."):
180
+ """Returns the path to the most recent 'last.pt' file in the specified directory for resuming training."""
181
+ last_list = glob.glob(f"{search_dir}/**/last*.pt", recursive=True)
182
+ return max(last_list, key=os.path.getctime) if last_list else ""
183
+
184
+
185
+ def update_models(model_names=("yolo11n.pt",), source_dir=Path("."), update_names=False):
186
+ """
187
+ Update and re-save specified YOLO models in an 'updated_models' subdirectory.
188
+
189
+ Args:
190
+ model_names (Tuple[str, ...]): Model filenames to update.
191
+ source_dir (Path): Directory containing models and target subdirectory.
192
+ update_names (bool): Update model names from a data YAML.
193
+
194
+ Examples:
195
+ Update specified YOLO models and save them in 'updated_models' subdirectory:
196
+ >>> from ultralytics.utils.files import update_models
197
+ >>> model_names = ("yolo11n.pt", "yolov8s.pt")
198
+ >>> update_models(model_names, source_dir=Path("/models"), update_names=True)
199
+ """
200
+ from ultralytics import YOLO
201
+ from ultralytics.nn.autobackend import default_class_names
202
+
203
+ target_dir = source_dir / "updated_models"
204
+ target_dir.mkdir(parents=True, exist_ok=True) # Ensure target directory exists
205
+
206
+ for model_name in model_names:
207
+ model_path = source_dir / model_name
208
+ print(f"Loading model from {model_path}")
209
+
210
+ # Load model
211
+ model = YOLO(model_path)
212
+ model.half()
213
+ if update_names: # update model names from a dataset YAML
214
+ model.model.names = default_class_names("coco8.yaml")
215
+
216
+ # Define new save path
217
+ save_path = target_dir / model_name
218
+
219
+ # Save model using model.save()
220
+ print(f"Re-saving {model_name} model to {save_path}")
221
+ model.save(save_path)