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,394 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+ from typing import Tuple
4
+
5
+ import torch
6
+ import torch.nn.functional as F
7
+
8
+
9
+ def select_closest_cond_frames(frame_idx, cond_frame_outputs, max_cond_frame_num):
10
+ """
11
+ Select the closest conditioning frames to a given frame index.
12
+
13
+ Args:
14
+ frame_idx (int): Current frame index.
15
+ cond_frame_outputs (Dict[int, Any]): Dictionary of conditioning frame outputs keyed by frame indices.
16
+ max_cond_frame_num (int): Maximum number of conditioning frames to select.
17
+
18
+ Returns:
19
+ selected_outputs (Dict[int, Any]): Selected items from cond_frame_outputs.
20
+ unselected_outputs (Dict[int, Any]): Items not selected from cond_frame_outputs.
21
+
22
+ Examples:
23
+ >>> frame_idx = 5
24
+ >>> cond_frame_outputs = {1: "a", 3: "b", 7: "c", 9: "d"}
25
+ >>> max_cond_frame_num = 2
26
+ >>> selected, unselected = select_closest_cond_frames(frame_idx, cond_frame_outputs, max_cond_frame_num)
27
+ >>> print(selected)
28
+ {3: 'b', 7: 'c'}
29
+ >>> print(unselected)
30
+ {1: 'a', 9: 'd'}
31
+ """
32
+ if max_cond_frame_num == -1 or len(cond_frame_outputs) <= max_cond_frame_num:
33
+ selected_outputs = cond_frame_outputs
34
+ unselected_outputs = {}
35
+ else:
36
+ assert max_cond_frame_num >= 2, "we should allow using 2+ conditioning frames"
37
+ selected_outputs = {}
38
+
39
+ # The closest conditioning frame before `frame_idx` (if any)
40
+ idx_before = max((t for t in cond_frame_outputs if t < frame_idx), default=None)
41
+ if idx_before is not None:
42
+ selected_outputs[idx_before] = cond_frame_outputs[idx_before]
43
+
44
+ # The closest conditioning frame after `frame_idx` (if any)
45
+ idx_after = min((t for t in cond_frame_outputs if t >= frame_idx), default=None)
46
+ if idx_after is not None:
47
+ selected_outputs[idx_after] = cond_frame_outputs[idx_after]
48
+
49
+ # Add other temporally closest conditioning frames until reaching a total
50
+ # of `max_cond_frame_num` conditioning frames.
51
+ num_remain = max_cond_frame_num - len(selected_outputs)
52
+ inds_remain = sorted(
53
+ (t for t in cond_frame_outputs if t not in selected_outputs),
54
+ key=lambda x: abs(x - frame_idx),
55
+ )[:num_remain]
56
+ selected_outputs.update((t, cond_frame_outputs[t]) for t in inds_remain)
57
+ unselected_outputs = {t: v for t, v in cond_frame_outputs.items() if t not in selected_outputs}
58
+
59
+ return selected_outputs, unselected_outputs
60
+
61
+
62
+ def get_1d_sine_pe(pos_inds, dim, temperature=10000):
63
+ """
64
+ Generate 1D sinusoidal positional embeddings for given positions and dimensions.
65
+
66
+ Args:
67
+ pos_inds (torch.Tensor): Position indices for which to generate embeddings.
68
+ dim (int): Dimension of the positional embeddings. Should be an even number.
69
+ temperature (float): Scaling factor for the frequency of the sinusoidal functions.
70
+
71
+ Returns:
72
+ (torch.Tensor): Sinusoidal positional embeddings with shape (pos_inds.shape, dim).
73
+
74
+ Examples:
75
+ >>> pos = torch.tensor([0, 1, 2, 3])
76
+ >>> embeddings = get_1d_sine_pe(pos, 128)
77
+ >>> embeddings.shape
78
+ torch.Size([4, 128])
79
+ """
80
+ pe_dim = dim // 2
81
+ dim_t = torch.arange(pe_dim, dtype=torch.float32, device=pos_inds.device)
82
+ dim_t = temperature ** (2 * (dim_t // 2) / pe_dim)
83
+
84
+ pos_embed = pos_inds.unsqueeze(-1) / dim_t
85
+ pos_embed = torch.cat([pos_embed.sin(), pos_embed.cos()], dim=-1)
86
+ return pos_embed
87
+
88
+
89
+ def init_t_xy(end_x: int, end_y: int):
90
+ """
91
+ Initialize 1D and 2D coordinate tensors for a grid of specified dimensions.
92
+
93
+ This function creates coordinate tensors for a grid with dimensions end_x × end_y. It generates a linear index tensor
94
+ and corresponding x and y coordinate tensors.
95
+
96
+ Args:
97
+ end_x (int): Width of the grid (number of columns).
98
+ end_y (int): Height of the grid (number of rows).
99
+
100
+ Returns:
101
+ t (torch.Tensor): Linear indices for each position in the grid, with shape (end_x * end_y).
102
+ t_x (torch.Tensor): X-coordinates for each position, with shape (end_x * end_y).
103
+ t_y (torch.Tensor): Y-coordinates for each position, with shape (end_x * end_y).
104
+
105
+ Examples:
106
+ >>> t, t_x, t_y = init_t_xy(3, 2)
107
+ >>> print(t)
108
+ tensor([0., 1., 2., 3., 4., 5.])
109
+ >>> print(t_x)
110
+ tensor([0., 1., 2., 0., 1., 2.])
111
+ >>> print(t_y)
112
+ tensor([0., 0., 0., 1., 1., 1.])
113
+ """
114
+ t = torch.arange(end_x * end_y, dtype=torch.float32)
115
+ t_x = (t % end_x).float()
116
+ t_y = torch.div(t, end_x, rounding_mode="floor").float()
117
+ return t_x, t_y
118
+
119
+
120
+ def compute_axial_cis(dim: int, end_x: int, end_y: int, theta: float = 10000.0):
121
+ """
122
+ Compute axial complex exponential positional encodings for 2D spatial positions in a grid.
123
+
124
+ This function generates complex exponential positional encodings for a 2D grid of spatial positions,
125
+ using separate frequency components for the x and y dimensions.
126
+
127
+ Args:
128
+ dim (int): Dimension of the positional encoding.
129
+ end_x (int): Width of the 2D grid.
130
+ end_y (int): Height of the 2D grid.
131
+ theta (float, optional): Scaling factor for frequency computation.
132
+
133
+ Returns:
134
+ freqs_cis_x (torch.Tensor): Complex exponential positional encodings for x-dimension with shape
135
+ (end_x*end_y, dim//4).
136
+ freqs_cis_y (torch.Tensor): Complex exponential positional encodings for y-dimension with shape
137
+ (end_x*end_y, dim//4).
138
+
139
+ Examples:
140
+ >>> dim, end_x, end_y = 128, 8, 8
141
+ >>> freqs_cis_x, freqs_cis_y = compute_axial_cis(dim, end_x, end_y)
142
+ >>> freqs_cis_x.shape
143
+ torch.Size([64, 32])
144
+ >>> freqs_cis_y.shape
145
+ torch.Size([64, 32])
146
+ """
147
+ freqs_x = 1.0 / (theta ** (torch.arange(0, dim, 4)[: (dim // 4)].float() / dim))
148
+ freqs_y = 1.0 / (theta ** (torch.arange(0, dim, 4)[: (dim // 4)].float() / dim))
149
+
150
+ t_x, t_y = init_t_xy(end_x, end_y)
151
+ freqs_x = torch.outer(t_x, freqs_x)
152
+ freqs_y = torch.outer(t_y, freqs_y)
153
+ freqs_cis_x = torch.polar(torch.ones_like(freqs_x), freqs_x)
154
+ freqs_cis_y = torch.polar(torch.ones_like(freqs_y), freqs_y)
155
+ return torch.cat([freqs_cis_x, freqs_cis_y], dim=-1)
156
+
157
+
158
+ def reshape_for_broadcast(freqs_cis: torch.Tensor, x: torch.Tensor):
159
+ """
160
+ Reshape frequency tensor for broadcasting with input tensor.
161
+
162
+ Reshapes a frequency tensor to ensure dimensional compatibility for broadcasting with an input tensor.
163
+ This function is typically used in positional encoding operations.
164
+
165
+ Args:
166
+ freqs_cis (torch.Tensor): Frequency tensor with shape matching the last two dimensions of x.
167
+ x (torch.Tensor): Input tensor to broadcast with.
168
+
169
+ Returns:
170
+ (torch.Tensor): Reshaped frequency tensor ready for broadcasting with the input tensor.
171
+
172
+ Raises:
173
+ AssertionError: If the shape of freqs_cis doesn't match the last two dimensions of x.
174
+ """
175
+ ndim = x.ndim
176
+ assert 0 <= 1 < ndim
177
+ assert freqs_cis.shape == (x.shape[-2], x.shape[-1])
178
+ shape = [d if i >= ndim - 2 else 1 for i, d in enumerate(x.shape)]
179
+ return freqs_cis.view(*shape)
180
+
181
+
182
+ def apply_rotary_enc(
183
+ xq: torch.Tensor,
184
+ xk: torch.Tensor,
185
+ freqs_cis: torch.Tensor,
186
+ repeat_freqs_k: bool = False,
187
+ ):
188
+ """
189
+ Apply rotary positional encoding to query and key tensors.
190
+
191
+ This function applies rotary positional encoding (RoPE) to query and key tensors using complex-valued frequency
192
+ components. RoPE is a technique that injects relative position information into self-attention mechanisms.
193
+
194
+ Args:
195
+ xq (torch.Tensor): Query tensor to encode with positional information.
196
+ xk (torch.Tensor): Key tensor to encode with positional information.
197
+ freqs_cis (torch.Tensor): Complex-valued frequency components for rotary encoding with shape matching the
198
+ last two dimensions of xq.
199
+ repeat_freqs_k (bool, optional): Whether to repeat frequency components along sequence length dimension
200
+ to match key sequence length.
201
+
202
+ Returns:
203
+ xq_out (torch.Tensor): Query tensor with rotary positional encoding applied.
204
+ xk_out (torch.Tensor): Key tensor with rotary positional encoding applied, or original xk if xk is empty.
205
+
206
+ Examples:
207
+ >>> import torch
208
+ >>> xq = torch.randn(2, 8, 16, 64) # [batch, heads, seq_len, dim]
209
+ >>> xk = torch.randn(2, 8, 16, 64)
210
+ >>> freqs_cis = compute_axial_cis(64, 4, 4) # For a 4x4 spatial grid with dim=64
211
+ >>> q_encoded, k_encoded = apply_rotary_enc(xq, xk, freqs_cis)
212
+ """
213
+ xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2))
214
+ xk_ = torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2)) if xk.shape[-2] != 0 else None
215
+ freqs_cis = reshape_for_broadcast(freqs_cis, xq_)
216
+ xq_out = torch.view_as_real(xq_ * freqs_cis).flatten(3)
217
+ if xk_ is None:
218
+ # No keys to rotate, due to dropout
219
+ return xq_out.type_as(xq).to(xq.device), xk
220
+ # Repeat freqs along seq_len dim to match k seq_len
221
+ if repeat_freqs_k:
222
+ r = xk_.shape[-2] // xq_.shape[-2]
223
+ freqs_cis = freqs_cis.repeat(*([1] * (freqs_cis.ndim - 2)), r, 1)
224
+ xk_out = torch.view_as_real(xk_ * freqs_cis).flatten(3)
225
+ return xq_out.type_as(xq).to(xq.device), xk_out.type_as(xk).to(xk.device)
226
+
227
+
228
+ def window_partition(x, window_size):
229
+ """
230
+ Partition input tensor into non-overlapping windows with padding if needed.
231
+
232
+ Args:
233
+ x (torch.Tensor): Input tensor with shape (B, H, W, C).
234
+ window_size (int): Size of each window.
235
+
236
+ Returns:
237
+ windows (torch.Tensor): Partitioned windows with shape (B * num_windows, window_size, window_size, C).
238
+ padded_h_w (Tuple[int, int]): Padded height and width before partition.
239
+
240
+ Examples:
241
+ >>> x = torch.randn(1, 16, 16, 3)
242
+ >>> windows, (Hp, Wp) = window_partition(x, window_size=4)
243
+ >>> print(windows.shape, Hp, Wp)
244
+ torch.Size([16, 4, 4, 3]) 16 16
245
+ """
246
+ B, H, W, C = x.shape
247
+
248
+ pad_h = (window_size - H % window_size) % window_size
249
+ pad_w = (window_size - W % window_size) % window_size
250
+ if pad_h > 0 or pad_w > 0:
251
+ x = F.pad(x, (0, 0, 0, pad_w, 0, pad_h))
252
+ Hp, Wp = H + pad_h, W + pad_w
253
+
254
+ x = x.view(B, Hp // window_size, window_size, Wp // window_size, window_size, C)
255
+ windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
256
+ return windows, (Hp, Wp)
257
+
258
+
259
+ def window_unpartition(windows, window_size, pad_hw, hw):
260
+ """
261
+ Unpartition windowed sequences into original sequences and remove padding.
262
+
263
+ This function reverses the windowing process, reconstructing the original input from windowed segments
264
+ and removing any padding that was added during the windowing process.
265
+
266
+ Args:
267
+ windows (torch.Tensor): Input tensor of windowed sequences with shape (B * num_windows, window_size,
268
+ window_size, C), where B is the batch size, num_windows is the number of windows, window_size is
269
+ the size of each window, and C is the number of channels.
270
+ window_size (int): Size of each window.
271
+ pad_hw (Tuple[int, int]): Padded height and width (Hp, Wp) of the input before windowing.
272
+ hw (Tuple[int, int]): Original height and width (H, W) of the input before padding and windowing.
273
+
274
+ Returns:
275
+ (torch.Tensor): Unpartitioned sequences with shape (B, H, W, C), where B is the batch size, H and W
276
+ are the original height and width, and C is the number of channels.
277
+
278
+ Examples:
279
+ >>> windows = torch.rand(32, 8, 8, 64) # 32 windows of size 8x8 with 64 channels
280
+ >>> pad_hw = (16, 16) # Padded height and width
281
+ >>> hw = (15, 14) # Original height and width
282
+ >>> x = window_unpartition(windows, window_size=8, pad_hw=pad_hw, hw=hw)
283
+ >>> print(x.shape)
284
+ torch.Size([1, 15, 14, 64])
285
+ """
286
+ Hp, Wp = pad_hw
287
+ H, W = hw
288
+ B = windows.shape[0] // (Hp * Wp // window_size // window_size)
289
+ x = windows.view(B, Hp // window_size, Wp // window_size, window_size, window_size, -1)
290
+ x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, Hp, Wp, -1)
291
+
292
+ if Hp > H or Wp > W:
293
+ x = x[:, :H, :W, :].contiguous()
294
+ return x
295
+
296
+
297
+ def get_rel_pos(q_size: int, k_size: int, rel_pos: torch.Tensor) -> torch.Tensor:
298
+ """
299
+ Extract relative positional embeddings based on query and key sizes.
300
+
301
+ Args:
302
+ q_size (int): Size of the query.
303
+ k_size (int): Size of the key.
304
+ rel_pos (torch.Tensor): Relative position embeddings with shape (L, C), where L is the maximum relative
305
+ distance and C is the embedding dimension.
306
+
307
+ Returns:
308
+ (torch.Tensor): Extracted positional embeddings according to relative positions, with shape (q_size,
309
+ k_size, C).
310
+
311
+ Examples:
312
+ >>> q_size, k_size = 8, 16
313
+ >>> rel_pos = torch.randn(31, 64) # 31 = 2 * max(8, 16) - 1
314
+ >>> extracted_pos = get_rel_pos(q_size, k_size, rel_pos)
315
+ >>> print(extracted_pos.shape)
316
+ torch.Size([8, 16, 64])
317
+ """
318
+ max_rel_dist = int(2 * max(q_size, k_size) - 1)
319
+ # Interpolate rel pos if needed.
320
+ if rel_pos.shape[0] != max_rel_dist:
321
+ # Interpolate rel pos.
322
+ rel_pos_resized = F.interpolate(
323
+ rel_pos.reshape(1, rel_pos.shape[0], -1).permute(0, 2, 1),
324
+ size=max_rel_dist,
325
+ mode="linear",
326
+ )
327
+ rel_pos_resized = rel_pos_resized.reshape(-1, max_rel_dist).permute(1, 0)
328
+ else:
329
+ rel_pos_resized = rel_pos
330
+
331
+ # Scale the coords with short length if shapes for q and k are different.
332
+ q_coords = torch.arange(q_size)[:, None] * max(k_size / q_size, 1.0)
333
+ k_coords = torch.arange(k_size)[None, :] * max(q_size / k_size, 1.0)
334
+ relative_coords = (q_coords - k_coords) + (k_size - 1) * max(q_size / k_size, 1.0)
335
+
336
+ return rel_pos_resized[relative_coords.long()]
337
+
338
+
339
+ def add_decomposed_rel_pos(
340
+ attn: torch.Tensor,
341
+ q: torch.Tensor,
342
+ rel_pos_h: torch.Tensor,
343
+ rel_pos_w: torch.Tensor,
344
+ q_size: Tuple[int, int],
345
+ k_size: Tuple[int, int],
346
+ ) -> torch.Tensor:
347
+ """
348
+ Add decomposed Relative Positional Embeddings to the attention map.
349
+
350
+ This function calculates and applies decomposed Relative Positional Embeddings as described in the MVITv2
351
+ paper. It enhances the attention mechanism by incorporating spatial relationships between query and key
352
+ positions.
353
+
354
+ Args:
355
+ attn (torch.Tensor): Attention map with shape (B, q_h * q_w, k_h * k_w).
356
+ q (torch.Tensor): Query tensor in the attention layer with shape (B, q_h * q_w, C).
357
+ rel_pos_h (torch.Tensor): Relative position embeddings for height axis with shape (Lh, C).
358
+ rel_pos_w (torch.Tensor): Relative position embeddings for width axis with shape (Lw, C).
359
+ q_size (Tuple[int, int]): Spatial sequence size of query q as (q_h, q_w).
360
+ k_size (Tuple[int, int]): Spatial sequence size of key k as (k_h, k_w).
361
+
362
+ Returns:
363
+ (torch.Tensor): Updated attention map with added relative positional embeddings, shape
364
+ (B, q_h * q_w, k_h * k_w).
365
+
366
+ Examples:
367
+ >>> B, C, q_h, q_w, k_h, k_w = 1, 64, 8, 8, 8, 8
368
+ >>> attn = torch.rand(B, q_h * q_w, k_h * k_w)
369
+ >>> q = torch.rand(B, q_h * q_w, C)
370
+ >>> rel_pos_h = torch.rand(2 * max(q_h, k_h) - 1, C)
371
+ >>> rel_pos_w = torch.rand(2 * max(q_w, k_w) - 1, C)
372
+ >>> q_size, k_size = (q_h, q_w), (k_h, k_w)
373
+ >>> updated_attn = add_decomposed_rel_pos(attn, q, rel_pos_h, rel_pos_w, q_size, k_size)
374
+ >>> print(updated_attn.shape)
375
+ torch.Size([1, 64, 64])
376
+
377
+ References:
378
+ https://github.com/facebookresearch/mvit/blob/main/mvit/models/attention.py
379
+ """
380
+ q_h, q_w = q_size
381
+ k_h, k_w = k_size
382
+ Rh = get_rel_pos(q_h, k_h, rel_pos_h)
383
+ Rw = get_rel_pos(q_w, k_w, rel_pos_w)
384
+
385
+ B, _, dim = q.shape
386
+ r_q = q.reshape(B, q_h, q_w, dim)
387
+ rel_h = torch.einsum("bhwc,hkc->bhwk", r_q, Rh)
388
+ rel_w = torch.einsum("bhwc,wkc->bhwk", r_q, Rw)
389
+
390
+ attn = (attn.view(B, q_h, q_w, k_h, k_w) + rel_h[:, :, :, :, None] + rel_w[:, :, :, None, :]).view(
391
+ B, q_h * q_w, k_h * k_w
392
+ )
393
+
394
+ return attn