3
0

swin_mlp.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. # --------------------------------------------------------
  2. # Swin Transformer
  3. # Copyright (c) 2021 Microsoft
  4. # Licensed under The MIT License [see LICENSE for details]
  5. # Written by Ze Liu
  6. # --------------------------------------------------------
  7. import torch
  8. import torch.nn as nn
  9. import torch.nn.functional as F
  10. import torch.utils.checkpoint as checkpoint
  11. from timm.models.layers import DropPath, to_2tuple, trunc_normal_
  12. class Mlp(nn.Module):
  13. def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
  14. super().__init__()
  15. out_features = out_features or in_features
  16. hidden_features = hidden_features or in_features
  17. self.fc1 = nn.Linear(in_features, hidden_features)
  18. self.act = act_layer()
  19. self.fc2 = nn.Linear(hidden_features, out_features)
  20. self.drop = nn.Dropout(drop)
  21. def forward(self, x):
  22. x = self.fc1(x)
  23. x = self.act(x)
  24. x = self.drop(x)
  25. x = self.fc2(x)
  26. x = self.drop(x)
  27. return x
  28. def window_partition(x, window_size):
  29. """
  30. Args:
  31. x: (B, H, W, C)
  32. window_size (int): window size
  33. Returns:
  34. windows: (num_windows*B, window_size, window_size, C)
  35. """
  36. B, H, W, C = x.shape
  37. x = x.view(B, H // window_size, window_size, W // window_size, window_size, C)
  38. windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
  39. return windows
  40. def window_reverse(windows, window_size, H, W):
  41. """
  42. Args:
  43. windows: (num_windows*B, window_size, window_size, C)
  44. window_size (int): Window size
  45. H (int): Height of image
  46. W (int): Width of image
  47. Returns:
  48. x: (B, H, W, C)
  49. """
  50. B = int(windows.shape[0] / (H * W / window_size / window_size))
  51. x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1)
  52. x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)
  53. return x
  54. class SwinMLPBlock(nn.Module):
  55. r""" Swin MLP Block.
  56. Args:
  57. dim (int): Number of input channels.
  58. input_resolution (tuple[int]): Input resulotion.
  59. num_heads (int): Number of attention heads.
  60. window_size (int): Window size.
  61. shift_size (int): Shift size for SW-MSA.
  62. mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
  63. drop (float, optional): Dropout rate. Default: 0.0
  64. drop_path (float, optional): Stochastic depth rate. Default: 0.0
  65. act_layer (nn.Module, optional): Activation layer. Default: nn.GELU
  66. norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
  67. """
  68. def __init__(self, dim, input_resolution, num_heads, window_size=7, shift_size=0,
  69. mlp_ratio=4., drop=0., drop_path=0.,
  70. act_layer=nn.GELU, norm_layer=nn.LayerNorm):
  71. super().__init__()
  72. self.dim = dim
  73. self.input_resolution = input_resolution
  74. self.num_heads = num_heads
  75. self.window_size = window_size
  76. self.shift_size = shift_size
  77. self.mlp_ratio = mlp_ratio
  78. if min(self.input_resolution) <= self.window_size:
  79. # if window size is larger than input resolution, we don't partition windows
  80. self.shift_size = 0
  81. self.window_size = min(self.input_resolution)
  82. assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size"
  83. self.padding = [self.window_size - self.shift_size, self.shift_size,
  84. self.window_size - self.shift_size, self.shift_size] # P_l,P_r,P_t,P_b
  85. self.norm1 = norm_layer(dim)
  86. # use group convolution to implement multi-head MLP
  87. self.spatial_mlp = nn.Conv1d(self.num_heads * self.window_size ** 2,
  88. self.num_heads * self.window_size ** 2,
  89. kernel_size=1,
  90. groups=self.num_heads)
  91. self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
  92. self.norm2 = norm_layer(dim)
  93. mlp_hidden_dim = int(dim * mlp_ratio)
  94. self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
  95. def forward(self, x):
  96. H, W = self.input_resolution
  97. B, L, C = x.shape
  98. assert L == H * W, "input feature has wrong size"
  99. shortcut = x
  100. x = self.norm1(x)
  101. x = x.view(B, H, W, C)
  102. # shift
  103. if self.shift_size > 0:
  104. P_l, P_r, P_t, P_b = self.padding
  105. shifted_x = F.pad(x, [0, 0, P_l, P_r, P_t, P_b], "constant", 0)
  106. else:
  107. shifted_x = x
  108. _, _H, _W, _ = shifted_x.shape
  109. # partition windows
  110. x_windows = window_partition(shifted_x, self.window_size) # nW*B, window_size, window_size, C
  111. x_windows = x_windows.view(-1, self.window_size * self.window_size, C) # nW*B, window_size*window_size, C
  112. # Window/Shifted-Window Spatial MLP
  113. x_windows_heads = x_windows.view(-1, self.window_size * self.window_size, self.num_heads, C // self.num_heads)
  114. x_windows_heads = x_windows_heads.transpose(1, 2) # nW*B, nH, window_size*window_size, C//nH
  115. x_windows_heads = x_windows_heads.reshape(-1, self.num_heads * self.window_size * self.window_size,
  116. C // self.num_heads)
  117. spatial_mlp_windows = self.spatial_mlp(x_windows_heads) # nW*B, nH*window_size*window_size, C//nH
  118. spatial_mlp_windows = spatial_mlp_windows.view(-1, self.num_heads, self.window_size * self.window_size,
  119. C // self.num_heads).transpose(1, 2)
  120. spatial_mlp_windows = spatial_mlp_windows.reshape(-1, self.window_size * self.window_size, C)
  121. # merge windows
  122. spatial_mlp_windows = spatial_mlp_windows.reshape(-1, self.window_size, self.window_size, C)
  123. shifted_x = window_reverse(spatial_mlp_windows, self.window_size, _H, _W) # B H' W' C
  124. # reverse shift
  125. if self.shift_size > 0:
  126. P_l, P_r, P_t, P_b = self.padding
  127. x = shifted_x[:, P_t:-P_b, P_l:-P_r, :].contiguous()
  128. else:
  129. x = shifted_x
  130. x = x.view(B, H * W, C)
  131. # FFN
  132. x = shortcut + self.drop_path(x)
  133. x = x + self.drop_path(self.mlp(self.norm2(x)))
  134. return x
  135. def extra_repr(self) -> str:
  136. return f"dim={self.dim}, input_resolution={self.input_resolution}, num_heads={self.num_heads}, " \
  137. f"window_size={self.window_size}, shift_size={self.shift_size}, mlp_ratio={self.mlp_ratio}"
  138. def flops(self):
  139. flops = 0
  140. H, W = self.input_resolution
  141. # norm1
  142. flops += self.dim * H * W
  143. # Window/Shifted-Window Spatial MLP
  144. if self.shift_size > 0:
  145. nW = (H / self.window_size + 1) * (W / self.window_size + 1)
  146. else:
  147. nW = H * W / self.window_size / self.window_size
  148. flops += nW * self.dim * (self.window_size * self.window_size) * (self.window_size * self.window_size)
  149. # mlp
  150. flops += 2 * H * W * self.dim * self.dim * self.mlp_ratio
  151. # norm2
  152. flops += self.dim * H * W
  153. return flops
  154. class PatchMerging(nn.Module):
  155. r""" Patch Merging Layer.
  156. Args:
  157. input_resolution (tuple[int]): Resolution of input feature.
  158. dim (int): Number of input channels.
  159. norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
  160. """
  161. def __init__(self, input_resolution, dim, norm_layer=nn.LayerNorm):
  162. super().__init__()
  163. self.input_resolution = input_resolution
  164. self.dim = dim
  165. self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
  166. self.norm = norm_layer(4 * dim)
  167. def forward(self, x):
  168. """
  169. x: B, H*W, C
  170. """
  171. H, W = self.input_resolution
  172. B, L, C = x.shape
  173. assert L == H * W, "input feature has wrong size"
  174. assert H % 2 == 0 and W % 2 == 0, f"x size ({H}*{W}) are not even."
  175. x = x.view(B, H, W, C)
  176. x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C
  177. x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C
  178. x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C
  179. x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C
  180. x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C
  181. x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C
  182. x = self.norm(x)
  183. x = self.reduction(x)
  184. return x
  185. def extra_repr(self) -> str:
  186. return f"input_resolution={self.input_resolution}, dim={self.dim}"
  187. def flops(self):
  188. H, W = self.input_resolution
  189. flops = H * W * self.dim
  190. flops += (H // 2) * (W // 2) * 4 * self.dim * 2 * self.dim
  191. return flops
  192. class BasicLayer(nn.Module):
  193. """ A basic Swin MLP layer for one stage.
  194. Args:
  195. dim (int): Number of input channels.
  196. input_resolution (tuple[int]): Input resolution.
  197. depth (int): Number of blocks.
  198. num_heads (int): Number of attention heads.
  199. window_size (int): Local window size.
  200. mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
  201. drop (float, optional): Dropout rate. Default: 0.0
  202. drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
  203. norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
  204. downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
  205. use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
  206. """
  207. def __init__(self, dim, input_resolution, depth, num_heads, window_size,
  208. mlp_ratio=4., drop=0., drop_path=0.,
  209. norm_layer=nn.LayerNorm, downsample=None, use_checkpoint=False):
  210. super().__init__()
  211. self.dim = dim
  212. self.input_resolution = input_resolution
  213. self.depth = depth
  214. self.use_checkpoint = use_checkpoint
  215. # build blocks
  216. self.blocks = nn.ModuleList([
  217. SwinMLPBlock(dim=dim, input_resolution=input_resolution,
  218. num_heads=num_heads, window_size=window_size,
  219. shift_size=0 if (i % 2 == 0) else window_size // 2,
  220. mlp_ratio=mlp_ratio,
  221. drop=drop,
  222. drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,
  223. norm_layer=norm_layer)
  224. for i in range(depth)])
  225. # patch merging layer
  226. if downsample is not None:
  227. self.downsample = downsample(input_resolution, dim=dim, norm_layer=norm_layer)
  228. else:
  229. self.downsample = None
  230. def forward(self, x):
  231. for blk in self.blocks:
  232. if self.use_checkpoint:
  233. x = checkpoint.checkpoint(blk, x)
  234. else:
  235. x = blk(x)
  236. if self.downsample is not None:
  237. x = self.downsample(x)
  238. return x
  239. def extra_repr(self) -> str:
  240. return f"dim={self.dim}, input_resolution={self.input_resolution}, depth={self.depth}"
  241. def flops(self):
  242. flops = 0
  243. for blk in self.blocks:
  244. flops += blk.flops()
  245. if self.downsample is not None:
  246. flops += self.downsample.flops()
  247. return flops
  248. class PatchEmbed(nn.Module):
  249. r""" Image to Patch Embedding
  250. Args:
  251. img_size (int): Image size. Default: 224.
  252. patch_size (int): Patch token size. Default: 4.
  253. in_chans (int): Number of input image channels. Default: 3.
  254. embed_dim (int): Number of linear projection output channels. Default: 96.
  255. norm_layer (nn.Module, optional): Normalization layer. Default: None
  256. """
  257. def __init__(self, img_size=224, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None):
  258. super().__init__()
  259. img_size = to_2tuple(img_size)
  260. patch_size = to_2tuple(patch_size)
  261. patches_resolution = [img_size[0] // patch_size[0], img_size[1] // patch_size[1]]
  262. self.img_size = img_size
  263. self.patch_size = patch_size
  264. self.patches_resolution = patches_resolution
  265. self.num_patches = patches_resolution[0] * patches_resolution[1]
  266. self.in_chans = in_chans
  267. self.embed_dim = embed_dim
  268. self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
  269. if norm_layer is not None:
  270. self.norm = norm_layer(embed_dim)
  271. else:
  272. self.norm = None
  273. def forward(self, x):
  274. B, C, H, W = x.shape
  275. # FIXME look at relaxing size constraints
  276. assert H == self.img_size[0] and W == self.img_size[1], \
  277. f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
  278. x = self.proj(x).flatten(2).transpose(1, 2) # B Ph*Pw C
  279. if self.norm is not None:
  280. x = self.norm(x)
  281. return x
  282. def flops(self):
  283. Ho, Wo = self.patches_resolution
  284. flops = Ho * Wo * self.embed_dim * self.in_chans * (self.patch_size[0] * self.patch_size[1])
  285. if self.norm is not None:
  286. flops += Ho * Wo * self.embed_dim
  287. return flops
  288. class SwinMLP(nn.Module):
  289. r""" Swin MLP
  290. Args:
  291. img_size (int | tuple(int)): Input image size. Default 224
  292. patch_size (int | tuple(int)): Patch size. Default: 4
  293. in_chans (int): Number of input image channels. Default: 3
  294. num_classes (int): Number of classes for classification head. Default: 1000
  295. embed_dim (int): Patch embedding dimension. Default: 96
  296. depths (tuple(int)): Depth of each Swin MLP layer.
  297. num_heads (tuple(int)): Number of attention heads in different layers.
  298. window_size (int): Window size. Default: 7
  299. mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4
  300. drop_rate (float): Dropout rate. Default: 0
  301. drop_path_rate (float): Stochastic depth rate. Default: 0.1
  302. norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm.
  303. ape (bool): If True, add absolute position embedding to the patch embedding. Default: False
  304. patch_norm (bool): If True, add normalization after patch embedding. Default: True
  305. use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False
  306. """
  307. def __init__(self, img_size=224, patch_size=4, in_chans=3, num_classes=1000,
  308. embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24],
  309. window_size=7, mlp_ratio=4., drop_rate=0., drop_path_rate=0.1,
  310. norm_layer=nn.LayerNorm, ape=False, patch_norm=True,
  311. use_checkpoint=False, **kwargs):
  312. super().__init__()
  313. self.num_classes = num_classes
  314. self.num_layers = len(depths)
  315. self.embed_dim = embed_dim
  316. self.ape = ape
  317. self.patch_norm = patch_norm
  318. self.num_features = int(embed_dim * 2 ** (self.num_layers - 1))
  319. self.mlp_ratio = mlp_ratio
  320. # split image into non-overlapping patches
  321. self.patch_embed = PatchEmbed(
  322. img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim,
  323. norm_layer=norm_layer if self.patch_norm else None)
  324. num_patches = self.patch_embed.num_patches
  325. patches_resolution = self.patch_embed.patches_resolution
  326. self.patches_resolution = patches_resolution
  327. # absolute position embedding
  328. if self.ape:
  329. self.absolute_pos_embed = nn.Parameter(torch.zeros(1, num_patches, embed_dim))
  330. trunc_normal_(self.absolute_pos_embed, std=.02)
  331. self.pos_drop = nn.Dropout(p=drop_rate)
  332. # stochastic depth
  333. dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule
  334. # build layers
  335. self.layers = nn.ModuleList()
  336. for i_layer in range(self.num_layers):
  337. layer = BasicLayer(dim=int(embed_dim * 2 ** i_layer),
  338. input_resolution=(patches_resolution[0] // (2 ** i_layer),
  339. patches_resolution[1] // (2 ** i_layer)),
  340. depth=depths[i_layer],
  341. num_heads=num_heads[i_layer],
  342. window_size=window_size,
  343. mlp_ratio=self.mlp_ratio,
  344. drop=drop_rate,
  345. drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])],
  346. norm_layer=norm_layer,
  347. downsample=PatchMerging if (i_layer < self.num_layers - 1) else None,
  348. use_checkpoint=use_checkpoint)
  349. self.layers.append(layer)
  350. self.norm = norm_layer(self.num_features)
  351. self.avgpool = nn.AdaptiveAvgPool1d(1)
  352. self.head = nn.Linear(self.num_features, num_classes) if num_classes > 0 else nn.Identity()
  353. self.apply(self._init_weights)
  354. def _init_weights(self, m):
  355. if isinstance(m, (nn.Linear, nn.Conv1d)):
  356. trunc_normal_(m.weight, std=.02)
  357. if m.bias is not None:
  358. nn.init.constant_(m.bias, 0)
  359. elif isinstance(m, nn.LayerNorm):
  360. nn.init.constant_(m.bias, 0)
  361. nn.init.constant_(m.weight, 1.0)
  362. @torch.jit.ignore
  363. def no_weight_decay(self):
  364. return {'absolute_pos_embed'}
  365. @torch.jit.ignore
  366. def no_weight_decay_keywords(self):
  367. return {'relative_position_bias_table'}
  368. def forward_features(self, x):
  369. x = self.patch_embed(x)
  370. if self.ape:
  371. x = x + self.absolute_pos_embed
  372. x = self.pos_drop(x)
  373. for layer in self.layers:
  374. x = layer(x)
  375. x = self.norm(x) # B L C
  376. x = self.avgpool(x.transpose(1, 2)) # B C 1
  377. x = torch.flatten(x, 1)
  378. return x
  379. def forward(self, x):
  380. x = self.forward_features(x)
  381. x = self.head(x)
  382. return x
  383. def flops(self):
  384. flops = 0
  385. flops += self.patch_embed.flops()
  386. for i, layer in enumerate(self.layers):
  387. flops += layer.flops()
  388. flops += self.num_features * self.patches_resolution[0] * self.patches_resolution[1] // (2 ** self.num_layers)
  389. flops += self.num_features * self.num_classes
  390. return flops