ultralytics-opencv-headless 8.3.246__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 +1578 -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 +313 -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 +1006 -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 +501 -0
  282. ultralytics/utils/loss.py +849 -0
  283. ultralytics/utils/metrics.py +1563 -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.246.dist-info/METADATA +374 -0
  294. ultralytics_opencv_headless-8.3.246.dist-info/RECORD +298 -0
  295. ultralytics_opencv_headless-8.3.246.dist-info/WHEEL +5 -0
  296. ultralytics_opencv_headless-8.3.246.dist-info/entry_points.txt +3 -0
  297. ultralytics_opencv_headless-8.3.246.dist-info/licenses/LICENSE +661 -0
  298. ultralytics_opencv_headless-8.3.246.dist-info/top_level.txt +1 -0
@@ -0,0 +1,979 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+ # --------------------------------------------------------
4
+ # TinyViT Model Architecture
5
+ # Copyright (c) 2022 Microsoft
6
+ # Adapted from LeViT and Swin Transformer
7
+ # LeViT: (https://github.com/facebookresearch/levit)
8
+ # Swin: (https://github.com/microsoft/swin-transformer)
9
+ # Build the TinyViT Model
10
+ # --------------------------------------------------------
11
+
12
+ from __future__ import annotations
13
+
14
+ import itertools
15
+
16
+ import torch
17
+ import torch.nn as nn
18
+ import torch.nn.functional as F
19
+
20
+ from ultralytics.nn.modules import LayerNorm2d
21
+ from ultralytics.utils.instance import to_2tuple
22
+
23
+
24
+ class Conv2d_BN(torch.nn.Sequential):
25
+ """A sequential container that performs 2D convolution followed by batch normalization.
26
+
27
+ This module combines a 2D convolution layer with batch normalization, providing a common building block for
28
+ convolutional neural networks. The batch normalization weights and biases are initialized to specific values for
29
+ optimal training performance.
30
+
31
+ Attributes:
32
+ c (torch.nn.Conv2d): 2D convolution layer.
33
+ bn (torch.nn.BatchNorm2d): Batch normalization layer.
34
+
35
+ Examples:
36
+ >>> conv_bn = Conv2d_BN(3, 64, ks=3, stride=1, pad=1)
37
+ >>> input_tensor = torch.randn(1, 3, 224, 224)
38
+ >>> output = conv_bn(input_tensor)
39
+ >>> print(output.shape)
40
+ torch.Size([1, 64, 224, 224])
41
+ """
42
+
43
+ def __init__(
44
+ self,
45
+ a: int,
46
+ b: int,
47
+ ks: int = 1,
48
+ stride: int = 1,
49
+ pad: int = 0,
50
+ dilation: int = 1,
51
+ groups: int = 1,
52
+ bn_weight_init: float = 1,
53
+ ):
54
+ """Initialize a sequential container with 2D convolution followed by batch normalization.
55
+
56
+ Args:
57
+ a (int): Number of input channels.
58
+ b (int): Number of output channels.
59
+ ks (int, optional): Kernel size for the convolution.
60
+ stride (int, optional): Stride for the convolution.
61
+ pad (int, optional): Padding for the convolution.
62
+ dilation (int, optional): Dilation factor for the convolution.
63
+ groups (int, optional): Number of groups for the convolution.
64
+ bn_weight_init (float, optional): Initial value for batch normalization weight.
65
+ """
66
+ super().__init__()
67
+ self.add_module("c", torch.nn.Conv2d(a, b, ks, stride, pad, dilation, groups, bias=False))
68
+ bn = torch.nn.BatchNorm2d(b)
69
+ torch.nn.init.constant_(bn.weight, bn_weight_init)
70
+ torch.nn.init.constant_(bn.bias, 0)
71
+ self.add_module("bn", bn)
72
+
73
+
74
+ class PatchEmbed(nn.Module):
75
+ """Embed images into patches and project them into a specified embedding dimension.
76
+
77
+ This module converts input images into patch embeddings using a sequence of convolutional layers, effectively
78
+ downsampling the spatial dimensions while increasing the channel dimension.
79
+
80
+ Attributes:
81
+ patches_resolution (tuple[int, int]): Resolution of the patches after embedding.
82
+ num_patches (int): Total number of patches.
83
+ in_chans (int): Number of input channels.
84
+ embed_dim (int): Dimension of the embedding.
85
+ seq (nn.Sequential): Sequence of convolutional and activation layers for patch embedding.
86
+
87
+ Examples:
88
+ >>> import torch
89
+ >>> patch_embed = PatchEmbed(in_chans=3, embed_dim=96, resolution=224, activation=nn.GELU)
90
+ >>> x = torch.randn(1, 3, 224, 224)
91
+ >>> output = patch_embed(x)
92
+ >>> print(output.shape)
93
+ torch.Size([1, 96, 56, 56])
94
+ """
95
+
96
+ def __init__(self, in_chans: int, embed_dim: int, resolution: int, activation):
97
+ """Initialize patch embedding with convolutional layers for image-to-patch conversion and projection.
98
+
99
+ Args:
100
+ in_chans (int): Number of input channels.
101
+ embed_dim (int): Dimension of the embedding.
102
+ resolution (int): Input image resolution.
103
+ activation (nn.Module): Activation function to use between convolutions.
104
+ """
105
+ super().__init__()
106
+ img_size: tuple[int, int] = to_2tuple(resolution)
107
+ self.patches_resolution = (img_size[0] // 4, img_size[1] // 4)
108
+ self.num_patches = self.patches_resolution[0] * self.patches_resolution[1]
109
+ self.in_chans = in_chans
110
+ self.embed_dim = embed_dim
111
+ n = embed_dim
112
+ self.seq = nn.Sequential(
113
+ Conv2d_BN(in_chans, n // 2, 3, 2, 1),
114
+ activation(),
115
+ Conv2d_BN(n // 2, n, 3, 2, 1),
116
+ )
117
+
118
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
119
+ """Process input tensor through patch embedding sequence, converting images to patch embeddings."""
120
+ return self.seq(x)
121
+
122
+
123
+ class MBConv(nn.Module):
124
+ """Mobile Inverted Bottleneck Conv (MBConv) layer, part of the EfficientNet architecture.
125
+
126
+ This module implements the mobile inverted bottleneck convolution with expansion, depthwise convolution, and
127
+ projection phases, along with residual connections for improved gradient flow.
128
+
129
+ Attributes:
130
+ in_chans (int): Number of input channels.
131
+ hidden_chans (int): Number of hidden channels after expansion.
132
+ out_chans (int): Number of output channels.
133
+ conv1 (Conv2d_BN): First convolutional layer for channel expansion.
134
+ act1 (nn.Module): First activation function.
135
+ conv2 (Conv2d_BN): Depthwise convolutional layer.
136
+ act2 (nn.Module): Second activation function.
137
+ conv3 (Conv2d_BN): Final convolutional layer for projection.
138
+ act3 (nn.Module): Third activation function.
139
+ drop_path (nn.Module): Drop path layer (Identity for inference).
140
+
141
+ Examples:
142
+ >>> in_chans, out_chans = 32, 64
143
+ >>> mbconv = MBConv(in_chans, out_chans, expand_ratio=4, activation=nn.ReLU, drop_path=0.1)
144
+ >>> x = torch.randn(1, in_chans, 56, 56)
145
+ >>> output = mbconv(x)
146
+ >>> print(output.shape)
147
+ torch.Size([1, 64, 56, 56])
148
+ """
149
+
150
+ def __init__(self, in_chans: int, out_chans: int, expand_ratio: float, activation, drop_path: float):
151
+ """Initialize the MBConv layer with specified input/output channels, expansion ratio, and activation.
152
+
153
+ Args:
154
+ in_chans (int): Number of input channels.
155
+ out_chans (int): Number of output channels.
156
+ expand_ratio (float): Channel expansion ratio for the hidden layer.
157
+ activation (nn.Module): Activation function to use.
158
+ drop_path (float): Drop path rate for stochastic depth.
159
+ """
160
+ super().__init__()
161
+ self.in_chans = in_chans
162
+ self.hidden_chans = int(in_chans * expand_ratio)
163
+ self.out_chans = out_chans
164
+
165
+ self.conv1 = Conv2d_BN(in_chans, self.hidden_chans, ks=1)
166
+ self.act1 = activation()
167
+
168
+ self.conv2 = Conv2d_BN(self.hidden_chans, self.hidden_chans, ks=3, stride=1, pad=1, groups=self.hidden_chans)
169
+ self.act2 = activation()
170
+
171
+ self.conv3 = Conv2d_BN(self.hidden_chans, out_chans, ks=1, bn_weight_init=0.0)
172
+ self.act3 = activation()
173
+
174
+ # NOTE: `DropPath` is needed only for training.
175
+ # self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
176
+ self.drop_path = nn.Identity()
177
+
178
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
179
+ """Implement the forward pass of MBConv, applying convolutions and skip connection."""
180
+ shortcut = x
181
+ x = self.conv1(x)
182
+ x = self.act1(x)
183
+ x = self.conv2(x)
184
+ x = self.act2(x)
185
+ x = self.conv3(x)
186
+ x = self.drop_path(x)
187
+ x += shortcut
188
+ return self.act3(x)
189
+
190
+
191
+ class PatchMerging(nn.Module):
192
+ """Merge neighboring patches in the feature map and project to a new dimension.
193
+
194
+ This class implements a patch merging operation that combines spatial information and adjusts the feature dimension
195
+ using a series of convolutional layers with batch normalization. It effectively reduces spatial resolution while
196
+ potentially increasing channel dimensions.
197
+
198
+ Attributes:
199
+ input_resolution (tuple[int, int]): The input resolution (height, width) of the feature map.
200
+ dim (int): The input dimension of the feature map.
201
+ out_dim (int): The output dimension after merging and projection.
202
+ act (nn.Module): The activation function used between convolutions.
203
+ conv1 (Conv2d_BN): The first convolutional layer for dimension projection.
204
+ conv2 (Conv2d_BN): The second convolutional layer for spatial merging.
205
+ conv3 (Conv2d_BN): The third convolutional layer for final projection.
206
+
207
+ Examples:
208
+ >>> input_resolution = (56, 56)
209
+ >>> patch_merging = PatchMerging(input_resolution, dim=64, out_dim=128, activation=nn.ReLU)
210
+ >>> x = torch.randn(4, 64, 56, 56)
211
+ >>> output = patch_merging(x)
212
+ >>> print(output.shape)
213
+ torch.Size([4, 3136, 128])
214
+ """
215
+
216
+ def __init__(self, input_resolution: tuple[int, int], dim: int, out_dim: int, activation):
217
+ """Initialize the PatchMerging module for merging and projecting neighboring patches in feature maps.
218
+
219
+ Args:
220
+ input_resolution (tuple[int, int]): The input resolution (height, width) of the feature map.
221
+ dim (int): The input dimension of the feature map.
222
+ out_dim (int): The output dimension after merging and projection.
223
+ activation (nn.Module): The activation function used between convolutions.
224
+ """
225
+ super().__init__()
226
+
227
+ self.input_resolution = input_resolution
228
+ self.dim = dim
229
+ self.out_dim = out_dim
230
+ self.act = activation()
231
+ self.conv1 = Conv2d_BN(dim, out_dim, 1, 1, 0)
232
+ stride_c = 1 if out_dim in {320, 448, 576} else 2
233
+ self.conv2 = Conv2d_BN(out_dim, out_dim, 3, stride_c, 1, groups=out_dim)
234
+ self.conv3 = Conv2d_BN(out_dim, out_dim, 1, 1, 0)
235
+
236
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
237
+ """Apply patch merging and dimension projection to the input feature map."""
238
+ if x.ndim == 3:
239
+ H, W = self.input_resolution
240
+ B = len(x)
241
+ # (B, C, H, W)
242
+ x = x.view(B, H, W, -1).permute(0, 3, 1, 2)
243
+
244
+ x = self.conv1(x)
245
+ x = self.act(x)
246
+
247
+ x = self.conv2(x)
248
+ x = self.act(x)
249
+ x = self.conv3(x)
250
+ return x.flatten(2).transpose(1, 2)
251
+
252
+
253
+ class ConvLayer(nn.Module):
254
+ """Convolutional Layer featuring multiple MobileNetV3-style inverted bottleneck convolutions (MBConv).
255
+
256
+ This layer optionally applies downsample operations to the output and supports gradient checkpointing for memory
257
+ efficiency during training.
258
+
259
+ Attributes:
260
+ dim (int): Dimensionality of the input and output.
261
+ input_resolution (tuple[int, int]): Resolution of the input image.
262
+ depth (int): Number of MBConv layers in the block.
263
+ use_checkpoint (bool): Whether to use gradient checkpointing to save memory.
264
+ blocks (nn.ModuleList): List of MBConv layers.
265
+ downsample (Optional[nn.Module]): Function for downsampling the output.
266
+
267
+ Examples:
268
+ >>> input_tensor = torch.randn(1, 64, 56, 56)
269
+ >>> conv_layer = ConvLayer(64, (56, 56), depth=3, activation=nn.ReLU)
270
+ >>> output = conv_layer(input_tensor)
271
+ >>> print(output.shape)
272
+ torch.Size([1, 3136, 128])
273
+ """
274
+
275
+ def __init__(
276
+ self,
277
+ dim: int,
278
+ input_resolution: tuple[int, int],
279
+ depth: int,
280
+ activation,
281
+ drop_path: float | list[float] = 0.0,
282
+ downsample: nn.Module | None = None,
283
+ use_checkpoint: bool = False,
284
+ out_dim: int | None = None,
285
+ conv_expand_ratio: float = 4.0,
286
+ ):
287
+ """Initialize the ConvLayer with the given dimensions and settings.
288
+
289
+ This layer consists of multiple MobileNetV3-style inverted bottleneck convolutions (MBConv) and optionally
290
+ applies downsampling to the output.
291
+
292
+ Args:
293
+ dim (int): The dimensionality of the input and output.
294
+ input_resolution (tuple[int, int]): The resolution of the input image.
295
+ depth (int): The number of MBConv layers in the block.
296
+ activation (nn.Module): Activation function applied after each convolution.
297
+ drop_path (float | list[float], optional): Drop path rate. Single float or a list of floats for each MBConv.
298
+ downsample (Optional[nn.Module], optional): Function for downsampling the output. None to skip downsampling.
299
+ use_checkpoint (bool, optional): Whether to use gradient checkpointing to save memory.
300
+ out_dim (Optional[int], optional): Output dimensions. None means it will be the same as `dim`.
301
+ conv_expand_ratio (float, optional): Expansion ratio for the MBConv layers.
302
+ """
303
+ super().__init__()
304
+ self.dim = dim
305
+ self.input_resolution = input_resolution
306
+ self.depth = depth
307
+ self.use_checkpoint = use_checkpoint
308
+
309
+ # Build blocks
310
+ self.blocks = nn.ModuleList(
311
+ [
312
+ MBConv(
313
+ dim,
314
+ dim,
315
+ conv_expand_ratio,
316
+ activation,
317
+ drop_path[i] if isinstance(drop_path, list) else drop_path,
318
+ )
319
+ for i in range(depth)
320
+ ]
321
+ )
322
+
323
+ # Patch merging layer
324
+ self.downsample = (
325
+ None
326
+ if downsample is None
327
+ else downsample(input_resolution, dim=dim, out_dim=out_dim, activation=activation)
328
+ )
329
+
330
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
331
+ """Process input through convolutional layers, applying MBConv blocks and optional downsampling."""
332
+ for blk in self.blocks:
333
+ x = torch.utils.checkpoint(blk, x) if self.use_checkpoint else blk(x) # warn: checkpoint is slow import
334
+ return x if self.downsample is None else self.downsample(x)
335
+
336
+
337
+ class MLP(nn.Module):
338
+ """Multi-layer Perceptron (MLP) module for transformer architectures.
339
+
340
+ This module applies layer normalization, two fully-connected layers with an activation function in between, and
341
+ dropout. It is commonly used in transformer-based architectures for processing token embeddings.
342
+
343
+ Attributes:
344
+ norm (nn.LayerNorm): Layer normalization applied to the input.
345
+ fc1 (nn.Linear): First fully-connected layer.
346
+ fc2 (nn.Linear): Second fully-connected layer.
347
+ act (nn.Module): Activation function applied after the first fully-connected layer.
348
+ drop (nn.Dropout): Dropout layer applied after the activation function.
349
+
350
+ Examples:
351
+ >>> import torch
352
+ >>> from torch import nn
353
+ >>> mlp = MLP(in_features=256, hidden_features=512, out_features=256, activation=nn.GELU, drop=0.1)
354
+ >>> x = torch.randn(32, 100, 256)
355
+ >>> output = mlp(x)
356
+ >>> print(output.shape)
357
+ torch.Size([32, 100, 256])
358
+ """
359
+
360
+ def __init__(
361
+ self,
362
+ in_features: int,
363
+ hidden_features: int | None = None,
364
+ out_features: int | None = None,
365
+ activation=nn.GELU,
366
+ drop: float = 0.0,
367
+ ):
368
+ """Initialize a multi-layer perceptron with configurable input, hidden, and output dimensions.
369
+
370
+ Args:
371
+ in_features (int): Number of input features.
372
+ hidden_features (Optional[int], optional): Number of hidden features.
373
+ out_features (Optional[int], optional): Number of output features.
374
+ activation (nn.Module): Activation function applied after the first fully-connected layer.
375
+ drop (float, optional): Dropout probability.
376
+ """
377
+ super().__init__()
378
+ out_features = out_features or in_features
379
+ hidden_features = hidden_features or in_features
380
+ self.norm = nn.LayerNorm(in_features)
381
+ self.fc1 = nn.Linear(in_features, hidden_features)
382
+ self.fc2 = nn.Linear(hidden_features, out_features)
383
+ self.act = activation()
384
+ self.drop = nn.Dropout(drop)
385
+
386
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
387
+ """Apply MLP operations: layer norm, FC layers, activation, and dropout to the input tensor."""
388
+ x = self.norm(x)
389
+ x = self.fc1(x)
390
+ x = self.act(x)
391
+ x = self.drop(x)
392
+ x = self.fc2(x)
393
+ return self.drop(x)
394
+
395
+
396
+ class Attention(torch.nn.Module):
397
+ """Multi-head attention module with spatial awareness and trainable attention biases.
398
+
399
+ This module implements a multi-head attention mechanism with support for spatial awareness, applying attention
400
+ biases based on spatial resolution. It includes trainable attention biases for each unique offset between spatial
401
+ positions in the resolution grid.
402
+
403
+ Attributes:
404
+ num_heads (int): Number of attention heads.
405
+ scale (float): Scaling factor for attention scores.
406
+ key_dim (int): Dimensionality of the keys and queries.
407
+ nh_kd (int): Product of num_heads and key_dim.
408
+ d (int): Dimensionality of the value vectors.
409
+ dh (int): Product of d and num_heads.
410
+ attn_ratio (float): Attention ratio affecting the dimensions of the value vectors.
411
+ norm (nn.LayerNorm): Layer normalization applied to input.
412
+ qkv (nn.Linear): Linear layer for computing query, key, and value projections.
413
+ proj (nn.Linear): Linear layer for final projection.
414
+ attention_biases (nn.Parameter): Learnable attention biases.
415
+ attention_bias_idxs (torch.Tensor): Indices for attention biases.
416
+ ab (torch.Tensor): Cached attention biases for inference, deleted during training.
417
+
418
+ Examples:
419
+ >>> attn = Attention(dim=256, key_dim=64, num_heads=8, resolution=(14, 14))
420
+ >>> x = torch.randn(1, 196, 256)
421
+ >>> output = attn(x)
422
+ >>> print(output.shape)
423
+ torch.Size([1, 196, 256])
424
+ """
425
+
426
+ def __init__(
427
+ self,
428
+ dim: int,
429
+ key_dim: int,
430
+ num_heads: int = 8,
431
+ attn_ratio: float = 4,
432
+ resolution: tuple[int, int] = (14, 14),
433
+ ):
434
+ """Initialize the Attention module for multi-head attention with spatial awareness.
435
+
436
+ This module implements a multi-head attention mechanism with support for spatial awareness, applying attention
437
+ biases based on spatial resolution. It includes trainable attention biases for each unique offset between
438
+ spatial positions in the resolution grid.
439
+
440
+ Args:
441
+ dim (int): The dimensionality of the input and output.
442
+ key_dim (int): The dimensionality of the keys and queries.
443
+ num_heads (int, optional): Number of attention heads.
444
+ attn_ratio (float, optional): Attention ratio, affecting the dimensions of the value vectors.
445
+ resolution (tuple[int, int], optional): Spatial resolution of the input feature map.
446
+ """
447
+ super().__init__()
448
+
449
+ assert isinstance(resolution, tuple) and len(resolution) == 2, "'resolution' argument not tuple of length 2"
450
+ self.num_heads = num_heads
451
+ self.scale = key_dim**-0.5
452
+ self.key_dim = key_dim
453
+ self.nh_kd = nh_kd = key_dim * num_heads
454
+ self.d = int(attn_ratio * key_dim)
455
+ self.dh = int(attn_ratio * key_dim) * num_heads
456
+ self.attn_ratio = attn_ratio
457
+ h = self.dh + nh_kd * 2
458
+
459
+ self.norm = nn.LayerNorm(dim)
460
+ self.qkv = nn.Linear(dim, h)
461
+ self.proj = nn.Linear(self.dh, dim)
462
+
463
+ points = list(itertools.product(range(resolution[0]), range(resolution[1])))
464
+ N = len(points)
465
+ attention_offsets = {}
466
+ idxs = []
467
+ for p1 in points:
468
+ for p2 in points:
469
+ offset = (abs(p1[0] - p2[0]), abs(p1[1] - p2[1]))
470
+ if offset not in attention_offsets:
471
+ attention_offsets[offset] = len(attention_offsets)
472
+ idxs.append(attention_offsets[offset])
473
+ self.attention_biases = torch.nn.Parameter(torch.zeros(num_heads, len(attention_offsets)))
474
+ self.register_buffer("attention_bias_idxs", torch.LongTensor(idxs).view(N, N), persistent=False)
475
+
476
+ @torch.no_grad()
477
+ def train(self, mode: bool = True):
478
+ """Set the module in training mode and handle the 'ab' attribute for cached attention biases."""
479
+ super().train(mode)
480
+ if mode and hasattr(self, "ab"):
481
+ del self.ab
482
+ else:
483
+ self.ab = self.attention_biases[:, self.attention_bias_idxs]
484
+
485
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
486
+ """Apply multi-head attention with spatial awareness and trainable attention biases."""
487
+ B, N, _ = x.shape # B, N, C
488
+
489
+ # Normalization
490
+ x = self.norm(x)
491
+
492
+ qkv = self.qkv(x)
493
+ # (B, N, num_heads, d)
494
+ q, k, v = qkv.view(B, N, self.num_heads, -1).split([self.key_dim, self.key_dim, self.d], dim=3)
495
+ # (B, num_heads, N, d)
496
+ q = q.permute(0, 2, 1, 3)
497
+ k = k.permute(0, 2, 1, 3)
498
+ v = v.permute(0, 2, 1, 3)
499
+ self.ab = self.ab.to(self.attention_biases.device)
500
+
501
+ attn = (q @ k.transpose(-2, -1)) * self.scale + (
502
+ self.attention_biases[:, self.attention_bias_idxs] if self.training else self.ab
503
+ )
504
+ attn = attn.softmax(dim=-1)
505
+ x = (attn @ v).transpose(1, 2).reshape(B, N, self.dh)
506
+ return self.proj(x)
507
+
508
+
509
+ class TinyViTBlock(nn.Module):
510
+ """TinyViT Block that applies self-attention and a local convolution to the input.
511
+
512
+ This block is a key component of the TinyViT architecture, combining self-attention mechanisms with local
513
+ convolutions to process input features efficiently. It supports windowed attention for computational efficiency and
514
+ includes residual connections.
515
+
516
+ Attributes:
517
+ dim (int): The dimensionality of the input and output.
518
+ input_resolution (tuple[int, int]): Spatial resolution of the input feature map.
519
+ num_heads (int): Number of attention heads.
520
+ window_size (int): Size of the attention window.
521
+ mlp_ratio (float): Ratio of MLP hidden dimension to embedding dimension.
522
+ drop_path (nn.Module): Stochastic depth layer, identity function during inference.
523
+ attn (Attention): Self-attention module.
524
+ mlp (MLP): Multi-layer perceptron module.
525
+ local_conv (Conv2d_BN): Depth-wise local convolution layer.
526
+
527
+ Examples:
528
+ >>> input_tensor = torch.randn(1, 196, 192)
529
+ >>> block = TinyViTBlock(dim=192, input_resolution=(14, 14), num_heads=3)
530
+ >>> output = block(input_tensor)
531
+ >>> print(output.shape)
532
+ torch.Size([1, 196, 192])
533
+ """
534
+
535
+ def __init__(
536
+ self,
537
+ dim: int,
538
+ input_resolution: tuple[int, int],
539
+ num_heads: int,
540
+ window_size: int = 7,
541
+ mlp_ratio: float = 4.0,
542
+ drop: float = 0.0,
543
+ drop_path: float = 0.0,
544
+ local_conv_size: int = 3,
545
+ activation=nn.GELU,
546
+ ):
547
+ """Initialize a TinyViT block with self-attention and local convolution.
548
+
549
+ This block is a key component of the TinyViT architecture, combining self-attention mechanisms with local
550
+ convolutions to process input features efficiently.
551
+
552
+ Args:
553
+ dim (int): Dimensionality of the input and output features.
554
+ input_resolution (tuple[int, int]): Spatial resolution of the input feature map (height, width).
555
+ num_heads (int): Number of attention heads.
556
+ window_size (int, optional): Size of the attention window. Must be greater than 0.
557
+ mlp_ratio (float, optional): Ratio of MLP hidden dimension to embedding dimension.
558
+ drop (float, optional): Dropout rate.
559
+ drop_path (float, optional): Stochastic depth rate.
560
+ local_conv_size (int, optional): Kernel size of the local convolution.
561
+ activation (nn.Module): Activation function for MLP.
562
+ """
563
+ super().__init__()
564
+ self.dim = dim
565
+ self.input_resolution = input_resolution
566
+ self.num_heads = num_heads
567
+ assert window_size > 0, "window_size must be greater than 0"
568
+ self.window_size = window_size
569
+ self.mlp_ratio = mlp_ratio
570
+
571
+ # NOTE: `DropPath` is needed only for training.
572
+ # self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
573
+ self.drop_path = nn.Identity()
574
+
575
+ assert dim % num_heads == 0, "dim must be divisible by num_heads"
576
+ head_dim = dim // num_heads
577
+
578
+ window_resolution = (window_size, window_size)
579
+ self.attn = Attention(dim, head_dim, num_heads, attn_ratio=1, resolution=window_resolution)
580
+
581
+ mlp_hidden_dim = int(dim * mlp_ratio)
582
+ mlp_activation = activation
583
+ self.mlp = MLP(in_features=dim, hidden_features=mlp_hidden_dim, activation=mlp_activation, drop=drop)
584
+
585
+ pad = local_conv_size // 2
586
+ self.local_conv = Conv2d_BN(dim, dim, ks=local_conv_size, stride=1, pad=pad, groups=dim)
587
+
588
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
589
+ """Apply self-attention, local convolution, and MLP operations to the input tensor."""
590
+ h, w = self.input_resolution
591
+ b, hw, c = x.shape # batch, height*width, channels
592
+ assert hw == h * w, "input feature has wrong size"
593
+ res_x = x
594
+ if h == self.window_size and w == self.window_size:
595
+ x = self.attn(x)
596
+ else:
597
+ x = x.view(b, h, w, c)
598
+ pad_b = (self.window_size - h % self.window_size) % self.window_size
599
+ pad_r = (self.window_size - w % self.window_size) % self.window_size
600
+ padding = pad_b > 0 or pad_r > 0
601
+ if padding:
602
+ x = F.pad(x, (0, 0, 0, pad_r, 0, pad_b))
603
+
604
+ pH, pW = h + pad_b, w + pad_r
605
+ nH = pH // self.window_size
606
+ nW = pW // self.window_size
607
+
608
+ # Window partition
609
+ x = (
610
+ x.view(b, nH, self.window_size, nW, self.window_size, c)
611
+ .transpose(2, 3)
612
+ .reshape(b * nH * nW, self.window_size * self.window_size, c)
613
+ )
614
+ x = self.attn(x)
615
+
616
+ # Window reverse
617
+ x = x.view(b, nH, nW, self.window_size, self.window_size, c).transpose(2, 3).reshape(b, pH, pW, c)
618
+ if padding:
619
+ x = x[:, :h, :w].contiguous()
620
+
621
+ x = x.view(b, hw, c)
622
+
623
+ x = res_x + self.drop_path(x)
624
+ x = x.transpose(1, 2).reshape(b, c, h, w)
625
+ x = self.local_conv(x)
626
+ x = x.view(b, c, hw).transpose(1, 2)
627
+
628
+ return x + self.drop_path(self.mlp(x))
629
+
630
+ def extra_repr(self) -> str:
631
+ """Return a string representation of the TinyViTBlock's parameters.
632
+
633
+ This method provides a formatted string containing key information about the TinyViTBlock, including its
634
+ dimension, input resolution, number of attention heads, window size, and MLP ratio.
635
+
636
+ Returns:
637
+ (str): A formatted string containing the block's parameters.
638
+
639
+ Examples:
640
+ >>> block = TinyViTBlock(dim=192, input_resolution=(14, 14), num_heads=3, window_size=7, mlp_ratio=4.0)
641
+ >>> print(block.extra_repr())
642
+ dim=192, input_resolution=(14, 14), num_heads=3, window_size=7, mlp_ratio=4.0
643
+ """
644
+ return (
645
+ f"dim={self.dim}, input_resolution={self.input_resolution}, num_heads={self.num_heads}, "
646
+ f"window_size={self.window_size}, mlp_ratio={self.mlp_ratio}"
647
+ )
648
+
649
+
650
+ class BasicLayer(nn.Module):
651
+ """A basic TinyViT layer for one stage in a TinyViT architecture.
652
+
653
+ This class represents a single layer in the TinyViT model, consisting of multiple TinyViT blocks and an optional
654
+ downsampling operation. It processes features at a specific resolution and dimensionality within the overall
655
+ architecture.
656
+
657
+ Attributes:
658
+ dim (int): The dimensionality of the input and output features.
659
+ input_resolution (tuple[int, int]): Spatial resolution of the input feature map.
660
+ depth (int): Number of TinyViT blocks in this layer.
661
+ use_checkpoint (bool): Whether to use gradient checkpointing to save memory.
662
+ blocks (nn.ModuleList): List of TinyViT blocks that make up this layer.
663
+ downsample (nn.Module | None): Downsample layer at the end of the layer, if specified.
664
+
665
+ Examples:
666
+ >>> input_tensor = torch.randn(1, 3136, 192)
667
+ >>> layer = BasicLayer(dim=192, input_resolution=(56, 56), depth=2, num_heads=3, window_size=7)
668
+ >>> output = layer(input_tensor)
669
+ >>> print(output.shape)
670
+ torch.Size([1, 784, 384])
671
+ """
672
+
673
+ def __init__(
674
+ self,
675
+ dim: int,
676
+ input_resolution: tuple[int, int],
677
+ depth: int,
678
+ num_heads: int,
679
+ window_size: int,
680
+ mlp_ratio: float = 4.0,
681
+ drop: float = 0.0,
682
+ drop_path: float | list[float] = 0.0,
683
+ downsample: nn.Module | None = None,
684
+ use_checkpoint: bool = False,
685
+ local_conv_size: int = 3,
686
+ activation=nn.GELU,
687
+ out_dim: int | None = None,
688
+ ):
689
+ """Initialize a BasicLayer in the TinyViT architecture.
690
+
691
+ This layer consists of multiple TinyViT blocks and an optional downsampling operation. It is designed to process
692
+ feature maps at a specific resolution and dimensionality within the TinyViT model.
693
+
694
+ Args:
695
+ dim (int): Dimensionality of the input and output features.
696
+ input_resolution (tuple[int, int]): Spatial resolution of the input feature map (height, width).
697
+ depth (int): Number of TinyViT blocks in this layer.
698
+ num_heads (int): Number of attention heads in each TinyViT block.
699
+ window_size (int): Size of the local window for attention computation.
700
+ mlp_ratio (float, optional): Ratio of MLP hidden dimension to embedding dimension.
701
+ drop (float, optional): Dropout rate.
702
+ drop_path (float | list[float], optional): Stochastic depth rate. Can be a float or a list of floats for
703
+ each block.
704
+ downsample (nn.Module | None, optional): Downsampling layer at the end of the layer. None to skip
705
+ downsampling.
706
+ use_checkpoint (bool, optional): Whether to use gradient checkpointing to save memory.
707
+ local_conv_size (int, optional): Kernel size for the local convolution in each TinyViT block.
708
+ activation (nn.Module): Activation function used in the MLP.
709
+ out_dim (int | None, optional): Output dimension after downsampling. None means it will be the same as dim.
710
+ """
711
+ super().__init__()
712
+ self.dim = dim
713
+ self.input_resolution = input_resolution
714
+ self.depth = depth
715
+ self.use_checkpoint = use_checkpoint
716
+
717
+ # Build blocks
718
+ self.blocks = nn.ModuleList(
719
+ [
720
+ TinyViTBlock(
721
+ dim=dim,
722
+ input_resolution=input_resolution,
723
+ num_heads=num_heads,
724
+ window_size=window_size,
725
+ mlp_ratio=mlp_ratio,
726
+ drop=drop,
727
+ drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,
728
+ local_conv_size=local_conv_size,
729
+ activation=activation,
730
+ )
731
+ for i in range(depth)
732
+ ]
733
+ )
734
+
735
+ # Patch merging layer
736
+ self.downsample = (
737
+ None
738
+ if downsample is None
739
+ else downsample(input_resolution, dim=dim, out_dim=out_dim, activation=activation)
740
+ )
741
+
742
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
743
+ """Process input through TinyViT blocks and optional downsampling."""
744
+ for blk in self.blocks:
745
+ x = torch.utils.checkpoint(blk, x) if self.use_checkpoint else blk(x) # warn: checkpoint is slow import
746
+ return x if self.downsample is None else self.downsample(x)
747
+
748
+ def extra_repr(self) -> str:
749
+ """Return a string with the layer's parameters for printing."""
750
+ return f"dim={self.dim}, input_resolution={self.input_resolution}, depth={self.depth}"
751
+
752
+
753
+ class TinyViT(nn.Module):
754
+ """TinyViT: A compact vision transformer architecture for efficient image classification and feature extraction.
755
+
756
+ This class implements the TinyViT model, which combines elements of vision transformers and convolutional neural
757
+ networks for improved efficiency and performance on vision tasks. It features hierarchical processing with patch
758
+ embedding, multiple stages of attention and convolution blocks, and a feature refinement neck.
759
+
760
+ Attributes:
761
+ img_size (int): Input image size.
762
+ num_classes (int): Number of classification classes.
763
+ depths (tuple[int, int, int, int]): Number of blocks in each stage.
764
+ num_layers (int): Total number of layers in the network.
765
+ mlp_ratio (float): Ratio of MLP hidden dimension to embedding dimension.
766
+ patch_embed (PatchEmbed): Module for patch embedding.
767
+ patches_resolution (tuple[int, int]): Resolution of embedded patches.
768
+ layers (nn.ModuleList): List of network layers.
769
+ norm_head (nn.LayerNorm): Layer normalization for the classifier head.
770
+ head (nn.Linear): Linear layer for final classification.
771
+ neck (nn.Sequential): Neck module for feature refinement.
772
+
773
+ Examples:
774
+ >>> model = TinyViT(img_size=224, num_classes=1000)
775
+ >>> x = torch.randn(1, 3, 224, 224)
776
+ >>> features = model.forward_features(x)
777
+ >>> print(features.shape)
778
+ torch.Size([1, 256, 56, 56])
779
+ """
780
+
781
+ def __init__(
782
+ self,
783
+ img_size: int = 224,
784
+ in_chans: int = 3,
785
+ num_classes: int = 1000,
786
+ embed_dims: tuple[int, int, int, int] = (96, 192, 384, 768),
787
+ depths: tuple[int, int, int, int] = (2, 2, 6, 2),
788
+ num_heads: tuple[int, int, int, int] = (3, 6, 12, 24),
789
+ window_sizes: tuple[int, int, int, int] = (7, 7, 14, 7),
790
+ mlp_ratio: float = 4.0,
791
+ drop_rate: float = 0.0,
792
+ drop_path_rate: float = 0.1,
793
+ use_checkpoint: bool = False,
794
+ mbconv_expand_ratio: float = 4.0,
795
+ local_conv_size: int = 3,
796
+ layer_lr_decay: float = 1.0,
797
+ ):
798
+ """Initialize the TinyViT model.
799
+
800
+ This constructor sets up the TinyViT architecture, including patch embedding, multiple layers of attention and
801
+ convolution blocks, and a classification head.
802
+
803
+ Args:
804
+ img_size (int, optional): Size of the input image.
805
+ in_chans (int, optional): Number of input channels.
806
+ num_classes (int, optional): Number of classes for classification.
807
+ embed_dims (tuple[int, int, int, int], optional): Embedding dimensions for each stage.
808
+ depths (tuple[int, int, int, int], optional): Number of blocks in each stage.
809
+ num_heads (tuple[int, int, int, int], optional): Number of attention heads in each stage.
810
+ window_sizes (tuple[int, int, int, int], optional): Window sizes for each stage.
811
+ mlp_ratio (float, optional): Ratio of MLP hidden dim to embedding dim.
812
+ drop_rate (float, optional): Dropout rate.
813
+ drop_path_rate (float, optional): Stochastic depth rate.
814
+ use_checkpoint (bool, optional): Whether to use checkpointing to save memory.
815
+ mbconv_expand_ratio (float, optional): Expansion ratio for MBConv layer.
816
+ local_conv_size (int, optional): Kernel size for local convolutions.
817
+ layer_lr_decay (float, optional): Layer-wise learning rate decay factor.
818
+ """
819
+ super().__init__()
820
+ self.img_size = img_size
821
+ self.num_classes = num_classes
822
+ self.depths = depths
823
+ self.num_layers = len(depths)
824
+ self.mlp_ratio = mlp_ratio
825
+
826
+ activation = nn.GELU
827
+
828
+ self.patch_embed = PatchEmbed(
829
+ in_chans=in_chans, embed_dim=embed_dims[0], resolution=img_size, activation=activation
830
+ )
831
+
832
+ patches_resolution = self.patch_embed.patches_resolution
833
+ self.patches_resolution = patches_resolution
834
+
835
+ # Stochastic depth
836
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule
837
+
838
+ # Build layers
839
+ self.layers = nn.ModuleList()
840
+ for i_layer in range(self.num_layers):
841
+ kwargs = dict(
842
+ dim=embed_dims[i_layer],
843
+ input_resolution=(
844
+ patches_resolution[0] // (2 ** (i_layer - 1 if i_layer == 3 else i_layer)),
845
+ patches_resolution[1] // (2 ** (i_layer - 1 if i_layer == 3 else i_layer)),
846
+ ),
847
+ # input_resolution=(patches_resolution[0] // (2 ** i_layer),
848
+ # patches_resolution[1] // (2 ** i_layer)),
849
+ depth=depths[i_layer],
850
+ drop_path=dpr[sum(depths[:i_layer]) : sum(depths[: i_layer + 1])],
851
+ downsample=PatchMerging if (i_layer < self.num_layers - 1) else None,
852
+ use_checkpoint=use_checkpoint,
853
+ out_dim=embed_dims[min(i_layer + 1, len(embed_dims) - 1)],
854
+ activation=activation,
855
+ )
856
+ if i_layer == 0:
857
+ layer = ConvLayer(conv_expand_ratio=mbconv_expand_ratio, **kwargs)
858
+ else:
859
+ layer = BasicLayer(
860
+ num_heads=num_heads[i_layer],
861
+ window_size=window_sizes[i_layer],
862
+ mlp_ratio=self.mlp_ratio,
863
+ drop=drop_rate,
864
+ local_conv_size=local_conv_size,
865
+ **kwargs,
866
+ )
867
+ self.layers.append(layer)
868
+
869
+ # Classifier head
870
+ self.norm_head = nn.LayerNorm(embed_dims[-1])
871
+ self.head = nn.Linear(embed_dims[-1], num_classes) if num_classes > 0 else torch.nn.Identity()
872
+
873
+ # Init weights
874
+ self.apply(self._init_weights)
875
+ self.set_layer_lr_decay(layer_lr_decay)
876
+ self.neck = nn.Sequential(
877
+ nn.Conv2d(
878
+ embed_dims[-1],
879
+ 256,
880
+ kernel_size=1,
881
+ bias=False,
882
+ ),
883
+ LayerNorm2d(256),
884
+ nn.Conv2d(
885
+ 256,
886
+ 256,
887
+ kernel_size=3,
888
+ padding=1,
889
+ bias=False,
890
+ ),
891
+ LayerNorm2d(256),
892
+ )
893
+
894
+ def set_layer_lr_decay(self, layer_lr_decay: float):
895
+ """Set layer-wise learning rate decay for the TinyViT model based on depth."""
896
+ decay_rate = layer_lr_decay
897
+
898
+ # Layers -> blocks (depth)
899
+ depth = sum(self.depths)
900
+ lr_scales = [decay_rate ** (depth - i - 1) for i in range(depth)]
901
+
902
+ def _set_lr_scale(m, scale):
903
+ """Set the learning rate scale for each layer in the model based on the layer's depth."""
904
+ for p in m.parameters():
905
+ p.lr_scale = scale
906
+
907
+ self.patch_embed.apply(lambda x: _set_lr_scale(x, lr_scales[0]))
908
+ i = 0
909
+ for layer in self.layers:
910
+ for block in layer.blocks:
911
+ block.apply(lambda x: _set_lr_scale(x, lr_scales[i]))
912
+ i += 1
913
+ if layer.downsample is not None:
914
+ layer.downsample.apply(lambda x: _set_lr_scale(x, lr_scales[i - 1]))
915
+ assert i == depth
916
+ for m in {self.norm_head, self.head}:
917
+ m.apply(lambda x: _set_lr_scale(x, lr_scales[-1]))
918
+
919
+ for k, p in self.named_parameters():
920
+ p.param_name = k
921
+
922
+ def _check_lr_scale(m):
923
+ """Check if the learning rate scale attribute is present in module's parameters."""
924
+ for p in m.parameters():
925
+ assert hasattr(p, "lr_scale"), p.param_name
926
+
927
+ self.apply(_check_lr_scale)
928
+
929
+ @staticmethod
930
+ def _init_weights(m):
931
+ """Initialize weights for linear and normalization layers in the TinyViT model."""
932
+ if isinstance(m, nn.Linear):
933
+ # NOTE: This initialization is needed only for training.
934
+ # trunc_normal_(m.weight, std=.02)
935
+ if m.bias is not None:
936
+ nn.init.constant_(m.bias, 0)
937
+ elif isinstance(m, nn.LayerNorm):
938
+ nn.init.constant_(m.bias, 0)
939
+ nn.init.constant_(m.weight, 1.0)
940
+
941
+ @torch.jit.ignore
942
+ def no_weight_decay_keywords(self):
943
+ """Return a set of keywords for parameters that should not use weight decay."""
944
+ return {"attention_biases"}
945
+
946
+ def forward_features(self, x: torch.Tensor) -> torch.Tensor:
947
+ """Process input through feature extraction layers, returning spatial features."""
948
+ x = self.patch_embed(x) # x input is (N, C, H, W)
949
+
950
+ x = self.layers[0](x)
951
+ start_i = 1
952
+
953
+ for i in range(start_i, len(self.layers)):
954
+ layer = self.layers[i]
955
+ x = layer(x)
956
+ batch, _, channel = x.shape
957
+ x = x.view(batch, self.patches_resolution[0] // 4, self.patches_resolution[1] // 4, channel)
958
+ x = x.permute(0, 3, 1, 2)
959
+ return self.neck(x)
960
+
961
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
962
+ """Perform the forward pass through the TinyViT model, extracting features from the input image."""
963
+ return self.forward_features(x)
964
+
965
+ def set_imgsz(self, imgsz: list[int] = [1024, 1024]):
966
+ """Set image size to make model compatible with different image sizes."""
967
+ imgsz = [s // 4 for s in imgsz]
968
+ self.patches_resolution = imgsz
969
+ for i, layer in enumerate(self.layers):
970
+ input_resolution = (
971
+ imgsz[0] // (2 ** (i - 1 if i == 3 else i)),
972
+ imgsz[1] // (2 ** (i - 1 if i == 3 else i)),
973
+ )
974
+ layer.input_resolution = input_resolution
975
+ if layer.downsample is not None:
976
+ layer.downsample.input_resolution = input_resolution
977
+ if isinstance(layer, BasicLayer):
978
+ for b in layer.blocks:
979
+ b.input_resolution = input_resolution