ultralytics 8.1.28__py3-none-any.whl → 8.3.62__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 (247) hide show
  1. tests/__init__.py +22 -0
  2. tests/conftest.py +83 -0
  3. tests/test_cli.py +122 -0
  4. tests/test_cuda.py +155 -0
  5. tests/test_engine.py +131 -0
  6. tests/test_exports.py +216 -0
  7. tests/test_integrations.py +150 -0
  8. tests/test_python.py +615 -0
  9. tests/test_solutions.py +94 -0
  10. ultralytics/__init__.py +11 -8
  11. ultralytics/cfg/__init__.py +569 -131
  12. ultralytics/cfg/datasets/Argoverse.yaml +2 -1
  13. ultralytics/cfg/datasets/DOTAv1.5.yaml +3 -2
  14. ultralytics/cfg/datasets/DOTAv1.yaml +3 -2
  15. ultralytics/cfg/datasets/GlobalWheat2020.yaml +3 -2
  16. ultralytics/cfg/datasets/ImageNet.yaml +2 -1
  17. ultralytics/cfg/datasets/Objects365.yaml +5 -4
  18. ultralytics/cfg/datasets/SKU-110K.yaml +2 -1
  19. ultralytics/cfg/datasets/VOC.yaml +3 -2
  20. ultralytics/cfg/datasets/VisDrone.yaml +6 -5
  21. ultralytics/cfg/datasets/african-wildlife.yaml +25 -0
  22. ultralytics/cfg/datasets/brain-tumor.yaml +23 -0
  23. ultralytics/cfg/datasets/carparts-seg.yaml +3 -2
  24. ultralytics/cfg/datasets/coco-pose.yaml +7 -6
  25. ultralytics/cfg/datasets/coco.yaml +3 -2
  26. ultralytics/cfg/datasets/coco128-seg.yaml +4 -3
  27. ultralytics/cfg/datasets/coco128.yaml +4 -3
  28. ultralytics/cfg/datasets/coco8-pose.yaml +3 -2
  29. ultralytics/cfg/datasets/coco8-seg.yaml +3 -2
  30. ultralytics/cfg/datasets/coco8.yaml +3 -2
  31. ultralytics/cfg/datasets/crack-seg.yaml +3 -2
  32. ultralytics/cfg/datasets/dog-pose.yaml +24 -0
  33. ultralytics/cfg/datasets/dota8.yaml +3 -2
  34. ultralytics/cfg/datasets/hand-keypoints.yaml +26 -0
  35. ultralytics/cfg/datasets/lvis.yaml +1236 -0
  36. ultralytics/cfg/datasets/medical-pills.yaml +22 -0
  37. ultralytics/cfg/datasets/open-images-v7.yaml +2 -1
  38. ultralytics/cfg/datasets/package-seg.yaml +5 -4
  39. ultralytics/cfg/datasets/signature.yaml +21 -0
  40. ultralytics/cfg/datasets/tiger-pose.yaml +3 -2
  41. ultralytics/cfg/datasets/xView.yaml +2 -1
  42. ultralytics/cfg/default.yaml +14 -11
  43. ultralytics/cfg/models/11/yolo11-cls-resnet18.yaml +24 -0
  44. ultralytics/cfg/models/11/yolo11-cls.yaml +33 -0
  45. ultralytics/cfg/models/11/yolo11-obb.yaml +50 -0
  46. ultralytics/cfg/models/11/yolo11-pose.yaml +51 -0
  47. ultralytics/cfg/models/11/yolo11-seg.yaml +50 -0
  48. ultralytics/cfg/models/11/yolo11.yaml +50 -0
  49. ultralytics/cfg/models/rt-detr/rtdetr-l.yaml +5 -2
  50. ultralytics/cfg/models/rt-detr/rtdetr-resnet101.yaml +5 -2
  51. ultralytics/cfg/models/rt-detr/rtdetr-resnet50.yaml +5 -2
  52. ultralytics/cfg/models/rt-detr/rtdetr-x.yaml +5 -2
  53. ultralytics/cfg/models/v10/yolov10b.yaml +45 -0
  54. ultralytics/cfg/models/v10/yolov10l.yaml +45 -0
  55. ultralytics/cfg/models/v10/yolov10m.yaml +45 -0
  56. ultralytics/cfg/models/v10/yolov10n.yaml +45 -0
  57. ultralytics/cfg/models/v10/yolov10s.yaml +45 -0
  58. ultralytics/cfg/models/v10/yolov10x.yaml +45 -0
  59. ultralytics/cfg/models/v3/yolov3-spp.yaml +5 -2
  60. ultralytics/cfg/models/v3/yolov3-tiny.yaml +5 -2
  61. ultralytics/cfg/models/v3/yolov3.yaml +5 -2
  62. ultralytics/cfg/models/v5/yolov5-p6.yaml +5 -2
  63. ultralytics/cfg/models/v5/yolov5.yaml +5 -2
  64. ultralytics/cfg/models/v6/yolov6.yaml +5 -2
  65. ultralytics/cfg/models/v8/yolov8-cls-resnet101.yaml +5 -2
  66. ultralytics/cfg/models/v8/yolov8-cls-resnet50.yaml +5 -2
  67. ultralytics/cfg/models/v8/yolov8-cls.yaml +5 -2
  68. ultralytics/cfg/models/v8/yolov8-ghost-p2.yaml +6 -2
  69. ultralytics/cfg/models/v8/yolov8-ghost-p6.yaml +6 -2
  70. ultralytics/cfg/models/v8/yolov8-ghost.yaml +5 -2
  71. ultralytics/cfg/models/v8/yolov8-obb.yaml +5 -2
  72. ultralytics/cfg/models/v8/yolov8-p2.yaml +5 -2
  73. ultralytics/cfg/models/v8/yolov8-p6.yaml +10 -7
  74. ultralytics/cfg/models/v8/yolov8-pose-p6.yaml +5 -2
  75. ultralytics/cfg/models/v8/yolov8-pose.yaml +5 -2
  76. ultralytics/cfg/models/v8/yolov8-rtdetr.yaml +5 -2
  77. ultralytics/cfg/models/v8/yolov8-seg-p6.yaml +5 -2
  78. ultralytics/cfg/models/v8/yolov8-seg.yaml +5 -2
  79. ultralytics/cfg/models/v8/yolov8-world.yaml +5 -2
  80. ultralytics/cfg/models/v8/yolov8-worldv2.yaml +5 -2
  81. ultralytics/cfg/models/v8/yolov8.yaml +5 -2
  82. ultralytics/cfg/models/v9/yolov9c-seg.yaml +41 -0
  83. ultralytics/cfg/models/v9/yolov9c.yaml +30 -25
  84. ultralytics/cfg/models/v9/yolov9e-seg.yaml +64 -0
  85. ultralytics/cfg/models/v9/yolov9e.yaml +46 -42
  86. ultralytics/cfg/models/v9/yolov9m.yaml +41 -0
  87. ultralytics/cfg/models/v9/yolov9s.yaml +41 -0
  88. ultralytics/cfg/models/v9/yolov9t.yaml +41 -0
  89. ultralytics/cfg/solutions/default.yaml +24 -0
  90. ultralytics/cfg/trackers/botsort.yaml +8 -5
  91. ultralytics/cfg/trackers/bytetrack.yaml +8 -5
  92. ultralytics/data/__init__.py +14 -3
  93. ultralytics/data/annotator.py +37 -15
  94. ultralytics/data/augment.py +1783 -289
  95. ultralytics/data/base.py +62 -27
  96. ultralytics/data/build.py +36 -8
  97. ultralytics/data/converter.py +196 -36
  98. ultralytics/data/dataset.py +233 -94
  99. ultralytics/data/loaders.py +199 -96
  100. ultralytics/data/split_dota.py +39 -29
  101. ultralytics/data/utils.py +110 -40
  102. ultralytics/engine/__init__.py +1 -1
  103. ultralytics/engine/exporter.py +569 -242
  104. ultralytics/engine/model.py +604 -252
  105. ultralytics/engine/predictor.py +22 -11
  106. ultralytics/engine/results.py +1228 -218
  107. ultralytics/engine/trainer.py +190 -129
  108. ultralytics/engine/tuner.py +18 -18
  109. ultralytics/engine/validator.py +18 -15
  110. ultralytics/hub/__init__.py +31 -13
  111. ultralytics/hub/auth.py +11 -7
  112. ultralytics/hub/google/__init__.py +159 -0
  113. ultralytics/hub/session.py +128 -94
  114. ultralytics/hub/utils.py +20 -21
  115. ultralytics/models/__init__.py +4 -2
  116. ultralytics/models/fastsam/__init__.py +2 -3
  117. ultralytics/models/fastsam/model.py +26 -4
  118. ultralytics/models/fastsam/predict.py +127 -63
  119. ultralytics/models/fastsam/utils.py +1 -44
  120. ultralytics/models/fastsam/val.py +1 -1
  121. ultralytics/models/nas/__init__.py +1 -1
  122. ultralytics/models/nas/model.py +21 -10
  123. ultralytics/models/nas/predict.py +3 -6
  124. ultralytics/models/nas/val.py +4 -4
  125. ultralytics/models/rtdetr/__init__.py +1 -1
  126. ultralytics/models/rtdetr/model.py +1 -1
  127. ultralytics/models/rtdetr/predict.py +6 -8
  128. ultralytics/models/rtdetr/train.py +6 -2
  129. ultralytics/models/rtdetr/val.py +3 -3
  130. ultralytics/models/sam/__init__.py +3 -3
  131. ultralytics/models/sam/amg.py +29 -23
  132. ultralytics/models/sam/build.py +211 -13
  133. ultralytics/models/sam/model.py +91 -30
  134. ultralytics/models/sam/modules/__init__.py +1 -1
  135. ultralytics/models/sam/modules/blocks.py +1129 -0
  136. ultralytics/models/sam/modules/decoders.py +381 -53
  137. ultralytics/models/sam/modules/encoders.py +515 -324
  138. ultralytics/models/sam/modules/memory_attention.py +237 -0
  139. ultralytics/models/sam/modules/sam.py +969 -21
  140. ultralytics/models/sam/modules/tiny_encoder.py +425 -154
  141. ultralytics/models/sam/modules/transformer.py +159 -60
  142. ultralytics/models/sam/modules/utils.py +293 -0
  143. ultralytics/models/sam/predict.py +1263 -132
  144. ultralytics/models/utils/__init__.py +1 -1
  145. ultralytics/models/utils/loss.py +36 -24
  146. ultralytics/models/utils/ops.py +3 -7
  147. ultralytics/models/yolo/__init__.py +3 -3
  148. ultralytics/models/yolo/classify/__init__.py +1 -1
  149. ultralytics/models/yolo/classify/predict.py +7 -8
  150. ultralytics/models/yolo/classify/train.py +17 -22
  151. ultralytics/models/yolo/classify/val.py +8 -4
  152. ultralytics/models/yolo/detect/__init__.py +1 -1
  153. ultralytics/models/yolo/detect/predict.py +3 -5
  154. ultralytics/models/yolo/detect/train.py +11 -4
  155. ultralytics/models/yolo/detect/val.py +90 -52
  156. ultralytics/models/yolo/model.py +14 -9
  157. ultralytics/models/yolo/obb/__init__.py +1 -1
  158. ultralytics/models/yolo/obb/predict.py +2 -2
  159. ultralytics/models/yolo/obb/train.py +5 -3
  160. ultralytics/models/yolo/obb/val.py +41 -23
  161. ultralytics/models/yolo/pose/__init__.py +1 -1
  162. ultralytics/models/yolo/pose/predict.py +3 -5
  163. ultralytics/models/yolo/pose/train.py +2 -2
  164. ultralytics/models/yolo/pose/val.py +51 -17
  165. ultralytics/models/yolo/segment/__init__.py +1 -1
  166. ultralytics/models/yolo/segment/predict.py +3 -5
  167. ultralytics/models/yolo/segment/train.py +2 -2
  168. ultralytics/models/yolo/segment/val.py +60 -19
  169. ultralytics/models/yolo/world/__init__.py +5 -0
  170. ultralytics/models/yolo/world/train.py +92 -0
  171. ultralytics/models/yolo/world/train_world.py +109 -0
  172. ultralytics/nn/__init__.py +1 -1
  173. ultralytics/nn/autobackend.py +228 -93
  174. ultralytics/nn/modules/__init__.py +39 -14
  175. ultralytics/nn/modules/activation.py +21 -0
  176. ultralytics/nn/modules/block.py +527 -67
  177. ultralytics/nn/modules/conv.py +24 -7
  178. ultralytics/nn/modules/head.py +177 -34
  179. ultralytics/nn/modules/transformer.py +6 -5
  180. ultralytics/nn/modules/utils.py +1 -2
  181. ultralytics/nn/tasks.py +225 -77
  182. ultralytics/solutions/__init__.py +30 -1
  183. ultralytics/solutions/ai_gym.py +96 -143
  184. ultralytics/solutions/analytics.py +247 -0
  185. ultralytics/solutions/distance_calculation.py +78 -135
  186. ultralytics/solutions/heatmap.py +93 -247
  187. ultralytics/solutions/object_counter.py +184 -259
  188. ultralytics/solutions/parking_management.py +246 -0
  189. ultralytics/solutions/queue_management.py +112 -0
  190. ultralytics/solutions/region_counter.py +116 -0
  191. ultralytics/solutions/security_alarm.py +144 -0
  192. ultralytics/solutions/solutions.py +178 -0
  193. ultralytics/solutions/speed_estimation.py +86 -174
  194. ultralytics/solutions/streamlit_inference.py +190 -0
  195. ultralytics/solutions/trackzone.py +68 -0
  196. ultralytics/trackers/__init__.py +1 -1
  197. ultralytics/trackers/basetrack.py +32 -13
  198. ultralytics/trackers/bot_sort.py +61 -28
  199. ultralytics/trackers/byte_tracker.py +83 -51
  200. ultralytics/trackers/track.py +21 -6
  201. ultralytics/trackers/utils/__init__.py +1 -1
  202. ultralytics/trackers/utils/gmc.py +62 -48
  203. ultralytics/trackers/utils/kalman_filter.py +166 -35
  204. ultralytics/trackers/utils/matching.py +40 -21
  205. ultralytics/utils/__init__.py +511 -239
  206. ultralytics/utils/autobatch.py +40 -22
  207. ultralytics/utils/benchmarks.py +266 -85
  208. ultralytics/utils/callbacks/__init__.py +1 -1
  209. ultralytics/utils/callbacks/base.py +1 -3
  210. ultralytics/utils/callbacks/clearml.py +7 -6
  211. ultralytics/utils/callbacks/comet.py +39 -17
  212. ultralytics/utils/callbacks/dvc.py +1 -1
  213. ultralytics/utils/callbacks/hub.py +16 -16
  214. ultralytics/utils/callbacks/mlflow.py +28 -24
  215. ultralytics/utils/callbacks/neptune.py +6 -2
  216. ultralytics/utils/callbacks/raytune.py +3 -4
  217. ultralytics/utils/callbacks/tensorboard.py +18 -18
  218. ultralytics/utils/callbacks/wb.py +27 -20
  219. ultralytics/utils/checks.py +160 -100
  220. ultralytics/utils/dist.py +2 -1
  221. ultralytics/utils/downloads.py +44 -37
  222. ultralytics/utils/errors.py +1 -1
  223. ultralytics/utils/files.py +72 -38
  224. ultralytics/utils/instance.py +41 -19
  225. ultralytics/utils/loss.py +84 -56
  226. ultralytics/utils/metrics.py +61 -56
  227. ultralytics/utils/ops.py +94 -89
  228. ultralytics/utils/patches.py +30 -14
  229. ultralytics/utils/plotting.py +600 -269
  230. ultralytics/utils/tal.py +67 -26
  231. ultralytics/utils/torch_utils.py +302 -102
  232. ultralytics/utils/triton.py +2 -1
  233. ultralytics/utils/tuner.py +21 -12
  234. ultralytics-8.3.62.dist-info/METADATA +370 -0
  235. ultralytics-8.3.62.dist-info/RECORD +241 -0
  236. {ultralytics-8.1.28.dist-info → ultralytics-8.3.62.dist-info}/WHEEL +1 -1
  237. ultralytics/data/explorer/__init__.py +0 -5
  238. ultralytics/data/explorer/explorer.py +0 -472
  239. ultralytics/data/explorer/gui/__init__.py +0 -1
  240. ultralytics/data/explorer/gui/dash.py +0 -268
  241. ultralytics/data/explorer/utils.py +0 -166
  242. ultralytics/models/fastsam/prompt.py +0 -357
  243. ultralytics-8.1.28.dist-info/METADATA +0 -373
  244. ultralytics-8.1.28.dist-info/RECORD +0 -197
  245. {ultralytics-8.1.28.dist-info → ultralytics-8.3.62.dist-info}/LICENSE +0 -0
  246. {ultralytics-8.1.28.dist-info → ultralytics-8.3.62.dist-info}/entry_points.txt +0 -0
  247. {ultralytics-8.1.28.dist-info → ultralytics-8.3.62.dist-info}/top_level.txt +0 -0
@@ -1,4 +1,4 @@
1
- # Ultralytics YOLO 🚀, AGPL-3.0 license
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
2
 
3
3
  # --------------------------------------------------------
4
4
  # TinyViT Model Architecture
@@ -17,16 +17,40 @@ import torch.nn as nn
17
17
  import torch.nn.functional as F
18
18
  import torch.utils.checkpoint as checkpoint
19
19
 
20
+ from ultralytics.nn.modules import LayerNorm2d
20
21
  from ultralytics.utils.instance import to_2tuple
21
22
 
22
23
 
23
24
  class Conv2d_BN(torch.nn.Sequential):
24
- """A sequential container that performs 2D convolution followed by batch normalization."""
25
+ """
26
+ A sequential container that performs 2D convolution followed by batch normalization.
27
+
28
+ Attributes:
29
+ c (torch.nn.Conv2d): 2D convolution layer.
30
+ 1 (torch.nn.BatchNorm2d): Batch normalization layer.
31
+
32
+ Methods:
33
+ __init__: Initializes the Conv2d_BN with specified parameters.
34
+
35
+ Args:
36
+ a (int): Number of input channels.
37
+ b (int): Number of output channels.
38
+ ks (int): Kernel size for the convolution. Defaults to 1.
39
+ stride (int): Stride for the convolution. Defaults to 1.
40
+ pad (int): Padding for the convolution. Defaults to 0.
41
+ dilation (int): Dilation factor for the convolution. Defaults to 1.
42
+ groups (int): Number of groups for the convolution. Defaults to 1.
43
+ bn_weight_init (float): Initial value for batch normalization weight. Defaults to 1.
44
+
45
+ Examples:
46
+ >>> conv_bn = Conv2d_BN(3, 64, ks=3, stride=1, pad=1)
47
+ >>> input_tensor = torch.randn(1, 3, 224, 224)
48
+ >>> output = conv_bn(input_tensor)
49
+ >>> print(output.shape)
50
+ """
25
51
 
26
52
  def __init__(self, a, b, ks=1, stride=1, pad=0, dilation=1, groups=1, bn_weight_init=1):
27
- """Initializes the MBConv model with given input channels, output channels, expansion ratio, activation, and
28
- drop path.
29
- """
53
+ """Initializes a sequential container with 2D convolution followed by batch normalization."""
30
54
  super().__init__()
31
55
  self.add_module("c", torch.nn.Conv2d(a, b, ks, stride, pad, dilation, groups, bias=False))
32
56
  bn = torch.nn.BatchNorm2d(b)
@@ -36,12 +60,29 @@ class Conv2d_BN(torch.nn.Sequential):
36
60
 
37
61
 
38
62
  class PatchEmbed(nn.Module):
39
- """Embeds images into patches and projects them into a specified embedding dimension."""
63
+ """
64
+ Embeds images into patches and projects them into a specified embedding dimension.
65
+
66
+ Attributes:
67
+ patches_resolution (Tuple[int, int]): Resolution of the patches after embedding.
68
+ num_patches (int): Total number of patches.
69
+ in_chans (int): Number of input channels.
70
+ embed_dim (int): Dimension of the embedding.
71
+ seq (nn.Sequential): Sequence of convolutional and activation layers for patch embedding.
72
+
73
+ Methods:
74
+ forward: Processes the input tensor through the patch embedding sequence.
75
+
76
+ Examples:
77
+ >>> import torch
78
+ >>> patch_embed = PatchEmbed(in_chans=3, embed_dim=96, resolution=224, activation=nn.GELU)
79
+ >>> x = torch.randn(1, 3, 224, 224)
80
+ >>> output = patch_embed(x)
81
+ >>> print(output.shape)
82
+ """
40
83
 
41
84
  def __init__(self, in_chans, embed_dim, resolution, activation):
42
- """Initialize the PatchMerging class with specified input, output dimensions, resolution and activation
43
- function.
44
- """
85
+ """Initializes patch embedding with convolutional layers for image-to-patch conversion and projection."""
45
86
  super().__init__()
46
87
  img_size: Tuple[int, int] = to_2tuple(resolution)
47
88
  self.patches_resolution = (img_size[0] // 4, img_size[1] // 4)
@@ -56,17 +97,40 @@ class PatchEmbed(nn.Module):
56
97
  )
57
98
 
58
99
  def forward(self, x):
59
- """Runs input tensor 'x' through the PatchMerging model's sequence of operations."""
100
+ """Processes input tensor through patch embedding sequence, converting images to patch embeddings."""
60
101
  return self.seq(x)
61
102
 
62
103
 
63
104
  class MBConv(nn.Module):
64
- """Mobile Inverted Bottleneck Conv (MBConv) layer, part of the EfficientNet architecture."""
105
+ """
106
+ Mobile Inverted Bottleneck Conv (MBConv) layer, part of the EfficientNet architecture.
107
+
108
+ Attributes:
109
+ in_chans (int): Number of input channels.
110
+ hidden_chans (int): Number of hidden channels.
111
+ out_chans (int): Number of output channels.
112
+ conv1 (Conv2d_BN): First convolutional layer.
113
+ act1 (nn.Module): First activation function.
114
+ conv2 (Conv2d_BN): Depthwise convolutional layer.
115
+ act2 (nn.Module): Second activation function.
116
+ conv3 (Conv2d_BN): Final convolutional layer.
117
+ act3 (nn.Module): Third activation function.
118
+ drop_path (nn.Module): Drop path layer (Identity for inference).
119
+
120
+ Methods:
121
+ forward: Performs the forward pass through the MBConv layer.
122
+
123
+ Examples:
124
+ >>> in_chans, out_chans = 32, 64
125
+ >>> mbconv = MBConv(in_chans, out_chans, expand_ratio=4, activation=nn.ReLU, drop_path=0.1)
126
+ >>> x = torch.randn(1, in_chans, 56, 56)
127
+ >>> output = mbconv(x)
128
+ >>> print(output.shape)
129
+ torch.Size([1, 64, 56, 56])
130
+ """
65
131
 
66
132
  def __init__(self, in_chans, out_chans, expand_ratio, activation, drop_path):
67
- """Initializes a convolutional layer with specified dimensions, input resolution, depth, and activation
68
- function.
69
- """
133
+ """Initializes the MBConv layer with specified input/output channels, expansion ratio, and activation."""
70
134
  super().__init__()
71
135
  self.in_chans = in_chans
72
136
  self.hidden_chans = int(in_chans * expand_ratio)
@@ -86,7 +150,7 @@ class MBConv(nn.Module):
86
150
  self.drop_path = nn.Identity()
87
151
 
88
152
  def forward(self, x):
89
- """Implements the forward pass for the model architecture."""
153
+ """Implements the forward pass of MBConv, applying convolutions and skip connection."""
90
154
  shortcut = x
91
155
  x = self.conv1(x)
92
156
  x = self.act1(x)
@@ -99,12 +163,34 @@ class MBConv(nn.Module):
99
163
 
100
164
 
101
165
  class PatchMerging(nn.Module):
102
- """Merges neighboring patches in the feature map and projects to a new dimension."""
166
+ """
167
+ Merges neighboring patches in the feature map and projects to a new dimension.
168
+
169
+ This class implements a patch merging operation that combines spatial information and adjusts the feature
170
+ dimension. It uses a series of convolutional layers with batch normalization to achieve this.
171
+
172
+ Attributes:
173
+ input_resolution (Tuple[int, int]): The input resolution (height, width) of the feature map.
174
+ dim (int): The input dimension of the feature map.
175
+ out_dim (int): The output dimension after merging and projection.
176
+ act (nn.Module): The activation function used between convolutions.
177
+ conv1 (Conv2d_BN): The first convolutional layer for dimension projection.
178
+ conv2 (Conv2d_BN): The second convolutional layer for spatial merging.
179
+ conv3 (Conv2d_BN): The third convolutional layer for final projection.
180
+
181
+ Methods:
182
+ forward: Applies the patch merging operation to the input tensor.
183
+
184
+ Examples:
185
+ >>> input_resolution = (56, 56)
186
+ >>> patch_merging = PatchMerging(input_resolution, dim=64, out_dim=128, activation=nn.ReLU)
187
+ >>> x = torch.randn(4, 64, 56, 56)
188
+ >>> output = patch_merging(x)
189
+ >>> print(output.shape)
190
+ """
103
191
 
104
192
  def __init__(self, input_resolution, dim, out_dim, activation):
105
- """Initializes the ConvLayer with specific dimension, input resolution, depth, activation, drop path, and other
106
- optional parameters.
107
- """
193
+ """Initializes the PatchMerging module for merging and projecting neighboring patches in feature maps."""
108
194
  super().__init__()
109
195
 
110
196
  self.input_resolution = input_resolution
@@ -112,12 +198,12 @@ class PatchMerging(nn.Module):
112
198
  self.out_dim = out_dim
113
199
  self.act = activation()
114
200
  self.conv1 = Conv2d_BN(dim, out_dim, 1, 1, 0)
115
- stride_c = 1 if out_dim in [320, 448, 576] else 2
201
+ stride_c = 1 if out_dim in {320, 448, 576} else 2
116
202
  self.conv2 = Conv2d_BN(out_dim, out_dim, 3, stride_c, 1, groups=out_dim)
117
203
  self.conv3 = Conv2d_BN(out_dim, out_dim, 1, 1, 0)
118
204
 
119
205
  def forward(self, x):
120
- """Applies forward pass on the input utilizing convolution and activation layers, and returns the result."""
206
+ """Applies patch merging and dimension projection to the input feature map."""
121
207
  if x.ndim == 3:
122
208
  H, W = self.input_resolution
123
209
  B = len(x)
@@ -137,7 +223,24 @@ class ConvLayer(nn.Module):
137
223
  """
138
224
  Convolutional Layer featuring multiple MobileNetV3-style inverted bottleneck convolutions (MBConv).
139
225
 
140
- Optionally applies downsample operations to the output, and provides support for gradient checkpointing.
226
+ This layer optionally applies downsample operations to the output and supports gradient checkpointing.
227
+
228
+ Attributes:
229
+ dim (int): Dimensionality of the input and output.
230
+ input_resolution (Tuple[int, int]): Resolution of the input image.
231
+ depth (int): Number of MBConv layers in the block.
232
+ use_checkpoint (bool): Whether to use gradient checkpointing to save memory.
233
+ blocks (nn.ModuleList): List of MBConv layers.
234
+ downsample (Optional[Callable]): Function for downsampling the output.
235
+
236
+ Methods:
237
+ forward: Processes the input through the convolutional layers.
238
+
239
+ Examples:
240
+ >>> input_tensor = torch.randn(1, 64, 56, 56)
241
+ >>> conv_layer = ConvLayer(64, (56, 56), depth=3, activation=nn.ReLU)
242
+ >>> output = conv_layer(input_tensor)
243
+ >>> print(output.shape)
141
244
  """
142
245
 
143
246
  def __init__(
@@ -155,16 +258,25 @@ class ConvLayer(nn.Module):
155
258
  """
156
259
  Initializes the ConvLayer with the given dimensions and settings.
157
260
 
261
+ This layer consists of multiple MobileNetV3-style inverted bottleneck convolutions (MBConv) and
262
+ optionally applies downsampling to the output.
263
+
158
264
  Args:
159
265
  dim (int): The dimensionality of the input and output.
160
266
  input_resolution (Tuple[int, int]): The resolution of the input image.
161
267
  depth (int): The number of MBConv layers in the block.
162
268
  activation (Callable): Activation function applied after each convolution.
163
- drop_path (Union[float, List[float]]): Drop path rate. Single float or a list of floats for each MBConv.
269
+ drop_path (float | List[float]): Drop path rate. Single float or a list of floats for each MBConv.
164
270
  downsample (Optional[Callable]): Function for downsampling the output. None to skip downsampling.
165
271
  use_checkpoint (bool): Whether to use gradient checkpointing to save memory.
166
272
  out_dim (Optional[int]): The dimensionality of the output. None means it will be the same as `dim`.
167
273
  conv_expand_ratio (float): Expansion ratio for the MBConv layers.
274
+
275
+ Examples:
276
+ >>> input_tensor = torch.randn(1, 64, 56, 56)
277
+ >>> conv_layer = ConvLayer(64, (56, 56), depth=3, activation=nn.ReLU)
278
+ >>> output = conv_layer(input_tensor)
279
+ >>> print(output.shape)
168
280
  """
169
281
  super().__init__()
170
282
  self.dim = dim
@@ -194,7 +306,7 @@ class ConvLayer(nn.Module):
194
306
  )
195
307
 
196
308
  def forward(self, x):
197
- """Processes the input through a series of convolutional layers and returns the activated output."""
309
+ """Processes input through convolutional layers, applying MBConv blocks and optional downsampling."""
198
310
  for blk in self.blocks:
199
311
  x = checkpoint.checkpoint(blk, x) if self.use_checkpoint else blk(x)
200
312
  return x if self.downsample is None else self.downsample(x)
@@ -202,13 +314,33 @@ class ConvLayer(nn.Module):
202
314
 
203
315
  class Mlp(nn.Module):
204
316
  """
205
- Multi-layer Perceptron (MLP) for transformer architectures.
317
+ Multi-layer Perceptron (MLP) module for transformer architectures.
318
+
319
+ This module applies layer normalization, two fully-connected layers with an activation function in between,
320
+ and dropout. It is commonly used in transformer-based architectures.
206
321
 
207
- This layer takes an input with in_features, applies layer normalization and two fully-connected layers.
322
+ Attributes:
323
+ norm (nn.LayerNorm): Layer normalization applied to the input.
324
+ fc1 (nn.Linear): First fully-connected layer.
325
+ fc2 (nn.Linear): Second fully-connected layer.
326
+ act (nn.Module): Activation function applied after the first fully-connected layer.
327
+ drop (nn.Dropout): Dropout layer applied after the activation function.
328
+
329
+ Methods:
330
+ forward: Applies the MLP operations on the input tensor.
331
+
332
+ Examples:
333
+ >>> import torch
334
+ >>> from torch import nn
335
+ >>> mlp = Mlp(in_features=256, hidden_features=512, out_features=256, act_layer=nn.GELU, drop=0.1)
336
+ >>> x = torch.randn(32, 100, 256)
337
+ >>> output = mlp(x)
338
+ >>> print(output.shape)
339
+ torch.Size([32, 100, 256])
208
340
  """
209
341
 
210
342
  def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.0):
211
- """Initializes Attention module with the given parameters including dimension, key_dim, number of heads, etc."""
343
+ """Initializes a multi-layer perceptron with configurable input, hidden, and output dimensions."""
212
344
  super().__init__()
213
345
  out_features = out_features or in_features
214
346
  hidden_features = hidden_features or in_features
@@ -219,7 +351,7 @@ class Mlp(nn.Module):
219
351
  self.drop = nn.Dropout(drop)
220
352
 
221
353
  def forward(self, x):
222
- """Applies operations on input x and returns modified x, runs downsample if not None."""
354
+ """Applies MLP operations: layer norm, FC layers, activation, and dropout to the input tensor."""
223
355
  x = self.norm(x)
224
356
  x = self.fc1(x)
225
357
  x = self.act(x)
@@ -230,12 +362,37 @@ class Mlp(nn.Module):
230
362
 
231
363
  class Attention(torch.nn.Module):
232
364
  """
233
- Multi-head attention module with support for spatial awareness, applying attention biases based on spatial
234
- resolution. Implements trainable attention biases for each unique offset between spatial positions in the resolution
235
- grid.
365
+ Multi-head attention module with spatial awareness and trainable attention biases.
366
+
367
+ This module implements a multi-head attention mechanism with support for spatial awareness, applying
368
+ attention biases based on spatial resolution. It includes trainable attention biases for each unique
369
+ offset between spatial positions in the resolution grid.
236
370
 
237
371
  Attributes:
238
- ab (Tensor, optional): Cached attention biases for inference, deleted during training.
372
+ num_heads (int): Number of attention heads.
373
+ scale (float): Scaling factor for attention scores.
374
+ key_dim (int): Dimensionality of the keys and queries.
375
+ nh_kd (int): Product of num_heads and key_dim.
376
+ d (int): Dimensionality of the value vectors.
377
+ dh (int): Product of d and num_heads.
378
+ attn_ratio (float): Attention ratio affecting the dimensions of the value vectors.
379
+ norm (nn.LayerNorm): Layer normalization applied to input.
380
+ qkv (nn.Linear): Linear layer for computing query, key, and value projections.
381
+ proj (nn.Linear): Linear layer for final projection.
382
+ attention_biases (nn.Parameter): Learnable attention biases.
383
+ attention_bias_idxs (Tensor): Indices for attention biases.
384
+ ab (Tensor): Cached attention biases for inference, deleted during training.
385
+
386
+ Methods:
387
+ train: Sets the module in training mode and handles the 'ab' attribute.
388
+ forward: Performs the forward pass of the attention mechanism.
389
+
390
+ Examples:
391
+ >>> attn = Attention(dim=256, key_dim=64, num_heads=8, resolution=(14, 14))
392
+ >>> x = torch.randn(1, 196, 256)
393
+ >>> output = attn(x)
394
+ >>> print(output.shape)
395
+ torch.Size([1, 196, 256])
239
396
  """
240
397
 
241
398
  def __init__(
@@ -247,21 +404,32 @@ class Attention(torch.nn.Module):
247
404
  resolution=(14, 14),
248
405
  ):
249
406
  """
250
- Initializes the Attention module.
407
+ Initializes the Attention module for multi-head attention with spatial awareness.
408
+
409
+ This module implements a multi-head attention mechanism with support for spatial awareness, applying
410
+ attention biases based on spatial resolution. It includes trainable attention biases for each unique
411
+ offset between spatial positions in the resolution grid.
251
412
 
252
413
  Args:
253
414
  dim (int): The dimensionality of the input and output.
254
415
  key_dim (int): The dimensionality of the keys and queries.
255
- num_heads (int, optional): Number of attention heads. Default is 8.
256
- attn_ratio (float, optional): Attention ratio, affecting the dimensions of the value vectors. Default is 4.
257
- resolution (Tuple[int, int], optional): Spatial resolution of the input feature map. Default is (14, 14).
416
+ num_heads (int): Number of attention heads. Default is 8.
417
+ attn_ratio (float): Attention ratio, affecting the dimensions of the value vectors. Default is 4.
418
+ resolution (Tuple[int, int]): Spatial resolution of the input feature map. Default is (14, 14).
258
419
 
259
420
  Raises:
260
- AssertionError: If `resolution` is not a tuple of length 2.
421
+ AssertionError: If 'resolution' is not a tuple of length 2.
422
+
423
+ Examples:
424
+ >>> attn = Attention(dim=256, key_dim=64, num_heads=8, resolution=(14, 14))
425
+ >>> x = torch.randn(1, 196, 256)
426
+ >>> output = attn(x)
427
+ >>> print(output.shape)
428
+ torch.Size([1, 196, 256])
261
429
  """
262
430
  super().__init__()
263
431
 
264
- assert isinstance(resolution, tuple) and len(resolution) == 2
432
+ assert isinstance(resolution, tuple) and len(resolution) == 2, "'resolution' argument not tuple of length 2"
265
433
  self.num_heads = num_heads
266
434
  self.scale = key_dim**-0.5
267
435
  self.key_dim = key_dim
@@ -290,7 +458,7 @@ class Attention(torch.nn.Module):
290
458
 
291
459
  @torch.no_grad()
292
460
  def train(self, mode=True):
293
- """Sets the module in training mode and handles attribute 'ab' based on the mode."""
461
+ """Performs multi-head attention with spatial awareness and trainable attention biases."""
294
462
  super().train(mode)
295
463
  if mode and hasattr(self, "ab"):
296
464
  del self.ab
@@ -298,7 +466,7 @@ class Attention(torch.nn.Module):
298
466
  self.ab = self.attention_biases[:, self.attention_bias_idxs]
299
467
 
300
468
  def forward(self, x): # x
301
- """Performs forward pass over the input tensor 'x' by applying normalization and querying keys/values."""
469
+ """Applies multi-head attention with spatial awareness and trainable attention biases."""
302
470
  B, N, _ = x.shape # B, N, C
303
471
 
304
472
  # Normalization
@@ -322,7 +490,34 @@ class Attention(torch.nn.Module):
322
490
 
323
491
 
324
492
  class TinyViTBlock(nn.Module):
325
- """TinyViT Block that applies self-attention and a local convolution to the input."""
493
+ """
494
+ TinyViT Block that applies self-attention and a local convolution to the input.
495
+
496
+ This block is a key component of the TinyViT architecture, combining self-attention mechanisms with
497
+ local convolutions to process input features efficiently.
498
+
499
+ Attributes:
500
+ dim (int): The dimensionality of the input and output.
501
+ input_resolution (Tuple[int, int]): Spatial resolution of the input feature map.
502
+ num_heads (int): Number of attention heads.
503
+ window_size (int): Size of the attention window.
504
+ mlp_ratio (float): Ratio of MLP hidden dimension to embedding dimension.
505
+ drop_path (nn.Module): Stochastic depth layer, identity function during inference.
506
+ attn (Attention): Self-attention module.
507
+ mlp (Mlp): Multi-layer perceptron module.
508
+ local_conv (Conv2d_BN): Depth-wise local convolution layer.
509
+
510
+ Methods:
511
+ forward: Processes the input through the TinyViT block.
512
+ extra_repr: Returns a string with extra information about the block's parameters.
513
+
514
+ Examples:
515
+ >>> input_tensor = torch.randn(1, 196, 192)
516
+ >>> block = TinyViTBlock(dim=192, input_resolution=(14, 14), num_heads=3)
517
+ >>> output = block(input_tensor)
518
+ >>> print(output.shape)
519
+ torch.Size([1, 196, 192])
520
+ """
326
521
 
327
522
  def __init__(
328
523
  self,
@@ -337,22 +532,32 @@ class TinyViTBlock(nn.Module):
337
532
  activation=nn.GELU,
338
533
  ):
339
534
  """
340
- Initializes the TinyViTBlock.
535
+ Initializes a TinyViT block with self-attention and local convolution.
536
+
537
+ This block is a key component of the TinyViT architecture, combining self-attention mechanisms with
538
+ local convolutions to process input features efficiently.
341
539
 
342
540
  Args:
343
- dim (int): The dimensionality of the input and output.
344
- input_resolution (Tuple[int, int]): Spatial resolution of the input feature map.
541
+ dim (int): Dimensionality of the input and output features.
542
+ input_resolution (Tuple[int, int]): Spatial resolution of the input feature map (height, width).
345
543
  num_heads (int): Number of attention heads.
346
- window_size (int, optional): Window size for attention. Default is 7.
347
- mlp_ratio (float, optional): Ratio of mlp hidden dim to embedding dim. Default is 4.
348
- drop (float, optional): Dropout rate. Default is 0.
349
- drop_path (float, optional): Stochastic depth rate. Default is 0.
350
- local_conv_size (int, optional): The kernel size of the local convolution. Default is 3.
351
- activation (torch.nn, optional): Activation function for MLP. Default is nn.GELU.
544
+ window_size (int): Size of the attention window. Must be greater than 0.
545
+ mlp_ratio (float): Ratio of MLP hidden dimension to embedding dimension.
546
+ drop (float): Dropout rate.
547
+ drop_path (float): Stochastic depth rate.
548
+ local_conv_size (int): Kernel size of the local convolution.
549
+ activation (torch.nn.Module): Activation function for MLP.
352
550
 
353
551
  Raises:
354
- AssertionError: If `window_size` is not greater than 0.
355
- AssertionError: If `dim` is not divisible by `num_heads`.
552
+ AssertionError: If window_size is not greater than 0.
553
+ AssertionError: If dim is not divisible by num_heads.
554
+
555
+ Examples:
556
+ >>> block = TinyViTBlock(dim=192, input_resolution=(14, 14), num_heads=3)
557
+ >>> input_tensor = torch.randn(1, 196, 192)
558
+ >>> output = block(input_tensor)
559
+ >>> print(output.shape)
560
+ torch.Size([1, 196, 192])
356
561
  """
357
562
  super().__init__()
358
563
  self.dim = dim
@@ -380,53 +585,61 @@ class TinyViTBlock(nn.Module):
380
585
  self.local_conv = Conv2d_BN(dim, dim, ks=local_conv_size, stride=1, pad=pad, groups=dim)
381
586
 
382
587
  def forward(self, x):
383
- """Applies attention-based transformation or padding to input 'x' before passing it through a local
384
- convolution.
385
- """
386
- H, W = self.input_resolution
387
- B, L, C = x.shape
388
- assert L == H * W, "input feature has wrong size"
588
+ """Applies self-attention, local convolution, and MLP operations to the input tensor."""
589
+ h, w = self.input_resolution
590
+ b, hw, c = x.shape # batch, height*width, channels
591
+ assert hw == h * w, "input feature has wrong size"
389
592
  res_x = x
390
- if H == self.window_size and W == self.window_size:
593
+ if h == self.window_size and w == self.window_size:
391
594
  x = self.attn(x)
392
595
  else:
393
- x = x.view(B, H, W, C)
394
- pad_b = (self.window_size - H % self.window_size) % self.window_size
395
- pad_r = (self.window_size - W % self.window_size) % self.window_size
596
+ x = x.view(b, h, w, c)
597
+ pad_b = (self.window_size - h % self.window_size) % self.window_size
598
+ pad_r = (self.window_size - w % self.window_size) % self.window_size
396
599
  padding = pad_b > 0 or pad_r > 0
397
-
398
600
  if padding:
399
601
  x = F.pad(x, (0, 0, 0, pad_r, 0, pad_b))
400
602
 
401
- pH, pW = H + pad_b, W + pad_r
603
+ pH, pW = h + pad_b, w + pad_r
402
604
  nH = pH // self.window_size
403
605
  nW = pW // self.window_size
606
+
404
607
  # Window partition
405
608
  x = (
406
- x.view(B, nH, self.window_size, nW, self.window_size, C)
609
+ x.view(b, nH, self.window_size, nW, self.window_size, c)
407
610
  .transpose(2, 3)
408
- .reshape(B * nH * nW, self.window_size * self.window_size, C)
611
+ .reshape(b * nH * nW, self.window_size * self.window_size, c)
409
612
  )
410
613
  x = self.attn(x)
411
- # Window reverse
412
- x = x.view(B, nH, nW, self.window_size, self.window_size, C).transpose(2, 3).reshape(B, pH, pW, C)
413
614
 
615
+ # Window reverse
616
+ x = x.view(b, nH, nW, self.window_size, self.window_size, c).transpose(2, 3).reshape(b, pH, pW, c)
414
617
  if padding:
415
- x = x[:, :H, :W].contiguous()
618
+ x = x[:, :h, :w].contiguous()
416
619
 
417
- x = x.view(B, L, C)
620
+ x = x.view(b, hw, c)
418
621
 
419
622
  x = res_x + self.drop_path(x)
420
-
421
- x = x.transpose(1, 2).reshape(B, C, H, W)
623
+ x = x.transpose(1, 2).reshape(b, c, h, w)
422
624
  x = self.local_conv(x)
423
- x = x.view(B, C, L).transpose(1, 2)
625
+ x = x.view(b, c, hw).transpose(1, 2)
424
626
 
425
627
  return x + self.drop_path(self.mlp(x))
426
628
 
427
629
  def extra_repr(self) -> str:
428
- """Returns a formatted string representing the TinyViTBlock's parameters: dimension, input resolution, number of
429
- attentions heads, window size, and MLP ratio.
630
+ """
631
+ Returns 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
430
643
  """
431
644
  return (
432
645
  f"dim={self.dim}, input_resolution={self.input_resolution}, num_heads={self.num_heads}, "
@@ -435,7 +648,31 @@ class TinyViTBlock(nn.Module):
435
648
 
436
649
 
437
650
  class BasicLayer(nn.Module):
438
- """A basic TinyViT layer for one stage in a TinyViT architecture."""
651
+ """
652
+ A basic TinyViT layer for one stage in a TinyViT architecture.
653
+
654
+ This class represents a single layer in the TinyViT model, consisting of multiple TinyViT blocks
655
+ and an optional downsampling operation.
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
+ Methods:
666
+ forward: Processes the input through the layer's blocks and optional downsampling.
667
+ extra_repr: Returns a string with the layer's parameters for printing.
668
+
669
+ Examples:
670
+ >>> input_tensor = torch.randn(1, 3136, 192)
671
+ >>> layer = BasicLayer(dim=192, input_resolution=(56, 56), depth=2, num_heads=3, window_size=7)
672
+ >>> output = layer(input_tensor)
673
+ >>> print(output.shape)
674
+ torch.Size([1, 784, 384])
675
+ """
439
676
 
440
677
  def __init__(
441
678
  self,
@@ -454,25 +691,34 @@ class BasicLayer(nn.Module):
454
691
  out_dim=None,
455
692
  ):
456
693
  """
457
- Initializes the BasicLayer.
694
+ Initializes a BasicLayer in the TinyViT architecture.
695
+
696
+ This layer consists of multiple TinyViT blocks and an optional downsampling operation. It is designed to
697
+ process feature maps at a specific resolution and dimensionality within the TinyViT model.
458
698
 
459
699
  Args:
460
- dim (int): The dimensionality of the input and output.
461
- input_resolution (Tuple[int, int]): Spatial resolution of the input feature map.
462
- depth (int): Number of TinyViT blocks.
463
- num_heads (int): Number of attention heads.
464
- window_size (int): Local window size.
465
- mlp_ratio (float, optional): Ratio of mlp hidden dim to embedding dim. Default is 4.
466
- drop (float, optional): Dropout rate. Default is 0.
467
- drop_path (float | tuple[float], optional): Stochastic depth rate. Default is 0.
468
- downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default is None.
469
- use_checkpoint (bool, optional): Whether to use checkpointing to save memory. Default is False.
470
- local_conv_size (int, optional): Kernel size of the local convolution. Default is 3.
471
- activation (torch.nn, optional): Activation function for MLP. Default is nn.GELU.
472
- out_dim (int | None, optional): The output dimension of the layer. Default is None.
700
+ dim (int): Dimensionality of the input and output features.
701
+ input_resolution (Tuple[int, int]): Spatial resolution of the input feature map (height, width).
702
+ depth (int): Number of TinyViT blocks in this layer.
703
+ num_heads (int): Number of attention heads in each TinyViT block.
704
+ window_size (int): Size of the local window for attention computation.
705
+ mlp_ratio (float): Ratio of MLP hidden dimension to embedding dimension.
706
+ drop (float): Dropout rate.
707
+ drop_path (float | List[float]): Stochastic depth rate. Can be a float or a list of floats for each block.
708
+ downsample (nn.Module | None): Downsampling layer at the end of the layer. None to skip downsampling.
709
+ use_checkpoint (bool): Whether to use gradient checkpointing to save memory.
710
+ local_conv_size (int): Kernel size for the local convolution in each TinyViT block.
711
+ activation (nn.Module): Activation function used in the MLP.
712
+ out_dim (int | None): Output dimension after downsampling. None means it will be the same as `dim`.
473
713
 
474
714
  Raises:
475
- ValueError: If `drop_path` is a list of float but its length doesn't match `depth`.
715
+ ValueError: If `drop_path` is a list and its length doesn't match `depth`.
716
+
717
+ Examples:
718
+ >>> layer = BasicLayer(dim=96, input_resolution=(56, 56), depth=2, num_heads=3, window_size=7)
719
+ >>> x = torch.randn(1, 56 * 56, 96)
720
+ >>> output = layer(x)
721
+ >>> print(output.shape)
476
722
  """
477
723
  super().__init__()
478
724
  self.dim = dim
@@ -506,58 +752,49 @@ class BasicLayer(nn.Module):
506
752
  )
507
753
 
508
754
  def forward(self, x):
509
- """Performs forward propagation on the input tensor and returns a normalized tensor."""
755
+ """Processes input through TinyViT blocks and optional downsampling."""
510
756
  for blk in self.blocks:
511
757
  x = checkpoint.checkpoint(blk, x) if self.use_checkpoint else blk(x)
512
758
  return x if self.downsample is None else self.downsample(x)
513
759
 
514
760
  def extra_repr(self) -> str:
515
- """Returns a string representation of the extra_repr function with the layer's parameters."""
761
+ """Returns a string with the layer's parameters for printing."""
516
762
  return f"dim={self.dim}, input_resolution={self.input_resolution}, depth={self.depth}"
517
763
 
518
764
 
519
- class LayerNorm2d(nn.Module):
520
- """A PyTorch implementation of Layer Normalization in 2D."""
521
-
522
- def __init__(self, num_channels: int, eps: float = 1e-6) -> None:
523
- """Initialize LayerNorm2d with the number of channels and an optional epsilon."""
524
- super().__init__()
525
- self.weight = nn.Parameter(torch.ones(num_channels))
526
- self.bias = nn.Parameter(torch.zeros(num_channels))
527
- self.eps = eps
528
-
529
- def forward(self, x: torch.Tensor) -> torch.Tensor:
530
- """Perform a forward pass, normalizing the input tensor."""
531
- u = x.mean(1, keepdim=True)
532
- s = (x - u).pow(2).mean(1, keepdim=True)
533
- x = (x - u) / torch.sqrt(s + self.eps)
534
- return self.weight[:, None, None] * x + self.bias[:, None, None]
535
-
536
-
537
765
  class TinyViT(nn.Module):
538
766
  """
539
- The TinyViT architecture for vision tasks.
767
+ TinyViT: A compact vision transformer architecture for efficient image classification and feature extraction.
768
+
769
+ This class implements the TinyViT model, which combines elements of vision transformers and convolutional
770
+ neural networks for improved efficiency and performance on vision tasks.
540
771
 
541
772
  Attributes:
542
773
  img_size (int): Input image size.
543
- in_chans (int): Number of input channels.
544
774
  num_classes (int): Number of classification classes.
545
- embed_dims (List[int]): List of embedding dimensions for each layer.
546
- depths (List[int]): List of depths for each layer.
547
- num_heads (List[int]): List of number of attention heads for each layer.
548
- window_sizes (List[int]): List of window sizes for each layer.
775
+ depths (List[int]): Number of blocks in each stage.
776
+ num_layers (int): Total number of layers in the network.
549
777
  mlp_ratio (float): Ratio of MLP hidden dimension to embedding dimension.
550
- drop_rate (float): Dropout rate for drop layers.
551
- drop_path_rate (float): Drop path rate for stochastic depth.
552
- use_checkpoint (bool): Use checkpointing for efficient memory usage.
553
- mbconv_expand_ratio (float): Expansion ratio for MBConv layer.
554
- local_conv_size (int): Local convolution kernel size.
555
- layer_lr_decay (float): Layer-wise learning rate decay.
556
-
557
- Note:
558
- This implementation is generalized to accept a list of depths, attention heads,
559
- embedding dimensions and window sizes, which allows you to create a
560
- "stack" of TinyViT models of varying configurations.
778
+ patch_embed (PatchEmbed): Module for patch embedding.
779
+ patches_resolution (Tuple[int, int]): Resolution of embedded patches.
780
+ layers (nn.ModuleList): List of network layers.
781
+ norm_head (nn.LayerNorm): Layer normalization for the classifier head.
782
+ head (nn.Linear): Linear layer for final classification.
783
+ neck (nn.Sequential): Neck module for feature refinement.
784
+
785
+ Methods:
786
+ set_layer_lr_decay: Sets layer-wise learning rate decay.
787
+ _init_weights: Initializes weights for linear and normalization layers.
788
+ no_weight_decay_keywords: Returns keywords for parameters that should not use weight decay.
789
+ forward_features: Processes input through the feature extraction layers.
790
+ forward: Performs a forward pass through the entire network.
791
+
792
+ Examples:
793
+ >>> model = TinyViT(img_size=224, num_classes=1000)
794
+ >>> x = torch.randn(1, 3, 224, 224)
795
+ >>> features = model.forward_features(x)
796
+ >>> print(features.shape)
797
+ torch.Size([1, 256, 64, 64])
561
798
  """
562
799
 
563
800
  def __init__(
@@ -565,10 +802,10 @@ class TinyViT(nn.Module):
565
802
  img_size=224,
566
803
  in_chans=3,
567
804
  num_classes=1000,
568
- embed_dims=[96, 192, 384, 768],
569
- depths=[2, 2, 6, 2],
570
- num_heads=[3, 6, 12, 24],
571
- window_sizes=[7, 7, 14, 7],
805
+ embed_dims=(96, 192, 384, 768),
806
+ depths=(2, 2, 6, 2),
807
+ num_heads=(3, 6, 12, 24),
808
+ window_sizes=(7, 7, 14, 7),
572
809
  mlp_ratio=4.0,
573
810
  drop_rate=0.0,
574
811
  drop_path_rate=0.1,
@@ -580,21 +817,33 @@ class TinyViT(nn.Module):
580
817
  """
581
818
  Initializes the TinyViT model.
582
819
 
820
+ This constructor sets up the TinyViT architecture, including patch embedding, multiple layers of
821
+ attention and convolution blocks, and a classification head.
822
+
583
823
  Args:
584
- img_size (int, optional): The input image size. Defaults to 224.
585
- in_chans (int, optional): Number of input channels. Defaults to 3.
586
- num_classes (int, optional): Number of classification classes. Defaults to 1000.
587
- embed_dims (List[int], optional): List of embedding dimensions for each layer. Defaults to [96, 192, 384, 768].
588
- depths (List[int], optional): List of depths for each layer. Defaults to [2, 2, 6, 2].
589
- num_heads (List[int], optional): List of number of attention heads for each layer. Defaults to [3, 6, 12, 24].
590
- window_sizes (List[int], optional): List of window sizes for each layer. Defaults to [7, 7, 14, 7].
591
- mlp_ratio (float, optional): Ratio of MLP hidden dimension to embedding dimension. Defaults to 4.
592
- drop_rate (float, optional): Dropout rate. Defaults to 0.
593
- drop_path_rate (float, optional): Drop path rate for stochastic depth. Defaults to 0.1.
594
- use_checkpoint (bool, optional): Whether to use checkpointing for efficient memory usage. Defaults to False.
595
- mbconv_expand_ratio (float, optional): Expansion ratio for MBConv layer. Defaults to 4.0.
596
- local_conv_size (int, optional): Local convolution kernel size. Defaults to 3.
597
- layer_lr_decay (float, optional): Layer-wise learning rate decay. Defaults to 1.0.
824
+ img_size (int): Size of the input image. Default is 224.
825
+ in_chans (int): Number of input channels. Default is 3.
826
+ num_classes (int): Number of classes for classification. Default is 1000.
827
+ embed_dims (Tuple[int, int, int, int]): Embedding dimensions for each stage.
828
+ Default is (96, 192, 384, 768).
829
+ depths (Tuple[int, int, int, int]): Number of blocks in each stage. Default is (2, 2, 6, 2).
830
+ num_heads (Tuple[int, int, int, int]): Number of attention heads in each stage.
831
+ Default is (3, 6, 12, 24).
832
+ window_sizes (Tuple[int, int, int, int]): Window sizes for each stage. Default is (7, 7, 14, 7).
833
+ mlp_ratio (float): Ratio of MLP hidden dim to embedding dim. Default is 4.0.
834
+ drop_rate (float): Dropout rate. Default is 0.0.
835
+ drop_path_rate (float): Stochastic depth rate. Default is 0.1.
836
+ use_checkpoint (bool): Whether to use checkpointing to save memory. Default is False.
837
+ mbconv_expand_ratio (float): Expansion ratio for MBConv layer. Default is 4.0.
838
+ local_conv_size (int): Kernel size for local convolutions. Default is 3.
839
+ layer_lr_decay (float): Layer-wise learning rate decay factor. Default is 1.0.
840
+
841
+ Examples:
842
+ >>> model = TinyViT(img_size=224, num_classes=1000)
843
+ >>> x = torch.randn(1, 3, 224, 224)
844
+ >>> output = model(x)
845
+ >>> print(output.shape)
846
+ torch.Size([1, 1000])
598
847
  """
599
848
  super().__init__()
600
849
  self.img_size = img_size
@@ -672,7 +921,7 @@ class TinyViT(nn.Module):
672
921
  )
673
922
 
674
923
  def set_layer_lr_decay(self, layer_lr_decay):
675
- """Sets the learning rate decay for each layer in the TinyViT model."""
924
+ """Sets layer-wise learning rate decay for the TinyViT model based on depth."""
676
925
  decay_rate = layer_lr_decay
677
926
 
678
927
  # Layers -> blocks (depth)
@@ -706,8 +955,9 @@ class TinyViT(nn.Module):
706
955
 
707
956
  self.apply(_check_lr_scale)
708
957
 
709
- def _init_weights(self, m):
710
- """Initializes weights for linear layers and layer normalization in the given module."""
958
+ @staticmethod
959
+ def _init_weights(m):
960
+ """Initializes weights for linear and normalization layers in the TinyViT model."""
711
961
  if isinstance(m, nn.Linear):
712
962
  # NOTE: This initialization is needed only for training.
713
963
  # trunc_normal_(m.weight, std=.02)
@@ -719,11 +969,11 @@ class TinyViT(nn.Module):
719
969
 
720
970
  @torch.jit.ignore
721
971
  def no_weight_decay_keywords(self):
722
- """Returns a dictionary of parameter names where weight decay should not be applied."""
972
+ """Returns a set of keywords for parameters that should not use weight decay."""
723
973
  return {"attention_biases"}
724
974
 
725
975
  def forward_features(self, x):
726
- """Runs the input through the model layers and returns the transformed output."""
976
+ """Processes input through feature extraction layers, returning spatial features."""
727
977
  x = self.patch_embed(x) # x input is (N, C, H, W)
728
978
 
729
979
  x = self.layers[0](x)
@@ -732,11 +982,32 @@ class TinyViT(nn.Module):
732
982
  for i in range(start_i, len(self.layers)):
733
983
  layer = self.layers[i]
734
984
  x = layer(x)
735
- B, _, C = x.shape
736
- x = x.view(B, 64, 64, C)
985
+ batch, _, channel = x.shape
986
+ x = x.view(batch, self.patches_resolution[0] // 4, self.patches_resolution[1] // 4, channel)
737
987
  x = x.permute(0, 3, 1, 2)
738
988
  return self.neck(x)
739
989
 
740
990
  def forward(self, x):
741
- """Executes a forward pass on the input tensor through the constructed model layers."""
991
+ """Performs the forward pass through the TinyViT model, extracting features from the input image."""
742
992
  return self.forward_features(x)
993
+
994
+ def set_imgsz(self, imgsz=[1024, 1024]):
995
+ """
996
+ Set image size to make model compatible with different image sizes.
997
+
998
+ Args:
999
+ imgsz (Tuple[int, int]): The size of the input image.
1000
+ """
1001
+ imgsz = [s // 4 for s in imgsz]
1002
+ self.patches_resolution = imgsz
1003
+ for i, layer in enumerate(self.layers):
1004
+ input_resolution = (
1005
+ imgsz[0] // (2 ** (i - 1 if i == 3 else i)),
1006
+ imgsz[1] // (2 ** (i - 1 if i == 3 else i)),
1007
+ )
1008
+ layer.input_resolution = input_resolution
1009
+ if layer.downsample is not None:
1010
+ layer.downsample.input_resolution = input_resolution
1011
+ if isinstance(layer, BasicLayer):
1012
+ for b in layer.blocks:
1013
+ b.input_resolution = input_resolution