Transformer.py 25 KB

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