Vidit2003 commited on
Commit
60de7d8
·
verified ·
1 Parent(s): eb06e0c

Create vision_transformer.py

Browse files
Files changed (1) hide show
  1. vision_transformer.py +285 -0
vision_transformer.py ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """
15
+ Mostly copy-paste from timm library.
16
+ https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
17
+ """
18
+ import math
19
+ from functools import partial
20
+
21
+ import torch
22
+ import torch.nn as nn
23
+
24
+ from utils import trunc_normal_
25
+
26
+
27
+ def drop_path(x, drop_prob: float = 0., training: bool = False):
28
+ if drop_prob == 0. or not training:
29
+ return x
30
+ keep_prob = 1 - drop_prob
31
+ shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
32
+ random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device)
33
+ random_tensor.floor_() # binarize
34
+ output = x.div(keep_prob) * random_tensor
35
+ return output
36
+
37
+
38
+ class DropPath(nn.Module):
39
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
40
+ """
41
+ def __init__(self, drop_prob=None):
42
+ super(DropPath, self).__init__()
43
+ self.drop_prob = drop_prob
44
+
45
+ def forward(self, x):
46
+ return drop_path(x, self.drop_prob, self.training)
47
+
48
+
49
+ class Mlp(nn.Module):
50
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
51
+ super().__init__()
52
+ out_features = out_features or in_features
53
+ hidden_features = hidden_features or in_features
54
+ self.fc1 = nn.Linear(in_features, hidden_features)
55
+ self.act = act_layer()
56
+ self.fc2 = nn.Linear(hidden_features, out_features)
57
+ self.drop = nn.Dropout(drop)
58
+
59
+ def forward(self, x):
60
+ x = self.fc1(x)
61
+ x = self.act(x)
62
+ x = self.drop(x)
63
+ x = self.fc2(x)
64
+ x = self.drop(x)
65
+ return x
66
+
67
+
68
+ class Attention(nn.Module):
69
+ def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.):
70
+ super().__init__()
71
+ self.num_heads = num_heads
72
+ head_dim = dim // num_heads
73
+ self.scale = qk_scale or head_dim ** -0.5
74
+
75
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
76
+ self.attn_drop = nn.Dropout(attn_drop)
77
+ self.proj = nn.Linear(dim, dim)
78
+ self.proj_drop = nn.Dropout(proj_drop)
79
+
80
+ def forward(self, x):
81
+ B, N, C = x.shape
82
+ qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
83
+ q, k, v = qkv[0], qkv[1], qkv[2]
84
+
85
+ attn = (q @ k.transpose(-2, -1)) * self.scale
86
+ attn = attn.softmax(dim=-1)
87
+ attn = self.attn_drop(attn)
88
+
89
+ x = (attn @ v).transpose(1, 2).reshape(B, N, C)
90
+ x = self.proj(x)
91
+ x = self.proj_drop(x)
92
+ return x, attn
93
+
94
+
95
+ class Block(nn.Module):
96
+ def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
97
+ drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm):
98
+ super().__init__()
99
+ self.norm1 = norm_layer(dim)
100
+ self.attn = Attention(
101
+ dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
102
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
103
+ self.norm2 = norm_layer(dim)
104
+ mlp_hidden_dim = int(dim * mlp_ratio)
105
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
106
+
107
+ def forward(self, x, return_attention=False):
108
+ y, attn = self.attn(self.norm1(x))
109
+ if return_attention:
110
+ return attn
111
+ x = x + self.drop_path(y)
112
+ x = x + self.drop_path(self.mlp(self.norm2(x)))
113
+ return x
114
+
115
+
116
+ class PatchEmbed(nn.Module):
117
+ """ Image to Patch Embedding
118
+ """
119
+ def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768):
120
+ super().__init__()
121
+ num_patches = (img_size // patch_size) * (img_size // patch_size)
122
+ self.img_size = img_size
123
+ self.patch_size = patch_size
124
+ self.num_patches = num_patches
125
+
126
+ self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
127
+
128
+ def forward(self, x):
129
+ B, C, H, W = x.shape
130
+ x = self.proj(x).flatten(2).transpose(1, 2)
131
+ return x
132
+
133
+
134
+ class VisionTransformer(nn.Module):
135
+ """ Vision Transformer """
136
+ def __init__(self, img_size=[224], patch_size=16, in_chans=3, num_classes=0, embed_dim=768, depth=12,
137
+ num_heads=12, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop_rate=0., attn_drop_rate=0.,
138
+ drop_path_rate=0., norm_layer=nn.LayerNorm, **kwargs):
139
+ super().__init__()
140
+ self.num_features = self.embed_dim = embed_dim
141
+
142
+ self.patch_embed = PatchEmbed(
143
+ img_size=img_size[0], patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim)
144
+ num_patches = self.patch_embed.num_patches
145
+
146
+ self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
147
+ self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim))
148
+ self.pos_drop = nn.Dropout(p=drop_rate)
149
+
150
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
151
+ self.blocks = nn.ModuleList([
152
+ Block(
153
+ dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,
154
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer)
155
+ for i in range(depth)])
156
+ self.norm = norm_layer(embed_dim)
157
+
158
+ # Classifier head
159
+ self.head = nn.Linear(embed_dim, num_classes) if num_classes > 0 else nn.Identity()
160
+
161
+ trunc_normal_(self.pos_embed, std=.02)
162
+ trunc_normal_(self.cls_token, std=.02)
163
+ self.apply(self._init_weights)
164
+
165
+ def _init_weights(self, m):
166
+ if isinstance(m, nn.Linear):
167
+ trunc_normal_(m.weight, std=.02)
168
+ if isinstance(m, nn.Linear) and m.bias is not None:
169
+ nn.init.constant_(m.bias, 0)
170
+ elif isinstance(m, nn.LayerNorm):
171
+ nn.init.constant_(m.bias, 0)
172
+ nn.init.constant_(m.weight, 1.0)
173
+
174
+ def interpolate_pos_encoding(self, x, w, h):
175
+ npatch = x.shape[1] - 1
176
+ N = self.pos_embed.shape[1] - 1
177
+ if npatch == N and w == h:
178
+ return self.pos_embed
179
+ class_pos_embed = self.pos_embed[:, 0]
180
+ patch_pos_embed = self.pos_embed[:, 1:]
181
+ dim = x.shape[-1]
182
+ w0 = w // self.patch_embed.patch_size
183
+ h0 = h // self.patch_embed.patch_size
184
+ # we add a small number to avoid floating point error in the interpolation
185
+ # see discussion at https://github.com/facebookresearch/dino/issues/8
186
+ w0, h0 = w0 + 0.1, h0 + 0.1
187
+ patch_pos_embed = nn.functional.interpolate(
188
+ patch_pos_embed.reshape(1, int(math.sqrt(N)), int(math.sqrt(N)), dim).permute(0, 3, 1, 2),
189
+ scale_factor=(w0 / math.sqrt(N), h0 / math.sqrt(N)),
190
+ mode='bicubic',
191
+ )
192
+ assert int(w0) == patch_pos_embed.shape[-2] and int(h0) == patch_pos_embed.shape[-1]
193
+ patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
194
+ return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1)
195
+
196
+ def prepare_tokens(self, x):
197
+ B, nc, w, h = x.shape
198
+ x = self.patch_embed(x) # patch linear embedding
199
+
200
+ # add the [CLS] token to the embed patch tokens
201
+ cls_tokens = self.cls_token.expand(B, -1, -1)
202
+ x = torch.cat((cls_tokens, x), dim=1)
203
+
204
+ # add positional encoding to each token
205
+ x = x + self.interpolate_pos_encoding(x, w, h)
206
+
207
+ return self.pos_drop(x)
208
+
209
+ def forward(self, x):
210
+ x = self.prepare_tokens(x)
211
+ for blk in self.blocks:
212
+ x = blk(x)
213
+ x = self.norm(x)
214
+ return x[:, 0]
215
+
216
+ def get_last_selfattention(self, x):
217
+ x = self.prepare_tokens(x)
218
+ for i, blk in enumerate(self.blocks):
219
+ if i < len(self.blocks) - 1:
220
+ x = blk(x)
221
+ else:
222
+ # return attention of the last block
223
+ return blk(x, return_attention=True)
224
+
225
+ def get_intermediate_layers(self, x, n=1):
226
+ x = self.prepare_tokens(x)
227
+ # we return the output tokens from the `n` last blocks
228
+ output = []
229
+ for i, blk in enumerate(self.blocks):
230
+ x = blk(x)
231
+ if len(self.blocks) - i <= n:
232
+ output.append(self.norm(x))
233
+ return output
234
+
235
+
236
+
237
+ def vit_small(patch_size=16, **kwargs):
238
+ model = VisionTransformer(
239
+ patch_size=patch_size, embed_dim=384, depth=12, num_heads=6, mlp_ratio=4,
240
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)
241
+ return model
242
+
243
+
244
+ def vit_base(patch_size=16, **kwargs):
245
+ model = VisionTransformer(
246
+ patch_size=patch_size, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4,
247
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)
248
+ return model
249
+
250
+
251
+ class DINOHead(nn.Module):
252
+ def __init__(self, in_dim, out_dim, use_bn=False, norm_last_layer=True, nlayers=3, hidden_dim=2048, bottleneck_dim=256):
253
+ super().__init__()
254
+ nlayers = max(nlayers, 1)
255
+ if nlayers == 1:
256
+ self.mlp = nn.Linear(in_dim, bottleneck_dim)
257
+ else:
258
+ layers = [nn.Linear(in_dim, hidden_dim)]
259
+ if use_bn:
260
+ layers.append(nn.BatchNorm1d(hidden_dim))
261
+ layers.append(nn.GELU())
262
+ for _ in range(nlayers - 2):
263
+ layers.append(nn.Linear(hidden_dim, hidden_dim))
264
+ if use_bn:
265
+ layers.append(nn.BatchNorm1d(hidden_dim))
266
+ layers.append(nn.GELU())
267
+ layers.append(nn.Linear(hidden_dim, bottleneck_dim))
268
+ self.mlp = nn.Sequential(*layers)
269
+ self.apply(self._init_weights)
270
+ self.last_layer = nn.utils.weight_norm(nn.Linear(bottleneck_dim, out_dim, bias=False))
271
+ self.last_layer.weight_g.data.fill_(1)
272
+ if norm_last_layer:
273
+ self.last_layer.weight_g.requires_grad = False
274
+
275
+ def _init_weights(self, m):
276
+ if isinstance(m, nn.Linear):
277
+ trunc_normal_(m.weight, std=.02)
278
+ if isinstance(m, nn.Linear) and m.bias is not None:
279
+ nn.init.constant_(m.bias, 0)
280
+
281
+ def forward(self, x):
282
+ x = self.mlp(x)
283
+ x = nn.functional.normalize(x, dim=-1, p=2)
284
+ x = self.last_layer(x)
285
+ return x