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