swiftformer.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  1. """SwiftFormer
  2. SwiftFormer: Efficient Additive Attention for Transformer-based Real-time Mobile Vision Applications
  3. Code: https://github.com/Amshaker/SwiftFormer
  4. Paper: https://arxiv.org/pdf/2303.15446
  5. @InProceedings{Shaker_2023_ICCV,
  6. author = {Shaker, Abdelrahman and Maaz, Muhammad and Rasheed, Hanoona and Khan, Salman and Yang, Ming-Hsuan and Khan, Fahad Shahbaz},
  7. title = {SwiftFormer: Efficient Additive Attention for Transformer-based Real-time Mobile Vision Applications},
  8. booktitle = {Proceedings of the IEEE/CVF International Conference on Computer Vision (ICCV)},
  9. year = {2023},
  10. }
  11. """
  12. import re
  13. from typing import Any, Dict, List, Optional, Set, Tuple, Type, Union
  14. import torch
  15. import torch.nn as nn
  16. import torch.nn.functional as F
  17. from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
  18. from timm.layers import DropPath, Linear, LayerType, to_2tuple, trunc_normal_
  19. from ._builder import build_model_with_cfg
  20. from ._features import feature_take_indices
  21. from ._manipulate import checkpoint_seq
  22. from ._registry import generate_default_cfgs, register_model
  23. __all__ = ['SwiftFormer']
  24. class LayerScale2d(nn.Module):
  25. def __init__(self, dim: int, init_values: float = 1e-5, inplace: bool = False, device=None, dtype=None):
  26. dd = {'device': device, 'dtype': dtype}
  27. super().__init__()
  28. self.inplace = inplace
  29. self.gamma = nn.Parameter(
  30. init_values * torch.ones(dim, 1, 1, **dd), requires_grad=True)
  31. def forward(self, x: torch.Tensor) -> torch.Tensor:
  32. return x.mul_(self.gamma) if self.inplace else x * self.gamma
  33. class Embedding(nn.Module):
  34. """
  35. Patch Embedding that is implemented by a layer of conv.
  36. Input: tensor in shape [B, C, H, W]
  37. Output: tensor in shape [B, C, H/stride, W/stride]
  38. """
  39. def __init__(
  40. self,
  41. in_chans: int = 3,
  42. embed_dim: int = 768,
  43. patch_size: int = 16,
  44. stride: int = 16,
  45. padding: int = 0,
  46. norm_layer: Type[nn.Module] = nn.BatchNorm2d,
  47. device=None,
  48. dtype=None,
  49. ):
  50. dd = {'device': device, 'dtype': dtype}
  51. super().__init__()
  52. patch_size = to_2tuple(patch_size)
  53. stride = to_2tuple(stride)
  54. padding = to_2tuple(padding)
  55. self.proj = nn.Conv2d(in_chans, embed_dim, patch_size, stride, padding, **dd)
  56. self.norm = norm_layer(embed_dim, **dd) if norm_layer else nn.Identity()
  57. def forward(self, x: torch.Tensor) -> torch.Tensor:
  58. x = self.proj(x)
  59. x = self.norm(x)
  60. return x
  61. class ConvEncoder(nn.Module):
  62. """
  63. Implementation of ConvEncoder with 3*3 and 1*1 convolutions.
  64. Input: tensor with shape [B, C, H, W]
  65. Output: tensor with shape [B, C, H, W]
  66. """
  67. def __init__(
  68. self,
  69. dim: int,
  70. hidden_dim: int = 64,
  71. kernel_size: int = 3,
  72. drop_path: float = 0.,
  73. act_layer: Type[nn.Module] = nn.GELU,
  74. norm_layer: Type[nn.Module] = nn.BatchNorm2d,
  75. use_layer_scale: bool = True,
  76. device=None,
  77. dtype=None,
  78. ):
  79. dd = {'device': device, 'dtype': dtype}
  80. super().__init__()
  81. self.dwconv = nn.Conv2d(dim, dim, kernel_size, padding=kernel_size // 2, groups=dim, **dd)
  82. self.norm = norm_layer(dim, **dd)
  83. self.pwconv1 = nn.Conv2d(dim, hidden_dim, 1, **dd)
  84. self.act = act_layer()
  85. self.pwconv2 = nn.Conv2d(hidden_dim, dim, 1, **dd)
  86. self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
  87. self.layer_scale = LayerScale2d(dim, 1, **dd) if use_layer_scale else nn.Identity()
  88. def forward(self, x: torch.Tensor) -> torch.Tensor:
  89. input = x
  90. x = self.dwconv(x)
  91. x = self.norm(x)
  92. x = self.pwconv1(x)
  93. x = self.act(x)
  94. x = self.pwconv2(x)
  95. x = self.layer_scale(x)
  96. x = input + self.drop_path(x)
  97. return x
  98. class Mlp(nn.Module):
  99. """
  100. Implementation of MLP layer with 1*1 convolutions.
  101. Input: tensor with shape [B, C, H, W]
  102. Output: tensor with shape [B, C, H, W]
  103. """
  104. def __init__(
  105. self,
  106. in_features: int,
  107. hidden_features: Optional[int] = None,
  108. out_features: Optional[int] = None,
  109. act_layer: Type[nn.Module] = nn.GELU,
  110. norm_layer: Type[nn.Module] = nn.BatchNorm2d,
  111. drop: float = 0.,
  112. device=None,
  113. dtype=None,
  114. ):
  115. dd = {'device': device, 'dtype': dtype}
  116. super().__init__()
  117. out_features = out_features or in_features
  118. hidden_features = hidden_features or in_features
  119. self.norm1 = norm_layer(in_features, **dd)
  120. self.fc1 = nn.Conv2d(in_features, hidden_features, 1, **dd)
  121. self.act = act_layer()
  122. self.fc2 = nn.Conv2d(hidden_features, out_features, 1, **dd)
  123. self.drop = nn.Dropout(drop)
  124. def forward(self, x: torch.Tensor) -> torch.Tensor:
  125. x = self.norm1(x)
  126. x = self.fc1(x)
  127. x = self.act(x)
  128. x = self.drop(x)
  129. x = self.fc2(x)
  130. x = self.drop(x)
  131. return x
  132. class EfficientAdditiveAttention(nn.Module):
  133. """
  134. Efficient Additive Attention module for SwiftFormer.
  135. Input: tensor in shape [B, C, H, W]
  136. Output: tensor in shape [B, C, H, W]
  137. """
  138. def __init__(
  139. self,
  140. in_dims: int = 512,
  141. token_dim: int = 256,
  142. num_heads: int = 1,
  143. device=None,
  144. dtype=None,
  145. ):
  146. dd = {'device': device, 'dtype': dtype}
  147. super().__init__()
  148. self.scale_factor = token_dim ** -0.5
  149. self.to_query = nn.Linear(in_dims, token_dim * num_heads, **dd)
  150. self.to_key = nn.Linear(in_dims, token_dim * num_heads, **dd)
  151. self.w_g = nn.Parameter(torch.randn(token_dim * num_heads, 1, **dd))
  152. self.proj = nn.Linear(token_dim * num_heads, token_dim * num_heads, **dd)
  153. self.final = nn.Linear(token_dim * num_heads, token_dim, **dd)
  154. def forward(self, x: torch.Tensor) -> torch.Tensor:
  155. B, _, H, W = x.shape
  156. x = x.flatten(2).permute(0, 2, 1)
  157. query = F.normalize(self.to_query(x), dim=-1)
  158. key = F.normalize(self.to_key(x), dim=-1)
  159. attn = F.normalize(query @ self.w_g * self.scale_factor, dim=1)
  160. attn = torch.sum(attn * query, dim=1, keepdim=True)
  161. out = self.proj(attn * key) + query
  162. out = self.final(out).permute(0, 2, 1).reshape(B, -1, H, W)
  163. return out
  164. class LocalRepresentation(nn.Module):
  165. """
  166. Local Representation module for SwiftFormer that is implemented by 3*3 depth-wise and point-wise convolutions.
  167. Input: tensor in shape [B, C, H, W]
  168. Output: tensor in shape [B, C, H, W]
  169. """
  170. def __init__(
  171. self,
  172. dim: int,
  173. kernel_size: int = 3,
  174. drop_path: float = 0.,
  175. use_layer_scale: bool = True,
  176. act_layer: Type[nn.Module] = nn.GELU,
  177. norm_layer: Type[nn.Module] = nn.BatchNorm2d,
  178. device=None,
  179. dtype=None,
  180. ):
  181. dd = {'device': device, 'dtype': dtype}
  182. super().__init__()
  183. self.dwconv = nn.Conv2d(dim, dim, kernel_size, padding=kernel_size // 2, groups=dim, **dd)
  184. self.norm = norm_layer(dim, **dd)
  185. self.pwconv1 = nn.Conv2d(dim, dim, kernel_size=1, **dd)
  186. self.act = act_layer()
  187. self.pwconv2 = nn.Conv2d(dim, dim, kernel_size=1, **dd)
  188. self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
  189. self.layer_scale = LayerScale2d(dim, 1, **dd) if use_layer_scale else nn.Identity()
  190. def forward(self, x: torch.Tensor) -> torch.Tensor:
  191. skip = x
  192. x = self.dwconv(x)
  193. x = self.norm(x)
  194. x = self.pwconv1(x)
  195. x = self.act(x)
  196. x = self.pwconv2(x)
  197. x = self.layer_scale(x)
  198. x = skip + self.drop_path(x)
  199. return x
  200. class Block(nn.Module):
  201. """
  202. SwiftFormer Encoder Block for SwiftFormer. It consists of :
  203. (1) Local representation module, (2) EfficientAdditiveAttention, and (3) MLP block.
  204. Input: tensor in shape [B, C, H, W]
  205. Output: tensor in shape [B, C, H, W]
  206. """
  207. def __init__(
  208. self,
  209. dim: int,
  210. mlp_ratio: float = 4.,
  211. drop_rate: float = 0.,
  212. drop_path: float = 0.,
  213. act_layer: Type[nn.Module] = nn.GELU,
  214. norm_layer: Type[nn.Module] = nn.BatchNorm2d,
  215. use_layer_scale: bool = True,
  216. layer_scale_init_value: float = 1e-5,
  217. device=None,
  218. dtype=None,
  219. ):
  220. dd = {'device': device, 'dtype': dtype}
  221. super().__init__()
  222. self.local_representation = LocalRepresentation(
  223. dim=dim,
  224. use_layer_scale=use_layer_scale,
  225. act_layer=act_layer,
  226. norm_layer=norm_layer,
  227. **dd,
  228. )
  229. self.attn = EfficientAdditiveAttention(in_dims=dim, token_dim=dim, **dd)
  230. self.linear = Mlp(
  231. in_features=dim,
  232. hidden_features=int(dim * mlp_ratio),
  233. act_layer=act_layer,
  234. norm_layer=norm_layer,
  235. drop=drop_rate,
  236. **dd,
  237. )
  238. self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
  239. self.layer_scale_1 = LayerScale2d(dim, layer_scale_init_value, **dd) \
  240. if use_layer_scale else nn.Identity()
  241. self.layer_scale_2 = LayerScale2d(dim, layer_scale_init_value, **dd) \
  242. if use_layer_scale else nn.Identity()
  243. def forward(self, x: torch.Tensor) -> torch.Tensor:
  244. x = self.local_representation(x)
  245. x = x + self.drop_path(self.layer_scale_1(self.attn(x)))
  246. x = x + self.drop_path(self.layer_scale_2(self.linear(x)))
  247. return x
  248. class Stage(nn.Module):
  249. """
  250. Implementation of each SwiftFormer stages. Here, SwiftFormerEncoder used as the last block in all stages, while ConvEncoder used in the rest of the blocks.
  251. Input: tensor in shape [B, C, H, W]
  252. Output: tensor in shape [B, C, H, W]
  253. """
  254. def __init__(
  255. self,
  256. dim: int,
  257. index: int,
  258. layers: List[int],
  259. mlp_ratio: float = 4.,
  260. act_layer: Type[nn.Module] = nn.GELU,
  261. norm_layer: Type[nn.Module] = nn.BatchNorm2d,
  262. drop_rate: float = 0.,
  263. drop_path_rate: float = 0.,
  264. use_layer_scale: bool = True,
  265. layer_scale_init_value: float = 1e-5,
  266. downsample: Optional[Type[nn.Module]] = None,
  267. device=None,
  268. dtype=None,
  269. ):
  270. dd = {'device': device, 'dtype': dtype}
  271. super().__init__()
  272. self.grad_checkpointing = False
  273. self.downsample = downsample if downsample is not None else nn.Identity()
  274. blocks = []
  275. for block_idx in range(layers[index]):
  276. block_dpr = drop_path_rate * (block_idx + sum(layers[:index])) / (sum(layers) - 1)
  277. if layers[index] - block_idx <= 1:
  278. blocks.append(Block(
  279. dim,
  280. mlp_ratio=mlp_ratio,
  281. drop_rate=drop_rate,
  282. drop_path=block_dpr,
  283. act_layer=act_layer,
  284. norm_layer=norm_layer,
  285. use_layer_scale=use_layer_scale,
  286. layer_scale_init_value=layer_scale_init_value,
  287. **dd,
  288. ))
  289. else:
  290. blocks.append(ConvEncoder(
  291. dim=dim,
  292. hidden_dim=int(mlp_ratio * dim),
  293. kernel_size=3,
  294. drop_path=block_dpr,
  295. act_layer=act_layer,
  296. norm_layer=norm_layer,
  297. use_layer_scale=use_layer_scale,
  298. **dd,
  299. ))
  300. self.blocks = nn.Sequential(*blocks)
  301. def forward(self, x: torch.Tensor) -> torch.Tensor:
  302. x = self.downsample(x)
  303. if self.grad_checkpointing and not torch.jit.is_scripting():
  304. x = checkpoint_seq(self.blocks, x)
  305. else:
  306. x = self.blocks(x)
  307. return x
  308. class SwiftFormer(nn.Module):
  309. def __init__(
  310. self,
  311. layers: List[int] = [3, 3, 6, 4],
  312. embed_dims: List[int] = [48, 56, 112, 220],
  313. mlp_ratios: int = 4,
  314. downsamples: List[bool] = [False, True, True, True],
  315. act_layer: Type[nn.Module] = nn.GELU,
  316. down_patch_size: int = 3,
  317. down_stride: int = 2,
  318. down_pad: int = 1,
  319. num_classes: int = 1000,
  320. drop_rate: float = 0.,
  321. drop_path_rate: float = 0.,
  322. use_layer_scale: bool = True,
  323. layer_scale_init_value: float = 1e-5,
  324. global_pool: str = 'avg',
  325. output_stride: int = 32,
  326. in_chans: int = 3,
  327. device=None,
  328. dtype=None,
  329. **kwargs,
  330. ):
  331. super().__init__()
  332. dd = {'device': device, 'dtype': dtype}
  333. assert output_stride == 32
  334. self.num_classes = num_classes
  335. self.global_pool = global_pool
  336. self.feature_info = []
  337. self.stem = nn.Sequential(
  338. nn.Conv2d(in_chans, embed_dims[0] // 2, 3, 2, 1, **dd),
  339. nn.BatchNorm2d(embed_dims[0] // 2, **dd),
  340. nn.ReLU(),
  341. nn.Conv2d(embed_dims[0] // 2, embed_dims[0], 3, 2, 1, **dd),
  342. nn.BatchNorm2d(embed_dims[0], **dd),
  343. nn.ReLU(),
  344. )
  345. prev_dim = embed_dims[0]
  346. stages = []
  347. for i in range(len(layers)):
  348. downsample = Embedding(
  349. in_chans=prev_dim,
  350. embed_dim=embed_dims[i],
  351. patch_size=down_patch_size,
  352. stride=down_stride,
  353. padding=down_pad,
  354. **dd,
  355. ) if downsamples[i] else nn.Identity()
  356. stage = Stage(
  357. dim=embed_dims[i],
  358. index=i,
  359. layers=layers,
  360. mlp_ratio=mlp_ratios,
  361. act_layer=act_layer,
  362. drop_rate=drop_rate,
  363. drop_path_rate=drop_path_rate,
  364. use_layer_scale=use_layer_scale,
  365. layer_scale_init_value=layer_scale_init_value,
  366. downsample=downsample,
  367. **dd,
  368. )
  369. prev_dim = embed_dims[i]
  370. stages.append(stage)
  371. self.feature_info += [dict(num_chs=embed_dims[i], reduction=2**(i+2), module=f'stages.{i}')]
  372. self.stages = nn.Sequential(*stages)
  373. # Classifier head
  374. self.num_features = self.head_hidden_size = out_chs = embed_dims[-1]
  375. self.norm = nn.BatchNorm2d(out_chs, **dd)
  376. self.head_drop = nn.Dropout(drop_rate)
  377. self.head = Linear(out_chs, num_classes, **dd) if num_classes > 0 else nn.Identity()
  378. # assuming model is always distilled (valid for current checkpoints, will split def if that changes)
  379. self.head_dist = Linear(out_chs, num_classes, **dd) if num_classes > 0 else nn.Identity()
  380. self.distilled_training = False # must set this True to train w/ distillation token
  381. self._initialize_weights()
  382. def _initialize_weights(self):
  383. for name, m in self.named_modules():
  384. if isinstance(m, nn.Linear):
  385. trunc_normal_(m.weight, std=.02)
  386. if m.bias is not None:
  387. nn.init.constant_(m.bias, 0)
  388. elif isinstance(m, nn.Conv2d):
  389. trunc_normal_(m.weight, std=.02)
  390. if m.bias is not None:
  391. nn.init.constant_(m.bias, 0)
  392. @torch.jit.ignore
  393. def no_weight_decay(self) -> Set:
  394. return set()
  395. @torch.jit.ignore
  396. def group_matcher(self, coarse: bool = False) -> Dict[str, Any]:
  397. matcher = dict(
  398. stem=r'^stem', # stem and embed
  399. blocks=r'^stages\.(\d+)' if coarse else [
  400. (r'^stages\.(\d+).downsample', (0,)),
  401. (r'^stages\.(\d+)\.blocks\.(\d+)', None),
  402. (r'^norm', (99999,)),
  403. ]
  404. )
  405. return matcher
  406. @torch.jit.ignore
  407. def set_grad_checkpointing(self, enable: bool = True):
  408. for s in self.stages:
  409. s.grad_checkpointing = enable
  410. @torch.jit.ignore
  411. def get_classifier(self) -> Tuple[nn.Module, nn.Module]:
  412. return self.head, self.head_dist
  413. def reset_classifier(self, num_classes: int, global_pool: Optional[str] = None):
  414. self.num_classes = num_classes
  415. if global_pool is not None:
  416. self.global_pool = global_pool
  417. device, dtype = self.head.weight.device, self.head.weight.dtype if hasattr(self.head, 'weight') else (None, None)
  418. self.head = Linear(self.num_features, num_classes, device=device, dtype=dtype) if num_classes > 0 else nn.Identity()
  419. self.head_dist = Linear(self.num_features, num_classes, device=device, dtype=dtype) if num_classes > 0 else nn.Identity()
  420. @torch.jit.ignore
  421. def set_distilled_training(self, enable: bool = True):
  422. self.distilled_training = enable
  423. def forward_intermediates(
  424. self,
  425. x: torch.Tensor,
  426. indices: Optional[Union[int, List[int]]] = None,
  427. norm: bool = False,
  428. stop_early: bool = False,
  429. output_fmt: str = 'NCHW',
  430. intermediates_only: bool = False,
  431. ) -> Union[List[torch.Tensor], Tuple[torch.Tensor, List[torch.Tensor]]]:
  432. """ Forward features that returns intermediates.
  433. Args:
  434. x: Input image tensor
  435. indices: Take last n blocks if int, all if None, select matching indices if sequence
  436. norm: Apply norm layer to compatible intermediates
  437. stop_early: Stop iterating over blocks when last desired intermediate hit
  438. output_fmt: Shape of intermediate feature outputs
  439. intermediates_only: Only return intermediate features
  440. Returns:
  441. """
  442. assert output_fmt in ('NCHW',), 'Output shape must be NCHW.'
  443. intermediates = []
  444. take_indices, max_index = feature_take_indices(len(self.stages), indices)
  445. last_idx = len(self.stages) - 1
  446. # forward pass
  447. x = self.stem(x)
  448. if torch.jit.is_scripting() or not stop_early: # can't slice blocks in torchscript
  449. stages = self.stages
  450. else:
  451. stages = self.stages[:max_index + 1]
  452. for feat_idx, stage in enumerate(stages):
  453. x = stage(x)
  454. if feat_idx in take_indices:
  455. if norm and feat_idx == last_idx:
  456. x_inter = self.norm(x) # applying final norm last intermediate
  457. else:
  458. x_inter = x
  459. intermediates.append(x_inter)
  460. if intermediates_only:
  461. return intermediates
  462. if feat_idx == last_idx:
  463. x = self.norm(x)
  464. return x, intermediates
  465. def prune_intermediate_layers(
  466. self,
  467. indices: Union[int, List[int]] = 1,
  468. prune_norm: bool = False,
  469. prune_head: bool = True,
  470. ):
  471. """ Prune layers not required for specified intermediates.
  472. """
  473. take_indices, max_index = feature_take_indices(len(self.stages), indices)
  474. self.stages = self.stages[:max_index + 1] # truncate blocks w/ stem as idx 0
  475. if prune_norm:
  476. self.norm = nn.Identity()
  477. if prune_head:
  478. self.reset_classifier(0, '')
  479. return take_indices
  480. def forward_features(self, x: torch.Tensor) -> torch.Tensor:
  481. x = self.stem(x)
  482. x = self.stages(x)
  483. x = self.norm(x)
  484. return x
  485. def forward_head(self, x: torch.Tensor, pre_logits: bool = False):
  486. if self.global_pool == 'avg':
  487. x = x.mean(dim=(2, 3))
  488. x = self.head_drop(x)
  489. if pre_logits:
  490. return x
  491. x, x_dist = self.head(x), self.head_dist(x)
  492. if self.distilled_training and self.training and not torch.jit.is_scripting():
  493. # only return separate classification predictions when training in distilled mode
  494. return x, x_dist
  495. else:
  496. # during standard train/finetune, inference average the classifier predictions
  497. return (x + x_dist) / 2
  498. def forward(self, x: torch.Tensor):
  499. x = self.forward_features(x)
  500. x = self.forward_head(x)
  501. return x
  502. def checkpoint_filter_fn(state_dict: Dict[str, torch.Tensor], model: nn.Module) -> Dict[str, torch.Tensor]:
  503. state_dict = state_dict.get('model', state_dict)
  504. if 'stem.0.weight' in state_dict:
  505. return state_dict
  506. out_dict = {}
  507. for k, v in state_dict.items():
  508. k = k.replace('patch_embed.', 'stem.')
  509. k = k.replace('dist_head.', 'head_dist.')
  510. k = k.replace('attn.Proj.', 'attn.proj.')
  511. k = k.replace('.layer_scale_1', '.layer_scale_1.gamma')
  512. k = k.replace('.layer_scale_2', '.layer_scale_2.gamma')
  513. k = re.sub(r'\.layer_scale(?=$|\.)', '.layer_scale.gamma', k)
  514. m = re.match(r'^network\.(\d+)\.(.*)', k)
  515. if m:
  516. n_idx, rest = int(m.group(1)), m.group(2)
  517. stage_idx = n_idx // 2
  518. if n_idx % 2 == 0:
  519. k = f'stages.{stage_idx}.blocks.{rest}'
  520. else:
  521. k = f'stages.{stage_idx+1}.downsample.{rest}'
  522. out_dict[k] = v
  523. return out_dict
  524. def _cfg(url: str = '', **kwargs: Any) -> Dict[str, Any]:
  525. return {
  526. 'url': url,
  527. 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': None, 'fixed_input_size': True,
  528. 'crop_pct': .95, 'interpolation': 'bicubic',
  529. 'mean': IMAGENET_DEFAULT_MEAN, 'std': IMAGENET_DEFAULT_STD,
  530. 'first_conv': 'stem.0', 'classifier': ('head', 'head_dist'),
  531. 'license': 'apache-2.0',
  532. 'paper_ids': 'arXiv:2303.15446',
  533. 'paper_name': 'SwiftFormer: Efficient Additive Attention for Transformer-based Real-time Mobile Vision Applications',
  534. 'origin_url': 'https://github.com/Amshaker/SwiftFormer',
  535. **kwargs
  536. }
  537. default_cfgs = generate_default_cfgs({
  538. 'swiftformer_xs.dist_in1k': _cfg(
  539. hf_hub_id='timm/',
  540. ),
  541. 'swiftformer_s.dist_in1k': _cfg(
  542. hf_hub_id='timm/'
  543. ),
  544. 'swiftformer_l1.dist_in1k': _cfg(
  545. hf_hub_id='timm/'
  546. ),
  547. 'swiftformer_l3.dist_in1k': _cfg(
  548. hf_hub_id='timm/'
  549. ),
  550. })
  551. def _create_swiftformer(variant: str, pretrained: bool = False, **kwargs: Any) -> SwiftFormer:
  552. model = build_model_with_cfg(
  553. SwiftFormer, variant, pretrained,
  554. pretrained_filter_fn=checkpoint_filter_fn,
  555. feature_cfg=dict(out_indices=(0, 1, 2, 3), flatten_sequential=True),
  556. **kwargs,
  557. )
  558. return model
  559. @register_model
  560. def swiftformer_xs(pretrained: bool = False, **kwargs: Any) -> SwiftFormer:
  561. model_args = dict(layers=[3, 3, 6, 4], embed_dims=[48, 56, 112, 220])
  562. return _create_swiftformer('swiftformer_xs', pretrained=pretrained, **dict(model_args, **kwargs))
  563. @register_model
  564. def swiftformer_s(pretrained: bool = False, **kwargs: Any) -> SwiftFormer:
  565. model_args = dict(layers=[3, 3, 9, 6], embed_dims=[48, 64, 168, 224])
  566. return _create_swiftformer('swiftformer_s', pretrained=pretrained, **dict(model_args, **kwargs))
  567. @register_model
  568. def swiftformer_l1(pretrained: bool = False, **kwargs: Any) -> SwiftFormer:
  569. model_args = dict(layers=[4, 3, 10, 5], embed_dims=[48, 96, 192, 384])
  570. return _create_swiftformer('swiftformer_l1', pretrained=pretrained, **dict(model_args, **kwargs))
  571. @register_model
  572. def swiftformer_l3(pretrained: bool = False, **kwargs: Any) -> SwiftFormer:
  573. model_args = dict(layers=[4, 4, 12, 6], embed_dims=[64, 128, 320, 512])
  574. return _create_swiftformer('swiftformer_l3', pretrained=pretrained, **dict(model_args, **kwargs))