vit.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. '''
  2. * Copyright (c) 2022, salesforce.com, inc.
  3. * All rights reserved.
  4. * SPDX-License-Identifier: BSD-3-Clause
  5. * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
  6. * By Junnan Li
  7. * Based on timm code base
  8. * https://github.com/rwightman/pytorch-image-models/tree/master/timm
  9. '''
  10. import torch
  11. import torch.nn as nn
  12. import torch.nn.functional as F
  13. from functools import partial
  14. from timm.models.vision_transformer import _cfg, PatchEmbed
  15. from timm.models.registry import register_model
  16. from timm.models.layers import trunc_normal_, DropPath
  17. from timm.models.helpers import named_apply, adapt_input_conv
  18. from fairscale.nn.checkpoint.checkpoint_activations import checkpoint_wrapper
  19. class Mlp(nn.Module):
  20. """ MLP as used in Vision Transformer, MLP-Mixer and related networks
  21. """
  22. def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
  23. super().__init__()
  24. out_features = out_features or in_features
  25. hidden_features = hidden_features or in_features
  26. self.fc1 = nn.Linear(in_features, hidden_features)
  27. self.act = act_layer()
  28. self.fc2 = nn.Linear(hidden_features, out_features)
  29. self.drop = nn.Dropout(drop)
  30. def forward(self, x):
  31. x = self.fc1(x)
  32. x = self.act(x)
  33. x = self.drop(x)
  34. x = self.fc2(x)
  35. x = self.drop(x)
  36. return x
  37. class Attention(nn.Module):
  38. def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.):
  39. super().__init__()
  40. self.num_heads = num_heads
  41. head_dim = dim // num_heads
  42. # NOTE scale factor was wrong in my original version, can set manually to be compat with prev weights
  43. self.scale = qk_scale or head_dim ** -0.5
  44. self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
  45. self.attn_drop = nn.Dropout(attn_drop)
  46. self.proj = nn.Linear(dim, dim)
  47. self.proj_drop = nn.Dropout(proj_drop)
  48. self.attn_gradients = None
  49. self.attention_map = None
  50. def save_attn_gradients(self, attn_gradients):
  51. self.attn_gradients = attn_gradients
  52. def get_attn_gradients(self):
  53. return self.attn_gradients
  54. def save_attention_map(self, attention_map):
  55. self.attention_map = attention_map
  56. def get_attention_map(self):
  57. return self.attention_map
  58. def forward(self, x, register_hook=False):
  59. B, N, C = x.shape
  60. qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
  61. q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
  62. attn = (q @ k.transpose(-2, -1)) * self.scale
  63. attn = attn.softmax(dim=-1)
  64. attn = self.attn_drop(attn)
  65. if register_hook:
  66. self.save_attention_map(attn)
  67. attn.register_hook(self.save_attn_gradients)
  68. x = (attn @ v).transpose(1, 2).reshape(B, N, C)
  69. x = self.proj(x)
  70. x = self.proj_drop(x)
  71. return x
  72. class Block(nn.Module):
  73. def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
  74. drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, use_grad_checkpointing=False):
  75. super().__init__()
  76. self.norm1 = norm_layer(dim)
  77. self.attn = Attention(
  78. dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
  79. # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
  80. self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
  81. self.norm2 = norm_layer(dim)
  82. mlp_hidden_dim = int(dim * mlp_ratio)
  83. self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
  84. if use_grad_checkpointing:
  85. self.attn = checkpoint_wrapper(self.attn)
  86. self.mlp = checkpoint_wrapper(self.mlp)
  87. def forward(self, x, register_hook=False):
  88. x = x + self.drop_path(self.attn(self.norm1(x), register_hook=register_hook))
  89. x = x + self.drop_path(self.mlp(self.norm2(x)))
  90. return x
  91. class VisionTransformer(nn.Module):
  92. """ Vision Transformer
  93. A PyTorch impl of : `An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale` -
  94. https://arxiv.org/abs/2010.11929
  95. """
  96. def __init__(self, img_size=224, patch_size=16, in_chans=3, num_classes=1000, embed_dim=768, depth=12,
  97. num_heads=12, mlp_ratio=4., qkv_bias=True, qk_scale=None, representation_size=None,
  98. drop_rate=0., attn_drop_rate=0., drop_path_rate=0., norm_layer=None,
  99. use_grad_checkpointing=False, ckpt_layer=0):
  100. """
  101. Args:
  102. img_size (int, tuple): input image size
  103. patch_size (int, tuple): patch size
  104. in_chans (int): number of input channels
  105. num_classes (int): number of classes for classification head
  106. embed_dim (int): embedding dimension
  107. depth (int): depth of transformer
  108. num_heads (int): number of attention heads
  109. mlp_ratio (int): ratio of mlp hidden dim to embedding dim
  110. qkv_bias (bool): enable bias for qkv if True
  111. qk_scale (float): override default qk scale of head_dim ** -0.5 if set
  112. representation_size (Optional[int]): enable and set representation layer (pre-logits) to this value if set
  113. drop_rate (float): dropout rate
  114. attn_drop_rate (float): attention dropout rate
  115. drop_path_rate (float): stochastic depth rate
  116. norm_layer: (nn.Module): normalization layer
  117. """
  118. super().__init__()
  119. self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
  120. norm_layer = norm_layer or partial(nn.LayerNorm, eps=1e-6)
  121. self.patch_embed = PatchEmbed(
  122. img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim)
  123. num_patches = self.patch_embed.num_patches
  124. self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
  125. self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim))
  126. self.pos_drop = nn.Dropout(p=drop_rate)
  127. dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
  128. self.blocks = nn.ModuleList([
  129. Block(
  130. dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,
  131. drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer,
  132. use_grad_checkpointing=(use_grad_checkpointing and i>=depth-ckpt_layer)
  133. )
  134. for i in range(depth)])
  135. self.norm = norm_layer(embed_dim)
  136. trunc_normal_(self.pos_embed, std=.02)
  137. trunc_normal_(self.cls_token, std=.02)
  138. self.apply(self._init_weights)
  139. def _init_weights(self, m):
  140. if isinstance(m, nn.Linear):
  141. trunc_normal_(m.weight, std=.02)
  142. if isinstance(m, nn.Linear) and m.bias is not None:
  143. nn.init.constant_(m.bias, 0)
  144. elif isinstance(m, nn.LayerNorm):
  145. nn.init.constant_(m.bias, 0)
  146. nn.init.constant_(m.weight, 1.0)
  147. @torch.jit.ignore
  148. def no_weight_decay(self):
  149. return {'pos_embed', 'cls_token'}
  150. def forward(self, x, register_blk=-1):
  151. B = x.shape[0]
  152. x = self.patch_embed(x)
  153. cls_tokens = self.cls_token.expand(B, -1, -1) # stole cls_tokens impl from Phil Wang, thanks
  154. x = torch.cat((cls_tokens, x), dim=1)
  155. x = x + self.pos_embed[:,:x.size(1),:]
  156. x = self.pos_drop(x)
  157. for i,blk in enumerate(self.blocks):
  158. x = blk(x, register_blk==i)
  159. x = self.norm(x)
  160. return x
  161. @torch.jit.ignore()
  162. def load_pretrained(self, checkpoint_path, prefix=''):
  163. _load_weights(self, checkpoint_path, prefix)
  164. @torch.no_grad()
  165. def _load_weights(model: VisionTransformer, checkpoint_path: str, prefix: str = ''):
  166. """ Load weights from .npz checkpoints for official Google Brain Flax implementation
  167. """
  168. import numpy as np
  169. def _n2p(w, t=True):
  170. if w.ndim == 4 and w.shape[0] == w.shape[1] == w.shape[2] == 1:
  171. w = w.flatten()
  172. if t:
  173. if w.ndim == 4:
  174. w = w.transpose([3, 2, 0, 1])
  175. elif w.ndim == 3:
  176. w = w.transpose([2, 0, 1])
  177. elif w.ndim == 2:
  178. w = w.transpose([1, 0])
  179. return torch.from_numpy(w)
  180. w = np.load(checkpoint_path)
  181. if not prefix and 'opt/target/embedding/kernel' in w:
  182. prefix = 'opt/target/'
  183. if hasattr(model.patch_embed, 'backbone'):
  184. # hybrid
  185. backbone = model.patch_embed.backbone
  186. stem_only = not hasattr(backbone, 'stem')
  187. stem = backbone if stem_only else backbone.stem
  188. stem.conv.weight.copy_(adapt_input_conv(stem.conv.weight.shape[1], _n2p(w[f'{prefix}conv_root/kernel'])))
  189. stem.norm.weight.copy_(_n2p(w[f'{prefix}gn_root/scale']))
  190. stem.norm.bias.copy_(_n2p(w[f'{prefix}gn_root/bias']))
  191. if not stem_only:
  192. for i, stage in enumerate(backbone.stages):
  193. for j, block in enumerate(stage.blocks):
  194. bp = f'{prefix}block{i + 1}/unit{j + 1}/'
  195. for r in range(3):
  196. getattr(block, f'conv{r + 1}').weight.copy_(_n2p(w[f'{bp}conv{r + 1}/kernel']))
  197. getattr(block, f'norm{r + 1}').weight.copy_(_n2p(w[f'{bp}gn{r + 1}/scale']))
  198. getattr(block, f'norm{r + 1}').bias.copy_(_n2p(w[f'{bp}gn{r + 1}/bias']))
  199. if block.downsample is not None:
  200. block.downsample.conv.weight.copy_(_n2p(w[f'{bp}conv_proj/kernel']))
  201. block.downsample.norm.weight.copy_(_n2p(w[f'{bp}gn_proj/scale']))
  202. block.downsample.norm.bias.copy_(_n2p(w[f'{bp}gn_proj/bias']))
  203. embed_conv_w = _n2p(w[f'{prefix}embedding/kernel'])
  204. else:
  205. embed_conv_w = adapt_input_conv(
  206. model.patch_embed.proj.weight.shape[1], _n2p(w[f'{prefix}embedding/kernel']))
  207. model.patch_embed.proj.weight.copy_(embed_conv_w)
  208. model.patch_embed.proj.bias.copy_(_n2p(w[f'{prefix}embedding/bias']))
  209. model.cls_token.copy_(_n2p(w[f'{prefix}cls'], t=False))
  210. pos_embed_w = _n2p(w[f'{prefix}Transformer/posembed_input/pos_embedding'], t=False)
  211. if pos_embed_w.shape != model.pos_embed.shape:
  212. pos_embed_w = resize_pos_embed( # resize pos embedding when different size from pretrained weights
  213. pos_embed_w, model.pos_embed, getattr(model, 'num_tokens', 1), model.patch_embed.grid_size)
  214. model.pos_embed.copy_(pos_embed_w)
  215. model.norm.weight.copy_(_n2p(w[f'{prefix}Transformer/encoder_norm/scale']))
  216. model.norm.bias.copy_(_n2p(w[f'{prefix}Transformer/encoder_norm/bias']))
  217. # if isinstance(model.head, nn.Linear) and model.head.bias.shape[0] == w[f'{prefix}head/bias'].shape[-1]:
  218. # model.head.weight.copy_(_n2p(w[f'{prefix}head/kernel']))
  219. # model.head.bias.copy_(_n2p(w[f'{prefix}head/bias']))
  220. # if isinstance(getattr(model.pre_logits, 'fc', None), nn.Linear) and f'{prefix}pre_logits/bias' in w:
  221. # model.pre_logits.fc.weight.copy_(_n2p(w[f'{prefix}pre_logits/kernel']))
  222. # model.pre_logits.fc.bias.copy_(_n2p(w[f'{prefix}pre_logits/bias']))
  223. for i, block in enumerate(model.blocks.children()):
  224. block_prefix = f'{prefix}Transformer/encoderblock_{i}/'
  225. mha_prefix = block_prefix + 'MultiHeadDotProductAttention_1/'
  226. block.norm1.weight.copy_(_n2p(w[f'{block_prefix}LayerNorm_0/scale']))
  227. block.norm1.bias.copy_(_n2p(w[f'{block_prefix}LayerNorm_0/bias']))
  228. block.attn.qkv.weight.copy_(torch.cat([
  229. _n2p(w[f'{mha_prefix}{n}/kernel'], t=False).flatten(1).T for n in ('query', 'key', 'value')]))
  230. block.attn.qkv.bias.copy_(torch.cat([
  231. _n2p(w[f'{mha_prefix}{n}/bias'], t=False).reshape(-1) for n in ('query', 'key', 'value')]))
  232. block.attn.proj.weight.copy_(_n2p(w[f'{mha_prefix}out/kernel']).flatten(1))
  233. block.attn.proj.bias.copy_(_n2p(w[f'{mha_prefix}out/bias']))
  234. for r in range(2):
  235. getattr(block.mlp, f'fc{r + 1}').weight.copy_(_n2p(w[f'{block_prefix}MlpBlock_3/Dense_{r}/kernel']))
  236. getattr(block.mlp, f'fc{r + 1}').bias.copy_(_n2p(w[f'{block_prefix}MlpBlock_3/Dense_{r}/bias']))
  237. block.norm2.weight.copy_(_n2p(w[f'{block_prefix}LayerNorm_2/scale']))
  238. block.norm2.bias.copy_(_n2p(w[f'{block_prefix}LayerNorm_2/bias']))
  239. def interpolate_pos_embed(pos_embed_checkpoint, visual_encoder):
  240. # interpolate position embedding
  241. embedding_size = pos_embed_checkpoint.shape[-1]
  242. num_patches = visual_encoder.patch_embed.num_patches
  243. num_extra_tokens = visual_encoder.pos_embed.shape[-2] - num_patches
  244. # height (== width) for the checkpoint position embedding
  245. orig_size = int((pos_embed_checkpoint.shape[-2] - num_extra_tokens) ** 0.5)
  246. # height (== width) for the new position embedding
  247. new_size = int(num_patches ** 0.5)
  248. if orig_size!=new_size:
  249. # class_token and dist_token are kept unchanged
  250. extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens]
  251. # only the position tokens are interpolated
  252. pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:]
  253. pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, embedding_size).permute(0, 3, 1, 2)
  254. pos_tokens = torch.nn.functional.interpolate(
  255. pos_tokens, size=(new_size, new_size), mode='bicubic', align_corners=False)
  256. pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(1, 2)
  257. new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1)
  258. print('reshape position embedding from %d to %d'%(orig_size ** 2,new_size ** 2))
  259. return new_pos_embed
  260. else:
  261. return pos_embed_checkpoint