twins.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  1. """ Twins
  2. A PyTorch impl of : `Twins: Revisiting the Design of Spatial Attention in Vision Transformers`
  3. - https://arxiv.org/pdf/2104.13840.pdf
  4. Code/weights from https://github.com/Meituan-AutoML/Twins, original copyright/license info below
  5. """
  6. # --------------------------------------------------------
  7. # Twins
  8. # Copyright (c) 2021 Meituan
  9. # Licensed under The Apache 2.0 License [see LICENSE for details]
  10. # Written by Xinjie Li, Xiangxiang Chu
  11. # --------------------------------------------------------
  12. import math
  13. from functools import partial
  14. from typing import List, Optional, Tuple, Union, Type, Any
  15. import torch
  16. import torch.nn as nn
  17. import torch.nn.functional as F
  18. from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
  19. from timm.layers import Mlp, DropPath, to_2tuple, trunc_normal_, use_fused_attn, calculate_drop_path_rates
  20. from ._builder import build_model_with_cfg
  21. from ._features import feature_take_indices
  22. from ._features_fx import register_notrace_module
  23. from ._registry import register_model, generate_default_cfgs
  24. from .vision_transformer import Attention
  25. __all__ = ['Twins'] # model_registry will add each entrypoint fn to this
  26. Size_ = Tuple[int, int]
  27. @register_notrace_module # reason: FX can't symbolically trace control flow in forward method
  28. class LocallyGroupedAttn(nn.Module):
  29. """ LSA: self attention within a group
  30. """
  31. fused_attn: torch.jit.Final[bool]
  32. def __init__(
  33. self,
  34. dim: int,
  35. num_heads: int = 8,
  36. attn_drop: float = 0.,
  37. proj_drop: float = 0.,
  38. ws: int = 1,
  39. device=None,
  40. dtype=None,
  41. ):
  42. dd = {'device': device, 'dtype': dtype}
  43. assert ws != 1
  44. super().__init__()
  45. assert dim % num_heads == 0, f"dim {dim} should be divided by num_heads {num_heads}."
  46. self.dim = dim
  47. self.num_heads = num_heads
  48. head_dim = dim // num_heads
  49. self.scale = head_dim ** -0.5
  50. self.fused_attn = use_fused_attn()
  51. self.qkv = nn.Linear(dim, dim * 3, bias=True, **dd)
  52. self.attn_drop = nn.Dropout(attn_drop)
  53. self.proj = nn.Linear(dim, dim, **dd)
  54. self.proj_drop = nn.Dropout(proj_drop)
  55. self.ws = ws
  56. def forward(self, x, size: Size_):
  57. # There are two implementations for this function, zero padding or mask. We don't observe obvious difference for
  58. # both. You can choose any one, we recommend forward_padding because it's neat. However,
  59. # the masking implementation is more reasonable and accurate.
  60. B, N, C = x.shape
  61. H, W = size
  62. x = x.view(B, H, W, C)
  63. pad_l = pad_t = 0
  64. pad_r = (self.ws - W % self.ws) % self.ws
  65. pad_b = (self.ws - H % self.ws) % self.ws
  66. x = F.pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b))
  67. _, Hp, Wp, _ = x.shape
  68. _h, _w = Hp // self.ws, Wp // self.ws
  69. x = x.reshape(B, _h, self.ws, _w, self.ws, C).transpose(2, 3)
  70. qkv = self.qkv(x).reshape(
  71. B, _h * _w, self.ws * self.ws, 3, self.num_heads, C // self.num_heads).permute(3, 0, 1, 4, 2, 5)
  72. q, k, v = qkv.unbind(0)
  73. if self.fused_attn:
  74. x = F.scaled_dot_product_attention(
  75. q, k, v,
  76. dropout_p=self.attn_drop.p if self.training else 0.,
  77. )
  78. else:
  79. q = q * self.scale
  80. attn = q @ k.transpose(-2, -1)
  81. attn = attn.softmax(dim=-1)
  82. attn = self.attn_drop(attn)
  83. x = attn @ v
  84. x = x.transpose(2, 3).reshape(B, _h, _w, self.ws, self.ws, C)
  85. x = x.transpose(2, 3).reshape(B, _h * self.ws, _w * self.ws, C)
  86. if pad_r > 0 or pad_b > 0:
  87. x = x[:, :H, :W, :].contiguous()
  88. x = x.reshape(B, N, C)
  89. x = self.proj(x)
  90. x = self.proj_drop(x)
  91. return x
  92. # def forward_mask(self, x, size: Size_):
  93. # B, N, C = x.shape
  94. # H, W = size
  95. # x = x.view(B, H, W, C)
  96. # pad_l = pad_t = 0
  97. # pad_r = (self.ws - W % self.ws) % self.ws
  98. # pad_b = (self.ws - H % self.ws) % self.ws
  99. # x = F.pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b))
  100. # _, Hp, Wp, _ = x.shape
  101. # _h, _w = Hp // self.ws, Wp // self.ws
  102. # mask = torch.zeros((1, Hp, Wp), device=x.device)
  103. # mask[:, -pad_b:, :].fill_(1)
  104. # mask[:, :, -pad_r:].fill_(1)
  105. #
  106. # x = x.reshape(B, _h, self.ws, _w, self.ws, C).transpose(2, 3) # B, _h, _w, ws, ws, C
  107. # mask = mask.reshape(1, _h, self.ws, _w, self.ws).transpose(2, 3).reshape(1, _h * _w, self.ws * self.ws)
  108. # attn_mask = mask.unsqueeze(2) - mask.unsqueeze(3) # 1, _h*_w, ws*ws, ws*ws
  109. # attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-1000.0)).masked_fill(attn_mask == 0, float(0.0))
  110. # qkv = self.qkv(x).reshape(
  111. # B, _h * _w, self.ws * self.ws, 3, self.num_heads, C // self.num_heads).permute(3, 0, 1, 4, 2, 5)
  112. # # n_h, B, _w*_h, nhead, ws*ws, dim
  113. # q, k, v = qkv[0], qkv[1], qkv[2] # B, _h*_w, n_head, ws*ws, dim_head
  114. # attn = (q @ k.transpose(-2, -1)) * self.scale # B, _h*_w, n_head, ws*ws, ws*ws
  115. # attn = attn + attn_mask.unsqueeze(2)
  116. # attn = attn.softmax(dim=-1)
  117. # attn = self.attn_drop(attn) # attn @v -> B, _h*_w, n_head, ws*ws, dim_head
  118. # attn = (attn @ v).transpose(2, 3).reshape(B, _h, _w, self.ws, self.ws, C)
  119. # x = attn.transpose(2, 3).reshape(B, _h * self.ws, _w * self.ws, C)
  120. # if pad_r > 0 or pad_b > 0:
  121. # x = x[:, :H, :W, :].contiguous()
  122. # x = x.reshape(B, N, C)
  123. # x = self.proj(x)
  124. # x = self.proj_drop(x)
  125. # return x
  126. class GlobalSubSampleAttn(nn.Module):
  127. """ GSA: using a key to summarize the information for a group to be efficient.
  128. """
  129. fused_attn: torch.jit.Final[bool]
  130. def __init__(
  131. self,
  132. dim: int,
  133. num_heads: int = 8,
  134. attn_drop: float = 0.,
  135. proj_drop: float = 0.,
  136. sr_ratio: int = 1,
  137. device=None,
  138. dtype=None,
  139. ):
  140. dd = {'device': device, 'dtype': dtype}
  141. super().__init__()
  142. assert dim % num_heads == 0, f"dim {dim} should be divided by num_heads {num_heads}."
  143. self.dim = dim
  144. self.num_heads = num_heads
  145. head_dim = dim // num_heads
  146. self.scale = head_dim ** -0.5
  147. self.fused_attn = use_fused_attn()
  148. self.q = nn.Linear(dim, dim, bias=True, **dd)
  149. self.kv = nn.Linear(dim, dim * 2, bias=True, **dd)
  150. self.attn_drop = nn.Dropout(attn_drop)
  151. self.proj = nn.Linear(dim, dim, **dd)
  152. self.proj_drop = nn.Dropout(proj_drop)
  153. self.sr_ratio = sr_ratio
  154. if sr_ratio > 1:
  155. self.sr = nn.Conv2d(dim, dim, kernel_size=sr_ratio, stride=sr_ratio, **dd)
  156. self.norm = nn.LayerNorm(dim, **dd)
  157. else:
  158. self.sr = None
  159. self.norm = None
  160. def forward(self, x, size: Size_):
  161. B, N, C = x.shape
  162. q = self.q(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
  163. if self.sr is not None:
  164. x = x.permute(0, 2, 1).reshape(B, C, *size)
  165. x = self.sr(x).reshape(B, C, -1).permute(0, 2, 1)
  166. x = self.norm(x)
  167. kv = self.kv(x).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
  168. k, v = kv.unbind(0)
  169. if self.fused_attn:
  170. x = torch.nn.functional.scaled_dot_product_attention(
  171. q, k, v,
  172. dropout_p=self.attn_drop.p if self.training else 0.,
  173. )
  174. else:
  175. q = q * self.scale
  176. attn = q @ k.transpose(-2, -1)
  177. attn = attn.softmax(dim=-1)
  178. attn = self.attn_drop(attn)
  179. x = attn @ v
  180. x = x.transpose(1, 2).reshape(B, N, C)
  181. x = self.proj(x)
  182. x = self.proj_drop(x)
  183. return x
  184. class Block(nn.Module):
  185. def __init__(
  186. self,
  187. dim: int,
  188. num_heads: int,
  189. mlp_ratio: float = 4.,
  190. proj_drop: float = 0.,
  191. attn_drop: float = 0.,
  192. drop_path: float = 0.,
  193. act_layer: Type[nn.Module] = nn.GELU,
  194. norm_layer: Type[nn.Module] = nn.LayerNorm,
  195. sr_ratio: int = 1,
  196. ws: Optional[int] = None,
  197. device=None,
  198. dtype=None,
  199. ):
  200. super().__init__()
  201. dd = {'device': device, 'dtype': dtype}
  202. self.norm1 = norm_layer(dim, **dd)
  203. if ws is None:
  204. self.attn = Attention(dim, num_heads, False, None, attn_drop, proj_drop, **dd)
  205. elif ws == 1:
  206. self.attn = GlobalSubSampleAttn(dim, num_heads, attn_drop, proj_drop, sr_ratio, **dd)
  207. else:
  208. self.attn = LocallyGroupedAttn(dim, num_heads, attn_drop, proj_drop, ws, **dd)
  209. self.drop_path1 = DropPath(drop_path) if drop_path > 0. else nn.Identity()
  210. self.norm2 = norm_layer(dim, **dd)
  211. self.mlp = Mlp(
  212. in_features=dim,
  213. hidden_features=int(dim * mlp_ratio),
  214. act_layer=act_layer,
  215. drop=proj_drop,
  216. **dd,
  217. )
  218. self.drop_path2 = DropPath(drop_path) if drop_path > 0. else nn.Identity()
  219. def forward(self, x, size: Size_):
  220. x = x + self.drop_path1(self.attn(self.norm1(x), size))
  221. x = x + self.drop_path2(self.mlp(self.norm2(x)))
  222. return x
  223. class PosConv(nn.Module):
  224. # PEG from https://arxiv.org/abs/2102.10882
  225. def __init__(
  226. self,
  227. in_chans: int,
  228. embed_dim: int = 768,
  229. stride: int = 1,
  230. device=None,
  231. dtype=None,
  232. ):
  233. dd = {'device': device, 'dtype': dtype}
  234. super().__init__()
  235. self.proj = nn.Sequential(
  236. nn.Conv2d(in_chans, embed_dim, 3, stride, 1, bias=True, groups=embed_dim, **dd),
  237. )
  238. self.stride = stride
  239. def forward(self, x, size: Size_):
  240. B, N, C = x.shape
  241. cnn_feat_token = x.transpose(1, 2).view(B, C, *size)
  242. x = self.proj(cnn_feat_token)
  243. if self.stride == 1:
  244. x += cnn_feat_token
  245. x = x.flatten(2).transpose(1, 2)
  246. return x
  247. def no_weight_decay(self):
  248. return ['proj.%d.weight' % i for i in range(4)]
  249. class PatchEmbed(nn.Module):
  250. """ Image to Patch Embedding
  251. """
  252. def __init__(
  253. self,
  254. img_size: Union[int, Tuple[int, int]] = 224,
  255. patch_size: Union[int, Tuple[int, int]] = 16,
  256. in_chans: int = 3,
  257. embed_dim: int = 768,
  258. device=None,
  259. dtype=None,
  260. ):
  261. dd = {'device': device, 'dtype': dtype}
  262. super().__init__()
  263. img_size = to_2tuple(img_size)
  264. patch_size = to_2tuple(patch_size)
  265. self.img_size = img_size
  266. self.patch_size = patch_size
  267. assert img_size[0] % patch_size[0] == 0 and img_size[1] % patch_size[1] == 0, \
  268. f"img_size {img_size} should be divided by patch_size {patch_size}."
  269. self.H, self.W = img_size[0] // patch_size[0], img_size[1] // patch_size[1]
  270. self.num_patches = self.H * self.W
  271. self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size, **dd)
  272. self.norm = nn.LayerNorm(embed_dim, **dd)
  273. def forward(self, x) -> Tuple[torch.Tensor, Size_]:
  274. B, C, H, W = x.shape
  275. x = self.proj(x).flatten(2).transpose(1, 2)
  276. x = self.norm(x)
  277. out_size = (H // self.patch_size[0], W // self.patch_size[1])
  278. return x, out_size
  279. class Twins(nn.Module):
  280. """ Twins Vision Transformer (Revisiting Spatial Attention)
  281. Adapted from PVT (PyramidVisionTransformer) class at https://github.com/whai362/PVT.git
  282. """
  283. def __init__(
  284. self,
  285. img_size: Union[int, Tuple[int, int]] = 224,
  286. patch_size: int = 4,
  287. in_chans: int = 3,
  288. num_classes: int = 1000,
  289. global_pool: str = 'avg',
  290. embed_dims: Tuple[int, ...] = (64, 128, 256, 512),
  291. num_heads: Tuple[int, ...] = (1, 2, 4, 8),
  292. mlp_ratios: Tuple[float, ...] = (4, 4, 4, 4),
  293. depths: Tuple[int, ...] = (3, 4, 6, 3),
  294. sr_ratios: Tuple[int, ...] = (8, 4, 2, 1),
  295. wss: Optional[Tuple[int, ...]] = None,
  296. drop_rate: float = 0.,
  297. pos_drop_rate: float = 0.,
  298. proj_drop_rate: float = 0.,
  299. attn_drop_rate: float = 0.,
  300. drop_path_rate: float = 0.,
  301. norm_layer: Type[nn.Module] = partial(nn.LayerNorm, eps=1e-6),
  302. block_cls: Any = Block,
  303. device=None,
  304. dtype=None,
  305. ):
  306. super().__init__()
  307. dd = {'device': device, 'dtype': dtype}
  308. self.num_classes = num_classes
  309. self.in_chans = in_chans
  310. self.global_pool = global_pool
  311. self.depths = depths
  312. self.embed_dims = embed_dims
  313. self.num_features = self.head_hidden_size = embed_dims[-1]
  314. self.grad_checkpointing = False
  315. img_size = to_2tuple(img_size)
  316. prev_chs = in_chans
  317. self.patch_embeds = nn.ModuleList()
  318. self.pos_drops = nn.ModuleList()
  319. for i in range(len(depths)):
  320. self.patch_embeds.append(PatchEmbed(img_size, patch_size, prev_chs, embed_dims[i], **dd))
  321. self.pos_drops.append(nn.Dropout(p=pos_drop_rate))
  322. prev_chs = embed_dims[i]
  323. img_size = tuple(t // patch_size for t in img_size)
  324. patch_size = 2
  325. self.blocks = nn.ModuleList()
  326. self.feature_info = []
  327. dpr = calculate_drop_path_rates(drop_path_rate, sum(depths)) # stochastic depth decay rule
  328. cur = 0
  329. for k in range(len(depths)):
  330. _block = nn.ModuleList([block_cls(
  331. dim=embed_dims[k],
  332. num_heads=num_heads[k],
  333. mlp_ratio=mlp_ratios[k],
  334. proj_drop=proj_drop_rate,
  335. attn_drop=attn_drop_rate,
  336. drop_path=dpr[cur + i],
  337. norm_layer=norm_layer,
  338. sr_ratio=sr_ratios[k],
  339. ws=1 if wss is None or i % 2 == 1 else wss[k],
  340. **dd,
  341. ) for i in range(depths[k])])
  342. self.blocks.append(_block)
  343. self.feature_info += [dict(module=f'block.{k}', num_chs=embed_dims[k], reduction=2**(2+k))]
  344. cur += depths[k]
  345. self.pos_block = nn.ModuleList([PosConv(embed_dim, embed_dim, **dd) for embed_dim in embed_dims])
  346. self.norm = norm_layer(self.num_features, **dd)
  347. # classification head
  348. self.head_drop = nn.Dropout(drop_rate)
  349. self.head = nn.Linear(self.num_features, num_classes, **dd) if num_classes > 0 else nn.Identity()
  350. # init weights
  351. self.apply(self._init_weights)
  352. @torch.jit.ignore
  353. def no_weight_decay(self):
  354. return set(['pos_block.' + n for n, p in self.pos_block.named_parameters()])
  355. @torch.jit.ignore
  356. def group_matcher(self, coarse=False):
  357. matcher = dict(
  358. stem=r'^patch_embeds.0', # stem and embed
  359. blocks=[
  360. (r'^(?:blocks|patch_embeds|pos_block)\.(\d+)', None),
  361. ('^norm', (99999,))
  362. ] if coarse else [
  363. (r'^blocks\.(\d+)\.(\d+)', None),
  364. (r'^(?:patch_embeds|pos_block)\.(\d+)', (0,)),
  365. (r'^norm', (99999,))
  366. ]
  367. )
  368. return matcher
  369. @torch.jit.ignore
  370. def set_grad_checkpointing(self, enable=True):
  371. assert not enable, 'gradient checkpointing not supported'
  372. @torch.jit.ignore
  373. def get_classifier(self) -> nn.Module:
  374. return self.head
  375. def reset_classifier(self, num_classes: int, global_pool: Optional[str] = None):
  376. self.num_classes = num_classes
  377. if global_pool is not None:
  378. assert global_pool in ('', 'avg')
  379. self.global_pool = global_pool
  380. device = self.head.weight.device if hasattr(self.head, 'weight') else None
  381. dtype = self.head.weight.dtype if hasattr(self.head, 'weight') else None
  382. self.head = nn.Linear(self.num_features, num_classes, device=device, dtype=dtype) if num_classes > 0 else nn.Identity()
  383. def _init_weights(self, m):
  384. if isinstance(m, nn.Linear):
  385. trunc_normal_(m.weight, std=.02)
  386. if isinstance(m, nn.Linear) and m.bias is not None:
  387. nn.init.constant_(m.bias, 0)
  388. elif isinstance(m, nn.LayerNorm):
  389. nn.init.constant_(m.bias, 0)
  390. nn.init.constant_(m.weight, 1.0)
  391. elif isinstance(m, nn.Conv2d):
  392. fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
  393. fan_out //= m.groups
  394. m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
  395. if m.bias is not None:
  396. m.bias.data.zero_()
  397. def forward_intermediates(
  398. self,
  399. x: torch.Tensor,
  400. indices: Optional[Union[int, List[int]]] = None,
  401. norm: bool = False,
  402. stop_early: bool = False,
  403. output_fmt: str = 'NCHW',
  404. intermediates_only: bool = False,
  405. ) -> Union[List[torch.Tensor], Tuple[torch.Tensor, List[torch.Tensor]]]:
  406. """ Forward features that returns intermediates.
  407. Args:
  408. x: Input image tensor
  409. indices: Take last n blocks if int, all if None, select matching indices if sequence
  410. norm: Apply norm layer to all intermediates
  411. stop_early: Stop iterating over blocks when last desired intermediate hit
  412. output_fmt: Shape of intermediate feature outputs
  413. intermediates_only: Only return intermediate features
  414. Returns:
  415. """
  416. assert output_fmt == 'NCHW', 'Output shape for Twins must be NCHW.'
  417. intermediates = []
  418. take_indices, max_index = feature_take_indices(len(self.blocks), indices)
  419. # FIXME slice block/pos_block if < max
  420. # forward pass
  421. B, _, height, width = x.shape
  422. for i, (embed, drop, blocks, pos_blk) in enumerate(zip(
  423. self.patch_embeds, self.pos_drops, self.blocks, self.pos_block)
  424. ):
  425. x, size = embed(x)
  426. x = drop(x)
  427. for j, blk in enumerate(blocks):
  428. x = blk(x, size)
  429. if j == 0:
  430. x = pos_blk(x, size) # PEG here
  431. if i < len(self.depths) - 1:
  432. x = x.reshape(B, *size, -1).permute(0, 3, 1, 2).contiguous()
  433. if i in take_indices:
  434. intermediates.append(x)
  435. else:
  436. if i in take_indices:
  437. # only last feature can be normed
  438. x_feat = self.norm(x) if norm else x
  439. intermediates.append(x_feat.reshape(B, *size, -1).permute(0, 3, 1, 2).contiguous())
  440. if intermediates_only:
  441. return intermediates
  442. x = self.norm(x)
  443. return x, intermediates
  444. def prune_intermediate_layers(
  445. self,
  446. indices: Union[int, List[int]] = 1,
  447. prune_norm: bool = False,
  448. prune_head: bool = True,
  449. ):
  450. """ Prune layers not required for specified intermediates.
  451. """
  452. take_indices, max_index = feature_take_indices(len(self.blocks), indices)
  453. # FIXME add block pruning
  454. if prune_norm:
  455. self.norm = nn.Identity()
  456. if prune_head:
  457. self.reset_classifier(0, '')
  458. return take_indices
  459. def forward_features(self, x):
  460. B = x.shape[0]
  461. for i, (embed, drop, blocks, pos_blk) in enumerate(
  462. zip(self.patch_embeds, self.pos_drops, self.blocks, self.pos_block)):
  463. x, size = embed(x)
  464. x = drop(x)
  465. for j, blk in enumerate(blocks):
  466. x = blk(x, size)
  467. if j == 0:
  468. x = pos_blk(x, size) # PEG here
  469. if i < len(self.depths) - 1:
  470. x = x.reshape(B, *size, -1).permute(0, 3, 1, 2).contiguous()
  471. x = self.norm(x)
  472. return x
  473. def forward_head(self, x, pre_logits: bool = False):
  474. if self.global_pool == 'avg':
  475. x = x.mean(dim=1)
  476. x = self.head_drop(x)
  477. return x if pre_logits else self.head(x)
  478. def forward(self, x):
  479. x = self.forward_features(x)
  480. x = self.forward_head(x)
  481. return x
  482. def _create_twins(variant, pretrained=False, **kwargs):
  483. out_indices = kwargs.pop('out_indices', 4)
  484. model = build_model_with_cfg(
  485. Twins, variant, pretrained,
  486. feature_cfg=dict(out_indices=out_indices, feature_cls='getter'),
  487. **kwargs,
  488. )
  489. return model
  490. def _cfg(url='', **kwargs):
  491. return {
  492. 'url': url,
  493. 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': None,
  494. 'crop_pct': .9, 'interpolation': 'bicubic', 'fixed_input_size': True,
  495. 'mean': IMAGENET_DEFAULT_MEAN, 'std': IMAGENET_DEFAULT_STD,
  496. 'first_conv': 'patch_embeds.0.proj', 'classifier': 'head',
  497. 'license': 'apache-2.0',
  498. **kwargs
  499. }
  500. default_cfgs = generate_default_cfgs({
  501. 'twins_pcpvt_small.in1k': _cfg(hf_hub_id='timm/'),
  502. 'twins_pcpvt_base.in1k': _cfg(hf_hub_id='timm/'),
  503. 'twins_pcpvt_large.in1k': _cfg(hf_hub_id='timm/'),
  504. 'twins_svt_small.in1k': _cfg(hf_hub_id='timm/'),
  505. 'twins_svt_base.in1k': _cfg(hf_hub_id='timm/'),
  506. 'twins_svt_large.in1k': _cfg(hf_hub_id='timm/'),
  507. })
  508. @register_model
  509. def twins_pcpvt_small(pretrained=False, **kwargs) -> Twins:
  510. model_args = dict(
  511. patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
  512. depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1])
  513. return _create_twins('twins_pcpvt_small', pretrained=pretrained, **dict(model_args, **kwargs))
  514. @register_model
  515. def twins_pcpvt_base(pretrained=False, **kwargs) -> Twins:
  516. model_args = dict(
  517. patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
  518. depths=[3, 4, 18, 3], sr_ratios=[8, 4, 2, 1])
  519. return _create_twins('twins_pcpvt_base', pretrained=pretrained, **dict(model_args, **kwargs))
  520. @register_model
  521. def twins_pcpvt_large(pretrained=False, **kwargs) -> Twins:
  522. model_args = dict(
  523. patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
  524. depths=[3, 8, 27, 3], sr_ratios=[8, 4, 2, 1])
  525. return _create_twins('twins_pcpvt_large', pretrained=pretrained, **dict(model_args, **kwargs))
  526. @register_model
  527. def twins_svt_small(pretrained=False, **kwargs) -> Twins:
  528. model_args = dict(
  529. patch_size=4, embed_dims=[64, 128, 256, 512], num_heads=[2, 4, 8, 16], mlp_ratios=[4, 4, 4, 4],
  530. depths=[2, 2, 10, 4], wss=[7, 7, 7, 7], sr_ratios=[8, 4, 2, 1])
  531. return _create_twins('twins_svt_small', pretrained=pretrained, **dict(model_args, **kwargs))
  532. @register_model
  533. def twins_svt_base(pretrained=False, **kwargs) -> Twins:
  534. model_args = dict(
  535. patch_size=4, embed_dims=[96, 192, 384, 768], num_heads=[3, 6, 12, 24], mlp_ratios=[4, 4, 4, 4],
  536. depths=[2, 2, 18, 2], wss=[7, 7, 7, 7], sr_ratios=[8, 4, 2, 1])
  537. return _create_twins('twins_svt_base', pretrained=pretrained, **dict(model_args, **kwargs))
  538. @register_model
  539. def twins_svt_large(pretrained=False, **kwargs) -> Twins:
  540. model_args = dict(
  541. patch_size=4, embed_dims=[128, 256, 512, 1024], num_heads=[4, 8, 16, 32], mlp_ratios=[4, 4, 4, 4],
  542. depths=[2, 2, 18, 2], wss=[7, 7, 7, 7], sr_ratios=[8, 4, 2, 1])
  543. return _create_twins('twins_svt_large', pretrained=pretrained, **dict(model_args, **kwargs))