pvt_v2.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. import math
  2. from functools import partial
  3. import torch
  4. import torch.nn as nn
  5. from timm.layers import DropPath, to_2tuple, trunc_normal_
  6. from config import Config
  7. config = Config()
  8. class Mlp(nn.Module):
  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.dwconv = DWConv(hidden_features)
  15. self.act = act_layer()
  16. self.fc2 = nn.Linear(hidden_features, out_features)
  17. self.drop = nn.Dropout(drop)
  18. self.apply(self._init_weights)
  19. def _init_weights(self, m):
  20. if isinstance(m, nn.Linear):
  21. trunc_normal_(m.weight, std=.02)
  22. if isinstance(m, nn.Linear) and m.bias is not None:
  23. nn.init.constant_(m.bias, 0)
  24. elif isinstance(m, nn.LayerNorm):
  25. nn.init.constant_(m.bias, 0)
  26. nn.init.constant_(m.weight, 1.0)
  27. elif isinstance(m, nn.Conv2d):
  28. fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
  29. fan_out //= m.groups
  30. m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
  31. if m.bias is not None:
  32. m.bias.data.zero_()
  33. def forward(self, x, H, W):
  34. x = self.fc1(x)
  35. x = self.dwconv(x, H, W)
  36. x = self.act(x)
  37. x = self.drop(x)
  38. x = self.fc2(x)
  39. x = self.drop(x)
  40. return x
  41. class Attention(nn.Module):
  42. def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., sr_ratio=1):
  43. super().__init__()
  44. assert dim % num_heads == 0, f"dim {dim} should be divided by num_heads {num_heads}."
  45. self.dim = dim
  46. self.num_heads = num_heads
  47. head_dim = dim // num_heads
  48. self.scale = qk_scale or head_dim ** -0.5
  49. self.q = nn.Linear(dim, dim, bias=qkv_bias)
  50. self.kv = nn.Linear(dim, dim * 2, bias=qkv_bias)
  51. self.attn_drop_prob = attn_drop
  52. self.attn_drop = nn.Dropout(attn_drop)
  53. self.proj = nn.Linear(dim, dim)
  54. self.proj_drop = nn.Dropout(proj_drop)
  55. self.sr_ratio = sr_ratio
  56. if sr_ratio > 1:
  57. self.sr = nn.Conv2d(dim, dim, kernel_size=sr_ratio, stride=sr_ratio)
  58. self.norm = nn.LayerNorm(dim)
  59. self.apply(self._init_weights)
  60. def _init_weights(self, m):
  61. if isinstance(m, nn.Linear):
  62. trunc_normal_(m.weight, std=.02)
  63. if isinstance(m, nn.Linear) and m.bias is not None:
  64. nn.init.constant_(m.bias, 0)
  65. elif isinstance(m, nn.LayerNorm):
  66. nn.init.constant_(m.bias, 0)
  67. nn.init.constant_(m.weight, 1.0)
  68. elif isinstance(m, nn.Conv2d):
  69. fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
  70. fan_out //= m.groups
  71. m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
  72. if m.bias is not None:
  73. m.bias.data.zero_()
  74. def forward(self, x, H, W):
  75. B, N, C = x.shape
  76. q = self.q(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
  77. if self.sr_ratio > 1:
  78. x_ = x.permute(0, 2, 1).reshape(B, C, H, W)
  79. x_ = self.sr(x_).reshape(B, C, -1).permute(0, 2, 1)
  80. x_ = self.norm(x_)
  81. kv = self.kv(x_).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
  82. else:
  83. kv = self.kv(x).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
  84. k, v = kv[0], kv[1]
  85. if config.SDPA_enabled:
  86. x = torch.nn.functional.scaled_dot_product_attention(
  87. q, k, v,
  88. attn_mask=None, dropout_p=self.attn_drop_prob, is_causal=False
  89. ).transpose(1, 2).reshape(B, N, C)
  90. else:
  91. attn = (q @ k.transpose(-2, -1)) * self.scale
  92. attn = attn.softmax(dim=-1)
  93. attn = self.attn_drop(attn)
  94. x = (attn @ v).transpose(1, 2).reshape(B, N, C)
  95. x = self.proj(x)
  96. x = self.proj_drop(x)
  97. return x
  98. class Block(nn.Module):
  99. def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
  100. drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, sr_ratio=1):
  101. super().__init__()
  102. self.norm1 = norm_layer(dim)
  103. self.attn = Attention(
  104. dim,
  105. num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale,
  106. attn_drop=attn_drop, proj_drop=drop, sr_ratio=sr_ratio)
  107. # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
  108. self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
  109. self.norm2 = norm_layer(dim)
  110. mlp_hidden_dim = int(dim * mlp_ratio)
  111. self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
  112. self.apply(self._init_weights)
  113. def _init_weights(self, m):
  114. if isinstance(m, nn.Linear):
  115. trunc_normal_(m.weight, std=.02)
  116. if isinstance(m, nn.Linear) and m.bias is not None:
  117. nn.init.constant_(m.bias, 0)
  118. elif isinstance(m, nn.LayerNorm):
  119. nn.init.constant_(m.bias, 0)
  120. nn.init.constant_(m.weight, 1.0)
  121. elif isinstance(m, nn.Conv2d):
  122. fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
  123. fan_out //= m.groups
  124. m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
  125. if m.bias is not None:
  126. m.bias.data.zero_()
  127. def forward(self, x, H, W):
  128. x = x + self.drop_path(self.attn(self.norm1(x), H, W))
  129. x = x + self.drop_path(self.mlp(self.norm2(x), H, W))
  130. return x
  131. class OverlapPatchEmbed(nn.Module):
  132. """ Image to Patch Embedding
  133. """
  134. def __init__(self, img_size=224, patch_size=7, stride=4, in_channels=3, embed_dim=768):
  135. super().__init__()
  136. img_size = to_2tuple(img_size)
  137. patch_size = to_2tuple(patch_size)
  138. self.img_size = img_size
  139. self.patch_size = patch_size
  140. self.H, self.W = img_size[0] // patch_size[0], img_size[1] // patch_size[1]
  141. self.num_patches = self.H * self.W
  142. self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=stride,
  143. padding=(patch_size[0] // 2, patch_size[1] // 2))
  144. self.norm = nn.LayerNorm(embed_dim)
  145. self.apply(self._init_weights)
  146. def _init_weights(self, m):
  147. if isinstance(m, nn.Linear):
  148. trunc_normal_(m.weight, std=.02)
  149. if isinstance(m, nn.Linear) and m.bias is not None:
  150. nn.init.constant_(m.bias, 0)
  151. elif isinstance(m, nn.LayerNorm):
  152. nn.init.constant_(m.bias, 0)
  153. nn.init.constant_(m.weight, 1.0)
  154. elif isinstance(m, nn.Conv2d):
  155. fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
  156. fan_out //= m.groups
  157. m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
  158. if m.bias is not None:
  159. m.bias.data.zero_()
  160. def forward(self, x):
  161. x = self.proj(x)
  162. _, _, H, W = x.shape
  163. x = x.flatten(2).transpose(1, 2)
  164. x = self.norm(x)
  165. return x, H, W
  166. class PyramidVisionTransformerImpr(nn.Module):
  167. def __init__(self, img_size=224, patch_size=16, in_channels=3, num_classes=1000, embed_dims=[64, 128, 256, 512],
  168. num_heads=[1, 2, 4, 8], mlp_ratios=[4, 4, 4, 4], qkv_bias=False, qk_scale=None, drop_rate=0.,
  169. attn_drop_rate=0., drop_path_rate=0., norm_layer=nn.LayerNorm,
  170. depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1]):
  171. super().__init__()
  172. self.num_classes = num_classes
  173. self.depths = depths
  174. # patch_embed
  175. self.patch_embed1 = OverlapPatchEmbed(img_size=img_size, patch_size=7, stride=4, in_channels=in_channels,
  176. embed_dim=embed_dims[0])
  177. self.patch_embed2 = OverlapPatchEmbed(img_size=img_size // 4, patch_size=3, stride=2, in_channels=embed_dims[0],
  178. embed_dim=embed_dims[1])
  179. self.patch_embed3 = OverlapPatchEmbed(img_size=img_size // 8, patch_size=3, stride=2, in_channels=embed_dims[1],
  180. embed_dim=embed_dims[2])
  181. self.patch_embed4 = OverlapPatchEmbed(img_size=img_size // 16, patch_size=3, stride=2, in_channels=embed_dims[2],
  182. embed_dim=embed_dims[3])
  183. # transformer encoder
  184. dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule
  185. cur = 0
  186. self.block1 = nn.ModuleList([Block(
  187. dim=embed_dims[0], num_heads=num_heads[0], mlp_ratio=mlp_ratios[0], qkv_bias=qkv_bias, qk_scale=qk_scale,
  188. drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
  189. sr_ratio=sr_ratios[0])
  190. for i in range(depths[0])])
  191. self.norm1 = norm_layer(embed_dims[0])
  192. cur += depths[0]
  193. self.block2 = nn.ModuleList([Block(
  194. dim=embed_dims[1], num_heads=num_heads[1], mlp_ratio=mlp_ratios[1], qkv_bias=qkv_bias, qk_scale=qk_scale,
  195. drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
  196. sr_ratio=sr_ratios[1])
  197. for i in range(depths[1])])
  198. self.norm2 = norm_layer(embed_dims[1])
  199. cur += depths[1]
  200. self.block3 = nn.ModuleList([Block(
  201. dim=embed_dims[2], num_heads=num_heads[2], mlp_ratio=mlp_ratios[2], qkv_bias=qkv_bias, qk_scale=qk_scale,
  202. drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
  203. sr_ratio=sr_ratios[2])
  204. for i in range(depths[2])])
  205. self.norm3 = norm_layer(embed_dims[2])
  206. cur += depths[2]
  207. self.block4 = nn.ModuleList([Block(
  208. dim=embed_dims[3], num_heads=num_heads[3], mlp_ratio=mlp_ratios[3], qkv_bias=qkv_bias, qk_scale=qk_scale,
  209. drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
  210. sr_ratio=sr_ratios[3])
  211. for i in range(depths[3])])
  212. self.norm4 = norm_layer(embed_dims[3])
  213. # classification head
  214. # self.head = nn.Linear(embed_dims[3], num_classes) if num_classes > 0 else nn.Identity()
  215. self.apply(self._init_weights)
  216. def _init_weights(self, m):
  217. if isinstance(m, nn.Linear):
  218. trunc_normal_(m.weight, std=.02)
  219. if isinstance(m, nn.Linear) and m.bias is not None:
  220. nn.init.constant_(m.bias, 0)
  221. elif isinstance(m, nn.LayerNorm):
  222. nn.init.constant_(m.bias, 0)
  223. nn.init.constant_(m.weight, 1.0)
  224. elif isinstance(m, nn.Conv2d):
  225. fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
  226. fan_out //= m.groups
  227. m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
  228. if m.bias is not None:
  229. m.bias.data.zero_()
  230. def init_weights(self, pretrained=None):
  231. if isinstance(pretrained, str):
  232. logger = 1
  233. #load_checkpoint(self, pretrained, map_location='cpu', strict=False, logger=logger)
  234. def reset_drop_path(self, drop_path_rate):
  235. dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(self.depths))]
  236. cur = 0
  237. for i in range(self.depths[0]):
  238. self.block1[i].drop_path.drop_prob = dpr[cur + i]
  239. cur += self.depths[0]
  240. for i in range(self.depths[1]):
  241. self.block2[i].drop_path.drop_prob = dpr[cur + i]
  242. cur += self.depths[1]
  243. for i in range(self.depths[2]):
  244. self.block3[i].drop_path.drop_prob = dpr[cur + i]
  245. cur += self.depths[2]
  246. for i in range(self.depths[3]):
  247. self.block4[i].drop_path.drop_prob = dpr[cur + i]
  248. def freeze_patch_emb(self):
  249. self.patch_embed1.requires_grad = False
  250. @torch.jit.ignore
  251. def no_weight_decay(self):
  252. return {'pos_embed1', 'pos_embed2', 'pos_embed3', 'pos_embed4', 'cls_token'} # has pos_embed may be better
  253. def get_classifier(self):
  254. return self.head
  255. def reset_classifier(self, num_classes, global_pool=''):
  256. self.num_classes = num_classes
  257. self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity()
  258. def forward_features(self, x):
  259. B = x.shape[0]
  260. outs = []
  261. # stage 1
  262. x, H, W = self.patch_embed1(x)
  263. for i, blk in enumerate(self.block1):
  264. x = blk(x, H, W)
  265. x = self.norm1(x)
  266. x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
  267. outs.append(x)
  268. # stage 2
  269. x, H, W = self.patch_embed2(x)
  270. for i, blk in enumerate(self.block2):
  271. x = blk(x, H, W)
  272. x = self.norm2(x)
  273. x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
  274. outs.append(x)
  275. # stage 3
  276. x, H, W = self.patch_embed3(x)
  277. for i, blk in enumerate(self.block3):
  278. x = blk(x, H, W)
  279. x = self.norm3(x)
  280. x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
  281. outs.append(x)
  282. # stage 4
  283. x, H, W = self.patch_embed4(x)
  284. for i, blk in enumerate(self.block4):
  285. x = blk(x, H, W)
  286. x = self.norm4(x)
  287. x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
  288. outs.append(x)
  289. return outs
  290. # return x.mean(dim=1)
  291. def forward(self, x):
  292. x = self.forward_features(x)
  293. # x = self.head(x)
  294. return x
  295. class DWConv(nn.Module):
  296. def __init__(self, dim=768):
  297. super(DWConv, self).__init__()
  298. self.dwconv = nn.Conv2d(dim, dim, 3, 1, 1, bias=True, groups=dim)
  299. def forward(self, x, H, W):
  300. B, N, C = x.shape
  301. x = x.transpose(1, 2).view(B, C, H, W).contiguous()
  302. x = self.dwconv(x)
  303. x = x.flatten(2).transpose(1, 2)
  304. return x
  305. def _conv_filter(state_dict, patch_size=16):
  306. """ convert patch embedding weight from manual patchify + linear proj to conv"""
  307. out_dict = {}
  308. for k, v in state_dict.items():
  309. if 'patch_embed.proj.weight' in k:
  310. v = v.reshape((v.shape[0], 3, patch_size, patch_size))
  311. out_dict[k] = v
  312. return out_dict
  313. class pvt_v2_b0(PyramidVisionTransformerImpr):
  314. def __init__(self, **kwargs):
  315. super(pvt_v2_b0, self).__init__(
  316. patch_size=4, embed_dims=[32, 64, 160, 256], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
  317. qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1],
  318. drop_rate=0.0, drop_path_rate=0.1)
  319. class pvt_v2_b1(PyramidVisionTransformerImpr):
  320. def __init__(self, **kwargs):
  321. super(pvt_v2_b1, self).__init__(
  322. patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
  323. qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1],
  324. drop_rate=0.0, drop_path_rate=0.1)
  325. class pvt_v2_b2(PyramidVisionTransformerImpr):
  326. def __init__(self, in_channels=3, **kwargs):
  327. super(pvt_v2_b2, self).__init__(
  328. patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
  329. qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1],
  330. drop_rate=0.0, drop_path_rate=0.1, in_channels=in_channels)
  331. class pvt_v2_b3(PyramidVisionTransformerImpr):
  332. def __init__(self, **kwargs):
  333. super(pvt_v2_b3, self).__init__(
  334. patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
  335. qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 4, 18, 3], sr_ratios=[8, 4, 2, 1],
  336. drop_rate=0.0, drop_path_rate=0.1)
  337. class pvt_v2_b4(PyramidVisionTransformerImpr):
  338. def __init__(self, **kwargs):
  339. super(pvt_v2_b4, self).__init__(
  340. patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
  341. qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 8, 27, 3], sr_ratios=[8, 4, 2, 1],
  342. drop_rate=0.0, drop_path_rate=0.1)
  343. class pvt_v2_b5(PyramidVisionTransformerImpr):
  344. def __init__(self, **kwargs):
  345. super(pvt_v2_b5, self).__init__(
  346. patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4],
  347. qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 6, 40, 3], sr_ratios=[8, 4, 2, 1],
  348. drop_rate=0.0, drop_path_rate=0.1)