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.
Files changed (298) hide show
  1. tests/__init__.py +23 -0
  2. tests/conftest.py +59 -0
  3. tests/test_cli.py +131 -0
  4. tests/test_cuda.py +216 -0
  5. tests/test_engine.py +157 -0
  6. tests/test_exports.py +309 -0
  7. tests/test_integrations.py +151 -0
  8. tests/test_python.py +777 -0
  9. tests/test_solutions.py +371 -0
  10. ultralytics/__init__.py +48 -0
  11. ultralytics/assets/bus.jpg +0 -0
  12. ultralytics/assets/zidane.jpg +0 -0
  13. ultralytics/cfg/__init__.py +1026 -0
  14. ultralytics/cfg/datasets/Argoverse.yaml +78 -0
  15. ultralytics/cfg/datasets/DOTAv1.5.yaml +37 -0
  16. ultralytics/cfg/datasets/DOTAv1.yaml +36 -0
  17. ultralytics/cfg/datasets/GlobalWheat2020.yaml +68 -0
  18. ultralytics/cfg/datasets/HomeObjects-3K.yaml +32 -0
  19. ultralytics/cfg/datasets/ImageNet.yaml +2025 -0
  20. ultralytics/cfg/datasets/Objects365.yaml +447 -0
  21. ultralytics/cfg/datasets/SKU-110K.yaml +58 -0
  22. ultralytics/cfg/datasets/VOC.yaml +102 -0
  23. ultralytics/cfg/datasets/VisDrone.yaml +87 -0
  24. ultralytics/cfg/datasets/african-wildlife.yaml +25 -0
  25. ultralytics/cfg/datasets/brain-tumor.yaml +22 -0
  26. ultralytics/cfg/datasets/carparts-seg.yaml +44 -0
  27. ultralytics/cfg/datasets/coco-pose.yaml +64 -0
  28. ultralytics/cfg/datasets/coco.yaml +118 -0
  29. ultralytics/cfg/datasets/coco128-seg.yaml +101 -0
  30. ultralytics/cfg/datasets/coco128.yaml +101 -0
  31. ultralytics/cfg/datasets/coco8-grayscale.yaml +103 -0
  32. ultralytics/cfg/datasets/coco8-multispectral.yaml +104 -0
  33. ultralytics/cfg/datasets/coco8-pose.yaml +47 -0
  34. ultralytics/cfg/datasets/coco8-seg.yaml +101 -0
  35. ultralytics/cfg/datasets/coco8.yaml +101 -0
  36. ultralytics/cfg/datasets/construction-ppe.yaml +32 -0
  37. ultralytics/cfg/datasets/crack-seg.yaml +22 -0
  38. ultralytics/cfg/datasets/dog-pose.yaml +52 -0
  39. ultralytics/cfg/datasets/dota8-multispectral.yaml +38 -0
  40. ultralytics/cfg/datasets/dota8.yaml +35 -0
  41. ultralytics/cfg/datasets/hand-keypoints.yaml +50 -0
  42. ultralytics/cfg/datasets/kitti.yaml +27 -0
  43. ultralytics/cfg/datasets/lvis.yaml +1240 -0
  44. ultralytics/cfg/datasets/medical-pills.yaml +21 -0
  45. ultralytics/cfg/datasets/open-images-v7.yaml +663 -0
  46. ultralytics/cfg/datasets/package-seg.yaml +22 -0
  47. ultralytics/cfg/datasets/signature.yaml +21 -0
  48. ultralytics/cfg/datasets/tiger-pose.yaml +41 -0
  49. ultralytics/cfg/datasets/xView.yaml +155 -0
  50. ultralytics/cfg/default.yaml +130 -0
  51. ultralytics/cfg/models/11/yolo11-cls-resnet18.yaml +17 -0
  52. ultralytics/cfg/models/11/yolo11-cls.yaml +33 -0
  53. ultralytics/cfg/models/11/yolo11-obb.yaml +50 -0
  54. ultralytics/cfg/models/11/yolo11-pose.yaml +51 -0
  55. ultralytics/cfg/models/11/yolo11-seg.yaml +50 -0
  56. ultralytics/cfg/models/11/yolo11.yaml +50 -0
  57. ultralytics/cfg/models/11/yoloe-11-seg.yaml +48 -0
  58. ultralytics/cfg/models/11/yoloe-11.yaml +48 -0
  59. ultralytics/cfg/models/12/yolo12-cls.yaml +32 -0
  60. ultralytics/cfg/models/12/yolo12-obb.yaml +48 -0
  61. ultralytics/cfg/models/12/yolo12-pose.yaml +49 -0
  62. ultralytics/cfg/models/12/yolo12-seg.yaml +48 -0
  63. ultralytics/cfg/models/12/yolo12.yaml +48 -0
  64. ultralytics/cfg/models/rt-detr/rtdetr-l.yaml +53 -0
  65. ultralytics/cfg/models/rt-detr/rtdetr-resnet101.yaml +45 -0
  66. ultralytics/cfg/models/rt-detr/rtdetr-resnet50.yaml +45 -0
  67. ultralytics/cfg/models/rt-detr/rtdetr-x.yaml +57 -0
  68. ultralytics/cfg/models/v10/yolov10b.yaml +45 -0
  69. ultralytics/cfg/models/v10/yolov10l.yaml +45 -0
  70. ultralytics/cfg/models/v10/yolov10m.yaml +45 -0
  71. ultralytics/cfg/models/v10/yolov10n.yaml +45 -0
  72. ultralytics/cfg/models/v10/yolov10s.yaml +45 -0
  73. ultralytics/cfg/models/v10/yolov10x.yaml +45 -0
  74. ultralytics/cfg/models/v3/yolov3-spp.yaml +49 -0
  75. ultralytics/cfg/models/v3/yolov3-tiny.yaml +40 -0
  76. ultralytics/cfg/models/v3/yolov3.yaml +49 -0
  77. ultralytics/cfg/models/v5/yolov5-p6.yaml +62 -0
  78. ultralytics/cfg/models/v5/yolov5.yaml +51 -0
  79. ultralytics/cfg/models/v6/yolov6.yaml +56 -0
  80. ultralytics/cfg/models/v8/yoloe-v8-seg.yaml +48 -0
  81. ultralytics/cfg/models/v8/yoloe-v8.yaml +48 -0
  82. ultralytics/cfg/models/v8/yolov8-cls-resnet101.yaml +28 -0
  83. ultralytics/cfg/models/v8/yolov8-cls-resnet50.yaml +28 -0
  84. ultralytics/cfg/models/v8/yolov8-cls.yaml +32 -0
  85. ultralytics/cfg/models/v8/yolov8-ghost-p2.yaml +58 -0
  86. ultralytics/cfg/models/v8/yolov8-ghost-p6.yaml +60 -0
  87. ultralytics/cfg/models/v8/yolov8-ghost.yaml +50 -0
  88. ultralytics/cfg/models/v8/yolov8-obb.yaml +49 -0
  89. ultralytics/cfg/models/v8/yolov8-p2.yaml +57 -0
  90. ultralytics/cfg/models/v8/yolov8-p6.yaml +59 -0
  91. ultralytics/cfg/models/v8/yolov8-pose-p6.yaml +60 -0
  92. ultralytics/cfg/models/v8/yolov8-pose.yaml +50 -0
  93. ultralytics/cfg/models/v8/yolov8-rtdetr.yaml +49 -0
  94. ultralytics/cfg/models/v8/yolov8-seg-p6.yaml +59 -0
  95. ultralytics/cfg/models/v8/yolov8-seg.yaml +49 -0
  96. ultralytics/cfg/models/v8/yolov8-world.yaml +51 -0
  97. ultralytics/cfg/models/v8/yolov8-worldv2.yaml +49 -0
  98. ultralytics/cfg/models/v8/yolov8.yaml +49 -0
  99. ultralytics/cfg/models/v9/yolov9c-seg.yaml +41 -0
  100. ultralytics/cfg/models/v9/yolov9c.yaml +41 -0
  101. ultralytics/cfg/models/v9/yolov9e-seg.yaml +64 -0
  102. ultralytics/cfg/models/v9/yolov9e.yaml +64 -0
  103. ultralytics/cfg/models/v9/yolov9m.yaml +41 -0
  104. ultralytics/cfg/models/v9/yolov9s.yaml +41 -0
  105. ultralytics/cfg/models/v9/yolov9t.yaml +41 -0
  106. ultralytics/cfg/trackers/botsort.yaml +21 -0
  107. ultralytics/cfg/trackers/bytetrack.yaml +12 -0
  108. ultralytics/data/__init__.py +26 -0
  109. ultralytics/data/annotator.py +66 -0
  110. ultralytics/data/augment.py +2801 -0
  111. ultralytics/data/base.py +435 -0
  112. ultralytics/data/build.py +437 -0
  113. ultralytics/data/converter.py +855 -0
  114. ultralytics/data/dataset.py +834 -0
  115. ultralytics/data/loaders.py +704 -0
  116. ultralytics/data/scripts/download_weights.sh +18 -0
  117. ultralytics/data/scripts/get_coco.sh +61 -0
  118. ultralytics/data/scripts/get_coco128.sh +18 -0
  119. ultralytics/data/scripts/get_imagenet.sh +52 -0
  120. ultralytics/data/split.py +138 -0
  121. ultralytics/data/split_dota.py +344 -0
  122. ultralytics/data/utils.py +798 -0
  123. ultralytics/engine/__init__.py +1 -0
  124. ultralytics/engine/exporter.py +1574 -0
  125. ultralytics/engine/model.py +1124 -0
  126. ultralytics/engine/predictor.py +508 -0
  127. ultralytics/engine/results.py +1522 -0
  128. ultralytics/engine/trainer.py +974 -0
  129. ultralytics/engine/tuner.py +448 -0
  130. ultralytics/engine/validator.py +384 -0
  131. ultralytics/hub/__init__.py +166 -0
  132. ultralytics/hub/auth.py +151 -0
  133. ultralytics/hub/google/__init__.py +174 -0
  134. ultralytics/hub/session.py +422 -0
  135. ultralytics/hub/utils.py +162 -0
  136. ultralytics/models/__init__.py +9 -0
  137. ultralytics/models/fastsam/__init__.py +7 -0
  138. ultralytics/models/fastsam/model.py +79 -0
  139. ultralytics/models/fastsam/predict.py +169 -0
  140. ultralytics/models/fastsam/utils.py +23 -0
  141. ultralytics/models/fastsam/val.py +38 -0
  142. ultralytics/models/nas/__init__.py +7 -0
  143. ultralytics/models/nas/model.py +98 -0
  144. ultralytics/models/nas/predict.py +56 -0
  145. ultralytics/models/nas/val.py +38 -0
  146. ultralytics/models/rtdetr/__init__.py +7 -0
  147. ultralytics/models/rtdetr/model.py +63 -0
  148. ultralytics/models/rtdetr/predict.py +88 -0
  149. ultralytics/models/rtdetr/train.py +89 -0
  150. ultralytics/models/rtdetr/val.py +216 -0
  151. ultralytics/models/sam/__init__.py +25 -0
  152. ultralytics/models/sam/amg.py +275 -0
  153. ultralytics/models/sam/build.py +365 -0
  154. ultralytics/models/sam/build_sam3.py +377 -0
  155. ultralytics/models/sam/model.py +169 -0
  156. ultralytics/models/sam/modules/__init__.py +1 -0
  157. ultralytics/models/sam/modules/blocks.py +1067 -0
  158. ultralytics/models/sam/modules/decoders.py +495 -0
  159. ultralytics/models/sam/modules/encoders.py +794 -0
  160. ultralytics/models/sam/modules/memory_attention.py +298 -0
  161. ultralytics/models/sam/modules/sam.py +1160 -0
  162. ultralytics/models/sam/modules/tiny_encoder.py +979 -0
  163. ultralytics/models/sam/modules/transformer.py +344 -0
  164. ultralytics/models/sam/modules/utils.py +512 -0
  165. ultralytics/models/sam/predict.py +3940 -0
  166. ultralytics/models/sam/sam3/__init__.py +3 -0
  167. ultralytics/models/sam/sam3/decoder.py +546 -0
  168. ultralytics/models/sam/sam3/encoder.py +529 -0
  169. ultralytics/models/sam/sam3/geometry_encoders.py +415 -0
  170. ultralytics/models/sam/sam3/maskformer_segmentation.py +286 -0
  171. ultralytics/models/sam/sam3/model_misc.py +199 -0
  172. ultralytics/models/sam/sam3/necks.py +129 -0
  173. ultralytics/models/sam/sam3/sam3_image.py +339 -0
  174. ultralytics/models/sam/sam3/text_encoder_ve.py +307 -0
  175. ultralytics/models/sam/sam3/vitdet.py +547 -0
  176. ultralytics/models/sam/sam3/vl_combiner.py +160 -0
  177. ultralytics/models/utils/__init__.py +1 -0
  178. ultralytics/models/utils/loss.py +466 -0
  179. ultralytics/models/utils/ops.py +315 -0
  180. ultralytics/models/yolo/__init__.py +7 -0
  181. ultralytics/models/yolo/classify/__init__.py +7 -0
  182. ultralytics/models/yolo/classify/predict.py +90 -0
  183. ultralytics/models/yolo/classify/train.py +202 -0
  184. ultralytics/models/yolo/classify/val.py +216 -0
  185. ultralytics/models/yolo/detect/__init__.py +7 -0
  186. ultralytics/models/yolo/detect/predict.py +122 -0
  187. ultralytics/models/yolo/detect/train.py +227 -0
  188. ultralytics/models/yolo/detect/val.py +507 -0
  189. ultralytics/models/yolo/model.py +430 -0
  190. ultralytics/models/yolo/obb/__init__.py +7 -0
  191. ultralytics/models/yolo/obb/predict.py +56 -0
  192. ultralytics/models/yolo/obb/train.py +79 -0
  193. ultralytics/models/yolo/obb/val.py +302 -0
  194. ultralytics/models/yolo/pose/__init__.py +7 -0
  195. ultralytics/models/yolo/pose/predict.py +65 -0
  196. ultralytics/models/yolo/pose/train.py +110 -0
  197. ultralytics/models/yolo/pose/val.py +248 -0
  198. ultralytics/models/yolo/segment/__init__.py +7 -0
  199. ultralytics/models/yolo/segment/predict.py +109 -0
  200. ultralytics/models/yolo/segment/train.py +69 -0
  201. ultralytics/models/yolo/segment/val.py +307 -0
  202. ultralytics/models/yolo/world/__init__.py +5 -0
  203. ultralytics/models/yolo/world/train.py +173 -0
  204. ultralytics/models/yolo/world/train_world.py +178 -0
  205. ultralytics/models/yolo/yoloe/__init__.py +22 -0
  206. ultralytics/models/yolo/yoloe/predict.py +162 -0
  207. ultralytics/models/yolo/yoloe/train.py +287 -0
  208. ultralytics/models/yolo/yoloe/train_seg.py +122 -0
  209. ultralytics/models/yolo/yoloe/val.py +206 -0
  210. ultralytics/nn/__init__.py +27 -0
  211. ultralytics/nn/autobackend.py +958 -0
  212. ultralytics/nn/modules/__init__.py +182 -0
  213. ultralytics/nn/modules/activation.py +54 -0
  214. ultralytics/nn/modules/block.py +1947 -0
  215. ultralytics/nn/modules/conv.py +669 -0
  216. ultralytics/nn/modules/head.py +1183 -0
  217. ultralytics/nn/modules/transformer.py +793 -0
  218. ultralytics/nn/modules/utils.py +159 -0
  219. ultralytics/nn/tasks.py +1768 -0
  220. ultralytics/nn/text_model.py +356 -0
  221. ultralytics/py.typed +1 -0
  222. ultralytics/solutions/__init__.py +41 -0
  223. ultralytics/solutions/ai_gym.py +108 -0
  224. ultralytics/solutions/analytics.py +264 -0
  225. ultralytics/solutions/config.py +107 -0
  226. ultralytics/solutions/distance_calculation.py +123 -0
  227. ultralytics/solutions/heatmap.py +125 -0
  228. ultralytics/solutions/instance_segmentation.py +86 -0
  229. ultralytics/solutions/object_blurrer.py +89 -0
  230. ultralytics/solutions/object_counter.py +190 -0
  231. ultralytics/solutions/object_cropper.py +87 -0
  232. ultralytics/solutions/parking_management.py +280 -0
  233. ultralytics/solutions/queue_management.py +93 -0
  234. ultralytics/solutions/region_counter.py +133 -0
  235. ultralytics/solutions/security_alarm.py +151 -0
  236. ultralytics/solutions/similarity_search.py +219 -0
  237. ultralytics/solutions/solutions.py +828 -0
  238. ultralytics/solutions/speed_estimation.py +114 -0
  239. ultralytics/solutions/streamlit_inference.py +260 -0
  240. ultralytics/solutions/templates/similarity-search.html +156 -0
  241. ultralytics/solutions/trackzone.py +88 -0
  242. ultralytics/solutions/vision_eye.py +67 -0
  243. ultralytics/trackers/__init__.py +7 -0
  244. ultralytics/trackers/basetrack.py +115 -0
  245. ultralytics/trackers/bot_sort.py +257 -0
  246. ultralytics/trackers/byte_tracker.py +469 -0
  247. ultralytics/trackers/track.py +116 -0
  248. ultralytics/trackers/utils/__init__.py +1 -0
  249. ultralytics/trackers/utils/gmc.py +339 -0
  250. ultralytics/trackers/utils/kalman_filter.py +482 -0
  251. ultralytics/trackers/utils/matching.py +154 -0
  252. ultralytics/utils/__init__.py +1450 -0
  253. ultralytics/utils/autobatch.py +118 -0
  254. ultralytics/utils/autodevice.py +205 -0
  255. ultralytics/utils/benchmarks.py +728 -0
  256. ultralytics/utils/callbacks/__init__.py +5 -0
  257. ultralytics/utils/callbacks/base.py +233 -0
  258. ultralytics/utils/callbacks/clearml.py +146 -0
  259. ultralytics/utils/callbacks/comet.py +625 -0
  260. ultralytics/utils/callbacks/dvc.py +197 -0
  261. ultralytics/utils/callbacks/hub.py +110 -0
  262. ultralytics/utils/callbacks/mlflow.py +134 -0
  263. ultralytics/utils/callbacks/neptune.py +126 -0
  264. ultralytics/utils/callbacks/platform.py +73 -0
  265. ultralytics/utils/callbacks/raytune.py +42 -0
  266. ultralytics/utils/callbacks/tensorboard.py +123 -0
  267. ultralytics/utils/callbacks/wb.py +188 -0
  268. ultralytics/utils/checks.py +998 -0
  269. ultralytics/utils/cpu.py +85 -0
  270. ultralytics/utils/dist.py +123 -0
  271. ultralytics/utils/downloads.py +529 -0
  272. ultralytics/utils/errors.py +35 -0
  273. ultralytics/utils/events.py +113 -0
  274. ultralytics/utils/export/__init__.py +7 -0
  275. ultralytics/utils/export/engine.py +237 -0
  276. ultralytics/utils/export/imx.py +315 -0
  277. ultralytics/utils/export/tensorflow.py +231 -0
  278. ultralytics/utils/files.py +219 -0
  279. ultralytics/utils/git.py +137 -0
  280. ultralytics/utils/instance.py +484 -0
  281. ultralytics/utils/logger.py +444 -0
  282. ultralytics/utils/loss.py +849 -0
  283. ultralytics/utils/metrics.py +1560 -0
  284. ultralytics/utils/nms.py +337 -0
  285. ultralytics/utils/ops.py +664 -0
  286. ultralytics/utils/patches.py +201 -0
  287. ultralytics/utils/plotting.py +1045 -0
  288. ultralytics/utils/tal.py +403 -0
  289. ultralytics/utils/torch_utils.py +984 -0
  290. ultralytics/utils/tqdm.py +440 -0
  291. ultralytics/utils/triton.py +112 -0
  292. ultralytics/utils/tuner.py +160 -0
  293. ultralytics_opencv_headless-8.3.242.dist-info/METADATA +374 -0
  294. ultralytics_opencv_headless-8.3.242.dist-info/RECORD +298 -0
  295. ultralytics_opencv_headless-8.3.242.dist-info/WHEEL +5 -0
  296. ultralytics_opencv_headless-8.3.242.dist-info/entry_points.txt +3 -0
  297. ultralytics_opencv_headless-8.3.242.dist-info/licenses/LICENSE +661 -0
  298. ultralytics_opencv_headless-8.3.242.dist-info/top_level.txt +1 -0
@@ -0,0 +1,437 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import os
7
+ import random
8
+ from collections.abc import Iterator
9
+ from pathlib import Path
10
+ from typing import Any
11
+ from urllib.parse import urlsplit
12
+
13
+ import numpy as np
14
+ import torch
15
+ import torch.distributed as dist
16
+ from PIL import Image
17
+ from torch.utils.data import Dataset, dataloader, distributed
18
+
19
+ from ultralytics.cfg import IterableSimpleNamespace
20
+ from ultralytics.data.dataset import GroundingDataset, YOLODataset, YOLOMultiModalDataset
21
+ from ultralytics.data.loaders import (
22
+ LOADERS,
23
+ LoadImagesAndVideos,
24
+ LoadPilAndNumpy,
25
+ LoadScreenshots,
26
+ LoadStreams,
27
+ LoadTensor,
28
+ SourceTypes,
29
+ autocast_list,
30
+ )
31
+ from ultralytics.data.utils import IMG_FORMATS, VID_FORMATS
32
+ from ultralytics.utils import RANK, colorstr
33
+ from ultralytics.utils.checks import check_file
34
+ from ultralytics.utils.torch_utils import TORCH_2_0
35
+
36
+
37
+ class InfiniteDataLoader(dataloader.DataLoader):
38
+ """DataLoader that reuses workers for infinite iteration.
39
+
40
+ This dataloader extends the PyTorch DataLoader to provide infinite recycling of workers, which improves efficiency
41
+ for training loops that need to iterate through the dataset multiple times without recreating workers.
42
+
43
+ Attributes:
44
+ batch_sampler (_RepeatSampler): A sampler that repeats indefinitely.
45
+ iterator (Iterator): The iterator from the parent DataLoader.
46
+
47
+ Methods:
48
+ __len__: Return the length of the batch sampler's sampler.
49
+ __iter__: Create a sampler that repeats indefinitely.
50
+ __del__: Ensure workers are properly terminated.
51
+ reset: Reset the iterator, useful when modifying dataset settings during training.
52
+
53
+ Examples:
54
+ Create an infinite DataLoader for training
55
+ >>> dataset = YOLODataset(...)
56
+ >>> dataloader = InfiniteDataLoader(dataset, batch_size=16, shuffle=True)
57
+ >>> for batch in dataloader: # Infinite iteration
58
+ >>> train_step(batch)
59
+ """
60
+
61
+ def __init__(self, *args: Any, **kwargs: Any):
62
+ """Initialize the InfiniteDataLoader with the same arguments as DataLoader."""
63
+ if not TORCH_2_0:
64
+ kwargs.pop("prefetch_factor", None) # not supported by earlier versions
65
+ super().__init__(*args, **kwargs)
66
+ object.__setattr__(self, "batch_sampler", _RepeatSampler(self.batch_sampler))
67
+ self.iterator = super().__iter__()
68
+
69
+ def __len__(self) -> int:
70
+ """Return the length of the batch sampler's sampler."""
71
+ return len(self.batch_sampler.sampler)
72
+
73
+ def __iter__(self) -> Iterator:
74
+ """Create an iterator that yields indefinitely from the underlying iterator."""
75
+ for _ in range(len(self)):
76
+ yield next(self.iterator)
77
+
78
+ def __del__(self):
79
+ """Ensure that workers are properly terminated when the DataLoader is deleted."""
80
+ try:
81
+ if not hasattr(self.iterator, "_workers"):
82
+ return
83
+ for w in self.iterator._workers: # force terminate
84
+ if w.is_alive():
85
+ w.terminate()
86
+ self.iterator._shutdown_workers() # cleanup
87
+ except Exception:
88
+ pass
89
+
90
+ def reset(self):
91
+ """Reset the iterator to allow modifications to the dataset during training."""
92
+ self.iterator = self._get_iterator()
93
+
94
+
95
+ class _RepeatSampler:
96
+ """Sampler that repeats forever for infinite iteration.
97
+
98
+ This sampler wraps another sampler and yields its contents indefinitely, allowing for infinite iteration over a
99
+ dataset without recreating the sampler.
100
+
101
+ Attributes:
102
+ sampler (Dataset.sampler): The sampler to repeat.
103
+ """
104
+
105
+ def __init__(self, sampler: Any):
106
+ """Initialize the _RepeatSampler with a sampler to repeat indefinitely."""
107
+ self.sampler = sampler
108
+
109
+ def __iter__(self) -> Iterator:
110
+ """Iterate over the sampler indefinitely, yielding its contents."""
111
+ while True:
112
+ yield from iter(self.sampler)
113
+
114
+
115
+ class ContiguousDistributedSampler(torch.utils.data.Sampler):
116
+ """Distributed sampler that assigns contiguous batch-aligned chunks of the dataset to each GPU.
117
+
118
+ Unlike PyTorch's DistributedSampler which distributes samples in a round-robin fashion (GPU 0 gets indices
119
+ [0,2,4,...], GPU 1 gets [1,3,5,...]), this sampler gives each GPU contiguous batches of the dataset (GPU 0 gets
120
+ batches [0,1,2,...], GPU 1 gets batches [k,k+1,...], etc.). This preserves any ordering or grouping in the original
121
+ dataset, which is critical when samples are organized by similarity (e.g., images sorted by size to enable efficient
122
+ batching without padding when using rect=True).
123
+
124
+ The sampler handles uneven batch counts by distributing remainder batches to the first few ranks, ensuring all
125
+ samples are covered exactly once across all GPUs.
126
+
127
+ Args:
128
+ dataset (Dataset): Dataset to sample from. Must implement __len__.
129
+ num_replicas (int, optional): Number of distributed processes. Defaults to world size.
130
+ batch_size (int, optional): Batch size used by dataloader. Defaults to dataset batch size.
131
+ rank (int, optional): Rank of current process. Defaults to current rank.
132
+ shuffle (bool, optional): Whether to shuffle indices within each rank's chunk. Defaults to False. When True,
133
+ shuffling is deterministic and controlled by set_epoch() for reproducibility.
134
+
135
+ Examples:
136
+ >>> # For validation with size-grouped images
137
+ >>> sampler = ContiguousDistributedSampler(val_dataset, batch_size=32, shuffle=False)
138
+ >>> loader = DataLoader(val_dataset, batch_size=32, sampler=sampler)
139
+ >>> # For training with shuffling
140
+ >>> sampler = ContiguousDistributedSampler(train_dataset, batch_size=32, shuffle=True)
141
+ >>> for epoch in range(num_epochs):
142
+ ... sampler.set_epoch(epoch)
143
+ ... for batch in loader:
144
+ ... ...
145
+ """
146
+
147
+ def __init__(
148
+ self,
149
+ dataset: Dataset,
150
+ num_replicas: int | None = None,
151
+ batch_size: int | None = None,
152
+ rank: int | None = None,
153
+ shuffle: bool = False,
154
+ ) -> None:
155
+ """Initialize the sampler with dataset and distributed training parameters."""
156
+ if num_replicas is None:
157
+ num_replicas = dist.get_world_size() if dist.is_initialized() else 1
158
+ if rank is None:
159
+ rank = dist.get_rank() if dist.is_initialized() else 0
160
+ if batch_size is None:
161
+ batch_size = getattr(dataset, "batch_size", 1)
162
+
163
+ self.num_replicas = num_replicas
164
+ self.rank = rank
165
+ self.epoch = 0
166
+ self.shuffle = shuffle
167
+ self.total_size = len(dataset)
168
+ # ensure all ranks have a sample if batch size >= total size; degenerates to round-robin sampler
169
+ self.batch_size = 1 if batch_size >= self.total_size else batch_size
170
+ self.num_batches = math.ceil(self.total_size / self.batch_size)
171
+
172
+ def _get_rank_indices(self) -> tuple[int, int]:
173
+ """Calculate the start and end sample indices for this rank."""
174
+ # Calculate which batches this rank handles
175
+ batches_per_rank_base = self.num_batches // self.num_replicas
176
+ remainder = self.num_batches % self.num_replicas
177
+
178
+ # This rank gets an extra batch if rank < remainder
179
+ batches_for_this_rank = batches_per_rank_base + (1 if self.rank < remainder else 0)
180
+
181
+ # Calculate starting batch: base position + number of extra batches given to earlier ranks
182
+ start_batch = self.rank * batches_per_rank_base + min(self.rank, remainder)
183
+ end_batch = start_batch + batches_for_this_rank
184
+
185
+ # Convert batch indices to sample indices
186
+ start_idx = start_batch * self.batch_size
187
+ end_idx = min(end_batch * self.batch_size, self.total_size)
188
+
189
+ return start_idx, end_idx
190
+
191
+ def __iter__(self) -> Iterator:
192
+ """Generate indices for this rank's contiguous chunk of the dataset."""
193
+ start_idx, end_idx = self._get_rank_indices()
194
+ indices = list(range(start_idx, end_idx))
195
+
196
+ if self.shuffle:
197
+ g = torch.Generator()
198
+ g.manual_seed(self.epoch)
199
+ indices = [indices[i] for i in torch.randperm(len(indices), generator=g).tolist()]
200
+
201
+ return iter(indices)
202
+
203
+ def __len__(self) -> int:
204
+ """Return the number of samples in this rank's chunk."""
205
+ start_idx, end_idx = self._get_rank_indices()
206
+ return end_idx - start_idx
207
+
208
+ def set_epoch(self, epoch: int) -> None:
209
+ """Set the epoch for this sampler to ensure different shuffling patterns across epochs.
210
+
211
+ Args:
212
+ epoch (int): Epoch number to use as the random seed for shuffling.
213
+ """
214
+ self.epoch = epoch
215
+
216
+
217
+ def seed_worker(worker_id: int) -> None:
218
+ """Set dataloader worker seed for reproducibility across worker processes."""
219
+ worker_seed = torch.initial_seed() % 2**32
220
+ np.random.seed(worker_seed)
221
+ random.seed(worker_seed)
222
+
223
+
224
+ def build_yolo_dataset(
225
+ cfg: IterableSimpleNamespace,
226
+ img_path: str,
227
+ batch: int,
228
+ data: dict[str, Any],
229
+ mode: str = "train",
230
+ rect: bool = False,
231
+ stride: int = 32,
232
+ multi_modal: bool = False,
233
+ ) -> Dataset:
234
+ """Build and return a YOLO dataset based on configuration parameters."""
235
+ dataset = YOLOMultiModalDataset if multi_modal else YOLODataset
236
+ return dataset(
237
+ img_path=img_path,
238
+ imgsz=cfg.imgsz,
239
+ batch_size=batch,
240
+ augment=mode == "train", # augmentation
241
+ hyp=cfg, # TODO: probably add a get_hyps_from_cfg function
242
+ rect=cfg.rect or rect, # rectangular batches
243
+ cache=cfg.cache or None,
244
+ single_cls=cfg.single_cls or False,
245
+ stride=stride,
246
+ pad=0.0 if mode == "train" else 0.5,
247
+ prefix=colorstr(f"{mode}: "),
248
+ task=cfg.task,
249
+ classes=cfg.classes,
250
+ data=data,
251
+ fraction=cfg.fraction if mode == "train" else 1.0,
252
+ )
253
+
254
+
255
+ def build_grounding(
256
+ cfg: IterableSimpleNamespace,
257
+ img_path: str,
258
+ json_file: str,
259
+ batch: int,
260
+ mode: str = "train",
261
+ rect: bool = False,
262
+ stride: int = 32,
263
+ max_samples: int = 80,
264
+ ) -> Dataset:
265
+ """Build and return a GroundingDataset based on configuration parameters."""
266
+ return GroundingDataset(
267
+ img_path=img_path,
268
+ json_file=json_file,
269
+ max_samples=max_samples,
270
+ imgsz=cfg.imgsz,
271
+ batch_size=batch,
272
+ augment=mode == "train", # augmentation
273
+ hyp=cfg, # TODO: probably add a get_hyps_from_cfg function
274
+ rect=cfg.rect or rect, # rectangular batches
275
+ cache=cfg.cache or None,
276
+ single_cls=cfg.single_cls or False,
277
+ stride=stride,
278
+ pad=0.0 if mode == "train" else 0.5,
279
+ prefix=colorstr(f"{mode}: "),
280
+ task=cfg.task,
281
+ classes=cfg.classes,
282
+ fraction=cfg.fraction if mode == "train" else 1.0,
283
+ )
284
+
285
+
286
+ def build_dataloader(
287
+ dataset,
288
+ batch: int,
289
+ workers: int,
290
+ shuffle: bool = True,
291
+ rank: int = -1,
292
+ drop_last: bool = False,
293
+ pin_memory: bool = True,
294
+ ) -> InfiniteDataLoader:
295
+ """Create and return an InfiniteDataLoader or DataLoader for training or validation.
296
+
297
+ Args:
298
+ dataset (Dataset): Dataset to load data from.
299
+ batch (int): Batch size for the dataloader.
300
+ workers (int): Number of worker threads for loading data.
301
+ shuffle (bool, optional): Whether to shuffle the dataset.
302
+ rank (int, optional): Process rank in distributed training. -1 for single-GPU training.
303
+ drop_last (bool, optional): Whether to drop the last incomplete batch.
304
+ pin_memory (bool, optional): Whether to use pinned memory for dataloader.
305
+
306
+ Returns:
307
+ (InfiniteDataLoader): A dataloader that can be used for training or validation.
308
+
309
+ Examples:
310
+ Create a dataloader for training
311
+ >>> dataset = YOLODataset(...)
312
+ >>> dataloader = build_dataloader(dataset, batch=16, workers=4, shuffle=True)
313
+ """
314
+ batch = min(batch, len(dataset))
315
+ nd = torch.cuda.device_count() # number of CUDA devices
316
+ nw = min(os.cpu_count() // max(nd, 1), workers) # number of workers
317
+ sampler = (
318
+ None
319
+ if rank == -1
320
+ else distributed.DistributedSampler(dataset, shuffle=shuffle)
321
+ if shuffle
322
+ else ContiguousDistributedSampler(dataset)
323
+ )
324
+ generator = torch.Generator()
325
+ generator.manual_seed(6148914691236517205 + RANK)
326
+ return InfiniteDataLoader(
327
+ dataset=dataset,
328
+ batch_size=batch,
329
+ shuffle=shuffle and sampler is None,
330
+ num_workers=nw,
331
+ sampler=sampler,
332
+ prefetch_factor=4 if nw > 0 else None, # increase over default 2
333
+ pin_memory=nd > 0 and pin_memory,
334
+ collate_fn=getattr(dataset, "collate_fn", None),
335
+ worker_init_fn=seed_worker,
336
+ generator=generator,
337
+ drop_last=drop_last and len(dataset) % batch != 0,
338
+ )
339
+
340
+
341
+ def check_source(
342
+ source: str | int | Path | list | tuple | np.ndarray | Image.Image | torch.Tensor,
343
+ ) -> tuple[Any, bool, bool, bool, bool, bool]:
344
+ """Check the type of input source and return corresponding flag values.
345
+
346
+ Args:
347
+ source (str | int | Path | list | tuple | np.ndarray | PIL.Image | torch.Tensor): The input source to check.
348
+
349
+ Returns:
350
+ source (str | int | Path | list | tuple | np.ndarray | PIL.Image | torch.Tensor): The processed source.
351
+ webcam (bool): Whether the source is a webcam.
352
+ screenshot (bool): Whether the source is a screenshot.
353
+ from_img (bool): Whether the source is an image or list of images.
354
+ in_memory (bool): Whether the source is an in-memory object.
355
+ tensor (bool): Whether the source is a torch.Tensor.
356
+
357
+ Examples:
358
+ Check a file path source
359
+ >>> source, webcam, screenshot, from_img, in_memory, tensor = check_source("image.jpg")
360
+
361
+ Check a webcam source
362
+ >>> source, webcam, screenshot, from_img, in_memory, tensor = check_source(0)
363
+ """
364
+ webcam, screenshot, from_img, in_memory, tensor = False, False, False, False, False
365
+ if isinstance(source, (str, int, Path)): # int for local usb camera
366
+ source = str(source)
367
+ source_lower = source.lower()
368
+ is_url = source_lower.startswith(("https://", "http://", "rtsp://", "rtmp://", "tcp://"))
369
+ is_file = (urlsplit(source_lower).path if is_url else source_lower).rpartition(".")[-1] in (
370
+ IMG_FORMATS | VID_FORMATS
371
+ )
372
+ webcam = source.isnumeric() or source.endswith(".streams") or (is_url and not is_file)
373
+ screenshot = source_lower == "screen"
374
+ if is_url and is_file:
375
+ source = check_file(source) # download
376
+ elif isinstance(source, LOADERS):
377
+ in_memory = True
378
+ elif isinstance(source, (list, tuple)):
379
+ source = autocast_list(source) # convert all list elements to PIL or np arrays
380
+ from_img = True
381
+ elif isinstance(source, (Image.Image, np.ndarray)):
382
+ from_img = True
383
+ elif isinstance(source, torch.Tensor):
384
+ tensor = True
385
+ else:
386
+ raise TypeError("Unsupported image type. For supported types see https://docs.ultralytics.com/modes/predict")
387
+
388
+ return source, webcam, screenshot, from_img, in_memory, tensor
389
+
390
+
391
+ def load_inference_source(
392
+ source: str | int | Path | list | tuple | np.ndarray | Image.Image | torch.Tensor,
393
+ batch: int = 1,
394
+ vid_stride: int = 1,
395
+ buffer: bool = False,
396
+ channels: int = 3,
397
+ ):
398
+ """Load an inference source for object detection and apply necessary transformations.
399
+
400
+ Args:
401
+ source (str | Path | list | tuple | torch.Tensor | PIL.Image | np.ndarray): The input source for inference.
402
+ batch (int, optional): Batch size for dataloaders.
403
+ vid_stride (int, optional): The frame interval for video sources.
404
+ buffer (bool, optional): Whether stream frames will be buffered.
405
+ channels (int, optional): The number of input channels for the model.
406
+
407
+ Returns:
408
+ (Dataset): A dataset object for the specified input source with attached source_type attribute.
409
+
410
+ Examples:
411
+ Load an image source for inference
412
+ >>> dataset = load_inference_source("image.jpg", batch=1)
413
+
414
+ Load a video stream source
415
+ >>> dataset = load_inference_source("rtsp://example.com/stream", vid_stride=2)
416
+ """
417
+ source, stream, screenshot, from_img, in_memory, tensor = check_source(source)
418
+ source_type = source.source_type if in_memory else SourceTypes(stream, screenshot, from_img, tensor)
419
+
420
+ # DataLoader
421
+ if tensor:
422
+ dataset = LoadTensor(source)
423
+ elif in_memory:
424
+ dataset = source
425
+ elif stream:
426
+ dataset = LoadStreams(source, vid_stride=vid_stride, buffer=buffer, channels=channels)
427
+ elif screenshot:
428
+ dataset = LoadScreenshots(source, channels=channels)
429
+ elif from_img:
430
+ dataset = LoadPilAndNumpy(source, channels=channels)
431
+ else:
432
+ dataset = LoadImagesAndVideos(source, batch=batch, vid_stride=vid_stride, channels=channels)
433
+
434
+ # Attach source types to the dataset
435
+ setattr(dataset, "source_type", source_type)
436
+
437
+ return dataset