swin_v1.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. import torch
  2. import torch.nn as nn
  3. import torch.nn.functional as F
  4. import torch.utils.checkpoint as checkpoint
  5. from timm.layers import DropPath, to_2tuple, trunc_normal_
  6. from config import Config
  7. config = Config()
  8. class Mlp(nn.Module):
  9. """ Multilayer perceptron."""
  10. def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
  11. super().__init__()
  12. out_features = out_features or in_features
  13. hidden_features = hidden_features or in_features
  14. self.fc1 = nn.Linear(in_features, hidden_features)
  15. self.act = act_layer()
  16. self.fc2 = nn.Linear(hidden_features, out_features)
  17. self.drop = nn.Dropout(drop)
  18. def forward(self, x):
  19. x = self.fc1(x)
  20. x = self.act(x)
  21. x = self.drop(x)
  22. x = self.fc2(x)
  23. x = self.drop(x)
  24. return x
  25. def window_partition(x, window_size):
  26. """
  27. Args:
  28. x: (B, H, W, C)
  29. window_size (int): window size
  30. Returns:
  31. windows: (num_windows*B, window_size, window_size, C)
  32. """
  33. B, H, W, C = x.shape
  34. x = x.view(B, H // window_size, window_size, W // window_size, window_size, C)
  35. windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
  36. return windows
  37. def window_reverse(windows, window_size, H, W):
  38. """
  39. Args:
  40. windows: (num_windows*B, window_size, window_size, C)
  41. window_size (int): Window size
  42. H (int): Height of image
  43. W (int): Width of image
  44. Returns:
  45. x: (B, H, W, C)
  46. """
  47. C = int(windows.shape[-1])
  48. x = windows.view(-1, H // window_size, W // window_size, window_size, window_size, C)
  49. x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, H, W, C)
  50. return x
  51. class WindowAttention(nn.Module):
  52. """ Window based multi-head self attention (W-MSA) module with relative position bias.
  53. It supports both of shifted and non-shifted window.
  54. Args:
  55. dim (int): Number of input channels.
  56. window_size (tuple[int]): The height and width of the window.
  57. num_heads (int): Number of attention heads.
  58. qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
  59. qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set
  60. attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
  61. proj_drop (float, optional): Dropout ratio of output. Default: 0.0
  62. """
  63. def __init__(self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0., proj_drop=0., sdpa_backend='auto'):
  64. super().__init__()
  65. self.sdpa_backend = sdpa_backend
  66. self.dim = dim
  67. self.window_size = window_size # Wh, Ww
  68. self.num_heads = num_heads
  69. head_dim = dim // num_heads
  70. self.scale = qk_scale or head_dim ** -0.5
  71. # define a parameter table of relative position bias
  72. self.relative_position_bias_table = nn.Parameter(torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)) # 2*Wh-1 * 2*Ww-1, nH
  73. # get pair-wise relative position index for each token inside the window
  74. coords_h = torch.arange(self.window_size[0])
  75. coords_w = torch.arange(self.window_size[1])
  76. coords = torch.stack(torch.meshgrid([coords_h, coords_w], indexing='ij')) # 2, Wh, Ww
  77. coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
  78. relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
  79. relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
  80. relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0
  81. relative_coords[:, :, 1] += self.window_size[1] - 1
  82. relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
  83. relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
  84. self.register_buffer("relative_position_index", relative_position_index)
  85. self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
  86. self.attn_drop_prob = attn_drop
  87. self.attn_drop = nn.Dropout(attn_drop)
  88. self.proj = nn.Linear(dim, dim)
  89. self.proj_drop = nn.Dropout(proj_drop)
  90. trunc_normal_(self.relative_position_bias_table, std=.02)
  91. self.softmax = nn.Softmax(dim=-1)
  92. def forward(self, x, mask=None):
  93. """ Forward function.
  94. Args:
  95. x: input features with shape of (num_windows*B, N, C)
  96. mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None
  97. """
  98. B_, N, C = x.shape
  99. assert N == self.window_size[0] * self.window_size[1], "N must equal Wh*Ww for Swin window attention"
  100. qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
  101. q, k, v = qkv.unbind(0) # [B_, H, N, Dh]
  102. relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(
  103. N, N, -1
  104. ).permute(2, 0, 1).unsqueeze(0).to(dtype=q.dtype, device=q.device)
  105. if mask is not None:
  106. mask = mask.to(dtype=q.dtype).unsqueeze(1)
  107. if config.SDPA_enabled:
  108. attn_mask = relative_position_bias
  109. if mask is not None:
  110. attn_mask = attn_mask + mask
  111. attn_out = F.scaled_dot_product_attention(
  112. q, k, v,
  113. attn_mask=attn_mask, # None or [B_|1, H|1, N, N]
  114. dropout_p=self.attn_drop_prob if self.training else 0.0,
  115. is_causal=False
  116. ) # [B_, H, N, Dh]
  117. x = attn_out.transpose(1, 2).reshape(B_, N, C)
  118. else:
  119. q = q * self.scale
  120. attn = q @ k.transpose(-2, -1)
  121. attn = attn + relative_position_bias
  122. if mask is not None:
  123. nW = mask.shape[0]
  124. attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(0)
  125. attn = attn.view(-1, self.num_heads, N, N)
  126. attn = self.softmax(attn)
  127. attn = self.attn_drop(attn)
  128. x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
  129. x = self.proj(x)
  130. x = self.proj_drop(x)
  131. return x
  132. class SwinTransformerBlock(nn.Module):
  133. """ Swin Transformer Block.
  134. Args:
  135. dim (int): Number of input channels.
  136. num_heads (int): Number of attention heads.
  137. window_size (int): Window size.
  138. shift_size (int): Shift size for SW-MSA.
  139. mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
  140. qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
  141. qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
  142. drop (float, optional): Dropout rate. Default: 0.0
  143. attn_drop (float, optional): Attention dropout rate. Default: 0.0
  144. drop_path (float, optional): Stochastic depth rate. Default: 0.0
  145. act_layer (nn.Module, optional): Activation layer. Default: nn.GELU
  146. norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
  147. """
  148. def __init__(self, dim, num_heads, window_size=7, shift_size=0,
  149. mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0.,
  150. act_layer=nn.GELU, norm_layer=nn.LayerNorm):
  151. super().__init__()
  152. self.dim = dim
  153. self.num_heads = num_heads
  154. self.window_size = window_size
  155. self.shift_size = shift_size
  156. self.mlp_ratio = mlp_ratio
  157. assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size"
  158. self.norm1 = norm_layer(dim)
  159. self.attn = WindowAttention(
  160. dim, window_size=to_2tuple(self.window_size), num_heads=num_heads,
  161. qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
  162. self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
  163. self.norm2 = norm_layer(dim)
  164. mlp_hidden_dim = int(dim * mlp_ratio)
  165. self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
  166. self.H = None
  167. self.W = None
  168. def forward(self, x, mask_matrix):
  169. """ Forward function.
  170. Args:
  171. x: Input feature, tensor size (B, H*W, C).
  172. H, W: Spatial resolution of the input feature.
  173. mask_matrix: Attention mask for cyclic shift.
  174. """
  175. B, L, C = x.shape
  176. H, W = self.H, self.W
  177. assert L == H * W, "input feature has wrong size"
  178. shortcut = x
  179. x = self.norm1(x)
  180. x = x.view(B, H, W, C)
  181. # pad feature maps to multiples of window size
  182. pad_l = pad_t = 0
  183. pad_r = (self.window_size - W % self.window_size) % self.window_size
  184. pad_b = (self.window_size - H % self.window_size) % self.window_size
  185. x = F.pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b))
  186. _, Hp, Wp, _ = x.shape
  187. # cyclic shift
  188. if self.shift_size > 0:
  189. shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
  190. if config.SDPA_enabled:
  191. B = x.size(0)
  192. nW, N = mask_matrix.size(0), mask_matrix.size(1)
  193. attn_mask = mask_matrix.unsqueeze(0).expand(B, nW, N, N).reshape(B * nW, N, N)
  194. else:
  195. attn_mask = mask_matrix
  196. else:
  197. shifted_x = x
  198. attn_mask = None
  199. # partition windows
  200. x_windows = window_partition(shifted_x, self.window_size) # nW*B, window_size, window_size, C
  201. x_windows = x_windows.view(-1, self.window_size * self.window_size, C) # nW*B, window_size*window_size, C
  202. # W-MSA/SW-MSA
  203. attn_windows = self.attn(x_windows, mask=attn_mask) # nW*B, window_size*window_size, C
  204. # merge windows
  205. attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C)
  206. shifted_x = window_reverse(attn_windows, self.window_size, Hp, Wp) # B H' W' C
  207. # reverse cyclic shift
  208. if self.shift_size > 0:
  209. x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
  210. else:
  211. x = shifted_x
  212. if pad_r > 0 or pad_b > 0:
  213. x = x[:, :H, :W, :].contiguous()
  214. x = x.view(B, H * W, C)
  215. # FFN
  216. x = shortcut + self.drop_path(x)
  217. x = x + self.drop_path(self.mlp(self.norm2(x)))
  218. return x
  219. class PatchMerging(nn.Module):
  220. """ Patch Merging Layer
  221. Args:
  222. dim (int): Number of input channels.
  223. norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
  224. """
  225. def __init__(self, dim, norm_layer=nn.LayerNorm):
  226. super().__init__()
  227. self.dim = dim
  228. self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
  229. self.norm = norm_layer(4 * dim)
  230. def forward(self, x, H, W):
  231. """ Forward function.
  232. Args:
  233. x: Input feature, tensor size (B, H*W, C).
  234. H, W: Spatial resolution of the input feature.
  235. """
  236. B, L, C = x.shape
  237. assert L == H * W, "input feature has wrong size"
  238. x = x.view(B, H, W, C)
  239. # padding
  240. pad_input = (H % 2 == 1) or (W % 2 == 1)
  241. if pad_input:
  242. x = F.pad(x, (0, 0, 0, W % 2, 0, H % 2))
  243. x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C
  244. x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C
  245. x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C
  246. x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C
  247. x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C
  248. x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C
  249. x = self.norm(x)
  250. x = self.reduction(x)
  251. return x
  252. class BasicLayer(nn.Module):
  253. """ A basic Swin Transformer layer for one stage.
  254. Args:
  255. dim (int): Number of feature channels
  256. depth (int): Depths of this stage.
  257. num_heads (int): Number of attention head.
  258. window_size (int): Local window size. Default: 7.
  259. mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.
  260. qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
  261. qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
  262. drop (float, optional): Dropout rate. Default: 0.0
  263. attn_drop (float, optional): Attention dropout rate. Default: 0.0
  264. drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
  265. norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
  266. downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
  267. use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
  268. """
  269. def __init__(self,
  270. dim,
  271. depth,
  272. num_heads,
  273. window_size=7,
  274. mlp_ratio=4.,
  275. qkv_bias=True,
  276. qk_scale=None,
  277. drop=0.,
  278. attn_drop=0.,
  279. drop_path=0.,
  280. norm_layer=nn.LayerNorm,
  281. downsample=None,
  282. use_checkpoint=False):
  283. super().__init__()
  284. self.window_size = window_size
  285. self.shift_size = window_size // 2
  286. self.depth = depth
  287. self.use_checkpoint = use_checkpoint
  288. # build blocks
  289. self.blocks = nn.ModuleList([
  290. SwinTransformerBlock(
  291. dim=dim,
  292. num_heads=num_heads,
  293. window_size=window_size,
  294. shift_size=0 if (i % 2 == 0) else window_size // 2,
  295. mlp_ratio=mlp_ratio,
  296. qkv_bias=qkv_bias,
  297. qk_scale=qk_scale,
  298. drop=drop,
  299. attn_drop=attn_drop,
  300. drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,
  301. norm_layer=norm_layer)
  302. for i in range(depth)])
  303. # patch merging layer
  304. if downsample is not None:
  305. self.downsample = downsample(dim=dim, norm_layer=norm_layer)
  306. else:
  307. self.downsample = None
  308. def forward(self, x, H, W):
  309. """ Forward function.
  310. Args:
  311. x: Input feature, tensor size (B, H*W, C).
  312. H, W: Spatial resolution of the input feature.
  313. """
  314. # calculate attention mask for SW-MSA
  315. # Turn int to torch.tensor for the compatiability with torch.compile in PyTorch >= 2.5.
  316. Hp = torch.ceil(torch.tensor(H) / self.window_size).to(torch.int64) * self.window_size
  317. Wp = torch.ceil(torch.tensor(W) / self.window_size).to(torch.int64) * self.window_size
  318. img_mask = torch.zeros((1, Hp, Wp, 1), device=x.device) # 1 Hp Wp 1
  319. h_slices = (slice(0, -self.window_size),
  320. slice(-self.window_size, -self.shift_size),
  321. slice(-self.shift_size, None))
  322. w_slices = (slice(0, -self.window_size),
  323. slice(-self.window_size, -self.shift_size),
  324. slice(-self.shift_size, None))
  325. cnt = 0
  326. for h in h_slices:
  327. for w in w_slices:
  328. img_mask[:, h, w, :] = cnt
  329. cnt += 1
  330. mask_windows = window_partition(img_mask, self.window_size) # nW, window_size, window_size, 1
  331. mask_windows = mask_windows.view(-1, self.window_size * self.window_size)
  332. attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
  333. attn_mask = attn_mask.masked_fill(attn_mask != 0, float('-inf')).masked_fill(attn_mask == 0, float(0.0)).to(x.dtype)
  334. for blk in self.blocks:
  335. blk.H, blk.W = H, W
  336. if self.use_checkpoint:
  337. x = checkpoint.checkpoint(blk, x, attn_mask)
  338. else:
  339. x = blk(x, attn_mask)
  340. if self.downsample is not None:
  341. x_down = self.downsample(x, H, W)
  342. Wh, Ww = (H + 1) // 2, (W + 1) // 2
  343. return x, H, W, x_down, Wh, Ww
  344. else:
  345. return x, H, W, x, H, W
  346. class PatchEmbed(nn.Module):
  347. """ Image to Patch Embedding
  348. Args:
  349. patch_size (int): Patch token size. Default: 4.
  350. in_channels (int): Number of input image channels. Default: 3.
  351. embed_dim (int): Number of linear projection output channels. Default: 96.
  352. norm_layer (nn.Module, optional): Normalization layer. Default: None
  353. """
  354. def __init__(self, patch_size=4, in_channels=3, embed_dim=96, norm_layer=None):
  355. super().__init__()
  356. patch_size = to_2tuple(patch_size)
  357. self.patch_size = patch_size
  358. self.in_channels = in_channels
  359. self.embed_dim = embed_dim
  360. self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=patch_size)
  361. self.norm = norm_layer(embed_dim) if norm_layer is not None else None
  362. def forward(self, x):
  363. """Forward function."""
  364. # padding
  365. _, _, H, W = x.size()
  366. if W % self.patch_size[1] != 0:
  367. x = F.pad(x, (0, self.patch_size[1] - W % self.patch_size[1]))
  368. if H % self.patch_size[0] != 0:
  369. x = F.pad(x, (0, 0, 0, self.patch_size[0] - H % self.patch_size[0]))
  370. x = self.proj(x) # B C Wh Ww
  371. if self.norm is not None:
  372. Wh, Ww = x.size(2), x.size(3)
  373. x = x.flatten(2).transpose(1, 2)
  374. x = self.norm(x)
  375. x = x.transpose(1, 2).view(-1, self.embed_dim, Wh, Ww)
  376. return x
  377. class SwinTransformer(nn.Module):
  378. """ Swin Transformer backbone.
  379. A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows` -
  380. https://arxiv.org/pdf/2103.14030
  381. Args:
  382. pretrain_img_size (int): Input image size for training the pretrained model,
  383. used in absolute postion embedding. Default 224.
  384. patch_size (int | tuple(int)): Patch size. Default: 4.
  385. in_channels (int): Number of input image channels. Default: 3.
  386. embed_dim (int): Number of linear projection output channels. Default: 96.
  387. depths (tuple[int]): Depths of each Swin Transformer stage.
  388. num_heads (tuple[int]): Number of attention head of each stage.
  389. window_size (int): Window size. Default: 7.
  390. mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.
  391. qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True
  392. qk_scale (float): Override default qk scale of head_dim ** -0.5 if set.
  393. drop_rate (float): Dropout rate.
  394. attn_drop_rate (float): Attention dropout rate. Default: 0.
  395. drop_path_rate (float): Stochastic depth rate. Default: 0.2.
  396. norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm.
  397. ape (bool): If True, add absolute position embedding to the patch embedding. Default: False.
  398. patch_norm (bool): If True, add normalization after patch embedding. Default: True.
  399. out_indices (Sequence[int]): Output from which stages.
  400. frozen_stages (int): Stages to be frozen (stop grad and set eval mode).
  401. -1 means not freezing any parameters.
  402. use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
  403. """
  404. def __init__(self,
  405. pretrain_img_size=224,
  406. patch_size=4,
  407. in_channels=3,
  408. embed_dim=96,
  409. depths=[2, 2, 6, 2],
  410. num_heads=[3, 6, 12, 24],
  411. window_size=7,
  412. mlp_ratio=4.,
  413. qkv_bias=True,
  414. qk_scale=None,
  415. drop_rate=0.,
  416. attn_drop_rate=0.,
  417. drop_path_rate=0.2,
  418. norm_layer=nn.LayerNorm,
  419. ape=False,
  420. patch_norm=True,
  421. out_indices=(0, 1, 2, 3),
  422. frozen_stages=-1,
  423. use_checkpoint=False):
  424. super().__init__()
  425. self.pretrain_img_size = pretrain_img_size
  426. self.num_layers = len(depths)
  427. self.embed_dim = embed_dim
  428. self.ape = ape
  429. self.patch_norm = patch_norm
  430. self.out_indices = out_indices
  431. self.frozen_stages = frozen_stages
  432. # split image into non-overlapping patches
  433. self.patch_embed = PatchEmbed(
  434. patch_size=patch_size, in_channels=in_channels, embed_dim=embed_dim,
  435. norm_layer=norm_layer if self.patch_norm else None)
  436. # absolute position embedding
  437. if self.ape:
  438. pretrain_img_size = to_2tuple(pretrain_img_size)
  439. patch_size = to_2tuple(patch_size)
  440. patches_resolution = [pretrain_img_size[0] // patch_size[0], pretrain_img_size[1] // patch_size[1]]
  441. self.absolute_pos_embed = nn.Parameter(torch.zeros(1, embed_dim, patches_resolution[0], patches_resolution[1]))
  442. trunc_normal_(self.absolute_pos_embed, std=.02)
  443. self.pos_drop = nn.Dropout(p=drop_rate)
  444. # stochastic depth
  445. dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule
  446. # build layers
  447. self.layers = nn.ModuleList()
  448. for i_layer in range(self.num_layers):
  449. layer = BasicLayer(
  450. dim=int(embed_dim * 2 ** i_layer),
  451. depth=depths[i_layer],
  452. num_heads=num_heads[i_layer],
  453. window_size=window_size,
  454. mlp_ratio=mlp_ratio,
  455. qkv_bias=qkv_bias,
  456. qk_scale=qk_scale,
  457. drop=drop_rate,
  458. attn_drop=attn_drop_rate,
  459. drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])],
  460. norm_layer=norm_layer,
  461. downsample=PatchMerging if (i_layer < self.num_layers - 1) else None,
  462. use_checkpoint=use_checkpoint)
  463. self.layers.append(layer)
  464. num_features = [int(embed_dim * 2 ** i) for i in range(self.num_layers)]
  465. self.num_features = num_features
  466. # add a norm layer for each output
  467. for i_layer in out_indices:
  468. layer = norm_layer(num_features[i_layer])
  469. layer_name = f'norm{i_layer}'
  470. self.add_module(layer_name, layer)
  471. self._freeze_stages()
  472. def _freeze_stages(self):
  473. if self.frozen_stages >= 0:
  474. self.patch_embed.eval()
  475. for param in self.patch_embed.parameters():
  476. param.requires_grad = False
  477. if self.frozen_stages >= 1 and self.ape:
  478. self.absolute_pos_embed.requires_grad = False
  479. if self.frozen_stages >= 2:
  480. self.pos_drop.eval()
  481. for i in range(0, self.frozen_stages - 1):
  482. m = self.layers[i]
  483. m.eval()
  484. for param in m.parameters():
  485. param.requires_grad = False
  486. def forward(self, x):
  487. """Forward function."""
  488. x = self.patch_embed(x)
  489. Wh, Ww = x.size(2), x.size(3)
  490. if self.ape:
  491. # interpolate the position embedding to the corresponding size
  492. absolute_pos_embed = F.interpolate(self.absolute_pos_embed, size=(Wh, Ww), mode='bicubic')
  493. x = (x + absolute_pos_embed) # B Wh*Ww C
  494. outs = []#x.contiguous()]
  495. x = x.flatten(2).transpose(1, 2)
  496. x = self.pos_drop(x)
  497. for i in range(self.num_layers):
  498. layer = self.layers[i]
  499. x_out, H, W, x, Wh, Ww = layer(x, Wh, Ww)
  500. if i in self.out_indices:
  501. norm_layer = getattr(self, f'norm{i}')
  502. x_out = norm_layer(x_out)
  503. out = x_out.view(-1, H, W, self.num_features[i]).permute(0, 3, 1, 2).contiguous()
  504. outs.append(out)
  505. return tuple(outs)
  506. def train(self, mode=True):
  507. """Convert the model into training mode while keep layers freezed."""
  508. super(SwinTransformer, self).train(mode)
  509. self._freeze_stages()
  510. def swin_v1_t():
  511. model = SwinTransformer(embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24], window_size=7)
  512. return model
  513. def swin_v1_s():
  514. model = SwinTransformer(embed_dim=96, depths=[2, 2, 18, 2], num_heads=[3, 6, 12, 24], window_size=7)
  515. return model
  516. def swin_v1_b():
  517. model = SwinTransformer(embed_dim=128, depths=[2, 2, 18, 2], num_heads=[4, 8, 16, 32], window_size=12)
  518. return model
  519. def swin_v1_l():
  520. model = SwinTransformer(embed_dim=192, depths=[2, 2, 18, 2], num_heads=[6, 12, 24, 48], window_size=12)
  521. return model