SunderAli17 commited on
Commit
23ebba4
1 Parent(s): 5148630

Create eva_vit_model.py

Browse files
Files changed (1) hide show
  1. eva_clip/eva_vit_model.py +630 -0
eva_clip/eva_vit_model.py ADDED
@@ -0,0 +1,630 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # Adapted from https://github.com/microsoft/unilm/tree/master/beit
3
+ # --------------------------------------------------------
4
+ import math
5
+ import os
6
+ from functools import partial
7
+ from itertools import repeat
8
+ import collections.abc
9
+ import torch
10
+ import torch.nn as nn
11
+ import warnings
12
+ import torch.nn.functional as F
13
+
14
+ from .transformer import PatchDropout
15
+ from .rope import VisionRotaryEmbedding, VisionRotaryEmbeddingFast
16
+
17
+ if os.getenv('ENV_TYPE') == 'deepspeed':
18
+ try:
19
+ from deepspeed.runtime.activation_checkpointing.checkpointing import checkpoint
20
+ except:
21
+ from torch.utils.checkpoint import checkpoint
22
+ else:
23
+ from torch.utils.checkpoint import checkpoint
24
+
25
+ try:
26
+ import xformers
27
+ import xformers.ops as xops
28
+ XFORMERS_IS_AVAILBLE = True
29
+ except:
30
+ XFORMERS_IS_AVAILBLE = False
31
+
32
+
33
+ def _ntuple(n):
34
+ def parse(x):
35
+ if isinstance(x, collections.abc.Iterable):
36
+ return x
37
+ return tuple(repeat(x, n))
38
+ return parse
39
+
40
+ to_2tuple = _ntuple(2)
41
+
42
+ def _no_grad_trunc_normal_(tensor, mean, std, a, b):
43
+ # Cut & paste from PyTorch official master until it's in a few official releases - RW
44
+ # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf
45
+ def norm_cdf(x):
46
+ # Computes standard normal cumulative distribution function
47
+ return (1. + math.erf(x / math.sqrt(2.))) / 2.
48
+
49
+ if (mean < a - 2 * std) or (mean > b + 2 * std):
50
+ warnings.warn("mean is more than 2 std from [a, b] in nn.init.trunc_normal_. "
51
+ "The distribution of values may be incorrect.",
52
+ stacklevel=2)
53
+
54
+ with torch.no_grad():
55
+ # Values are generated by using a truncated uniform distribution and
56
+ # then using the inverse CDF for the normal distribution.
57
+ # Get upper and lower cdf values
58
+ l = norm_cdf((a - mean) / std)
59
+ u = norm_cdf((b - mean) / std)
60
+
61
+ # Uniformly fill tensor with values from [l, u], then translate to
62
+ # [2l-1, 2u-1].
63
+ tensor.uniform_(2 * l - 1, 2 * u - 1)
64
+
65
+ # Use inverse cdf transform for normal distribution to get truncated
66
+ # standard normal
67
+ tensor.erfinv_()
68
+
69
+ # Transform to proper mean, std
70
+ tensor.mul_(std * math.sqrt(2.))
71
+ tensor.add_(mean)
72
+
73
+ # Clamp to ensure it's in the proper range
74
+ tensor.clamp_(min=a, max=b)
75
+ return tensor
76
+
77
+
78
+ def trunc_normal_(tensor, mean=0., std=1., a=-2., b=2.):
79
+ # type: (Tensor, float, float, float, float) -> Tensor
80
+ r"""Fills the input Tensor with values drawn from a truncated
81
+ normal distribution. The values are effectively drawn from the
82
+ normal distribution :math:`\mathcal{N}(\text{mean}, \text{std}^2)`
83
+ with values outside :math:`[a, b]` redrawn until they are within
84
+ the bounds. The method used for generating the random values works
85
+ best when :math:`a \leq \text{mean} \leq b`.
86
+ Args:
87
+ tensor: an n-dimensional `torch.Tensor`
88
+ mean: the mean of the normal distribution
89
+ std: the standard deviation of the normal distribution
90
+ a: the minimum cutoff value
91
+ b: the maximum cutoff value
92
+ Examples:
93
+ >>> w = torch.empty(3, 5)
94
+ >>> nn.init.trunc_normal_(w)
95
+ """
96
+ return _no_grad_trunc_normal_(tensor, mean, std, a, b)
97
+
98
+ def drop_path(x, drop_prob: float = 0., training: bool = False, scale_by_keep: bool = True):
99
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
100
+ This is the same as the DropConnect impl I created for EfficientNet, etc networks, however,
101
+ the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
102
+ See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for
103
+ changing the layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use
104
+ 'survival rate' as the argument.
105
+ """
106
+ if drop_prob == 0. or not training:
107
+ return x
108
+ keep_prob = 1 - drop_prob
109
+ shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
110
+ random_tensor = x.new_empty(shape).bernoulli_(keep_prob)
111
+ if keep_prob > 0.0 and scale_by_keep:
112
+ random_tensor.div_(keep_prob)
113
+ return x * random_tensor
114
+
115
+
116
+ class DropPath(nn.Module):
117
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
118
+ """
119
+ def __init__(self, drop_prob=None):
120
+ super(DropPath, self).__init__()
121
+ self.drop_prob = drop_prob
122
+
123
+ def forward(self, x):
124
+ return drop_path(x, self.drop_prob, self.training)
125
+
126
+ def extra_repr(self) -> str:
127
+ return 'p={}'.format(self.drop_prob)
128
+
129
+
130
+ class Mlp(nn.Module):
131
+ def __init__(
132
+ self,
133
+ in_features,
134
+ hidden_features=None,
135
+ out_features=None,
136
+ act_layer=nn.GELU,
137
+ norm_layer=nn.LayerNorm,
138
+ drop=0.,
139
+ subln=False,
140
+ ):
141
+ super().__init__()
142
+ out_features = out_features or in_features
143
+ hidden_features = hidden_features or in_features
144
+ self.fc1 = nn.Linear(in_features, hidden_features)
145
+ self.act = act_layer()
146
+
147
+ self.ffn_ln = norm_layer(hidden_features) if subln else nn.Identity()
148
+
149
+ self.fc2 = nn.Linear(hidden_features, out_features)
150
+ self.drop = nn.Dropout(drop)
151
+
152
+ def forward(self, x):
153
+ x = self.fc1(x)
154
+ x = self.act(x)
155
+ # x = self.drop(x)
156
+ # commit this for the orignal BERT implement
157
+ x = self.ffn_ln(x)
158
+
159
+ x = self.fc2(x)
160
+ x = self.drop(x)
161
+ return x
162
+
163
+ class SwiGLU(nn.Module):
164
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.SiLU, drop=0.,
165
+ norm_layer=nn.LayerNorm, subln=False):
166
+ super().__init__()
167
+ out_features = out_features or in_features
168
+ hidden_features = hidden_features or in_features
169
+
170
+ self.w1 = nn.Linear(in_features, hidden_features)
171
+ self.w2 = nn.Linear(in_features, hidden_features)
172
+
173
+ self.act = act_layer()
174
+ self.ffn_ln = norm_layer(hidden_features) if subln else nn.Identity()
175
+ self.w3 = nn.Linear(hidden_features, out_features)
176
+
177
+ self.drop = nn.Dropout(drop)
178
+
179
+ def forward(self, x):
180
+ x1 = self.w1(x)
181
+ x2 = self.w2(x)
182
+ hidden = self.act(x1) * x2
183
+ x = self.ffn_ln(hidden)
184
+ x = self.w3(x)
185
+ x = self.drop(x)
186
+ return x
187
+
188
+ class Attention(nn.Module):
189
+ def __init__(
190
+ self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.,
191
+ proj_drop=0., window_size=None, attn_head_dim=None, xattn=False, rope=None, subln=False, norm_layer=nn.LayerNorm):
192
+ super().__init__()
193
+ self.num_heads = num_heads
194
+ head_dim = dim // num_heads
195
+ if attn_head_dim is not None:
196
+ head_dim = attn_head_dim
197
+ all_head_dim = head_dim * self.num_heads
198
+ self.scale = qk_scale or head_dim ** -0.5
199
+
200
+ self.subln = subln
201
+ if self.subln:
202
+ self.q_proj = nn.Linear(dim, all_head_dim, bias=False)
203
+ self.k_proj = nn.Linear(dim, all_head_dim, bias=False)
204
+ self.v_proj = nn.Linear(dim, all_head_dim, bias=False)
205
+ else:
206
+ self.qkv = nn.Linear(dim, all_head_dim * 3, bias=False)
207
+
208
+ if qkv_bias:
209
+ self.q_bias = nn.Parameter(torch.zeros(all_head_dim))
210
+ self.v_bias = nn.Parameter(torch.zeros(all_head_dim))
211
+ else:
212
+ self.q_bias = None
213
+ self.v_bias = None
214
+
215
+ if window_size:
216
+ self.window_size = window_size
217
+ self.num_relative_distance = (2 * window_size[0] - 1) * (2 * window_size[1] - 1) + 3
218
+ self.relative_position_bias_table = nn.Parameter(
219
+ torch.zeros(self.num_relative_distance, num_heads)) # 2*Wh-1 * 2*Ww-1, nH
220
+ # cls to token & token 2 cls & cls to cls
221
+
222
+ # get pair-wise relative position index for each token inside the window
223
+ coords_h = torch.arange(window_size[0])
224
+ coords_w = torch.arange(window_size[1])
225
+ coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
226
+ coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
227
+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
228
+ relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
229
+ relative_coords[:, :, 0] += window_size[0] - 1 # shift to start from 0
230
+ relative_coords[:, :, 1] += window_size[1] - 1
231
+ relative_coords[:, :, 0] *= 2 * window_size[1] - 1
232
+ relative_position_index = \
233
+ torch.zeros(size=(window_size[0] * window_size[1] + 1, ) * 2, dtype=relative_coords.dtype)
234
+ relative_position_index[1:, 1:] = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
235
+ relative_position_index[0, 0:] = self.num_relative_distance - 3
236
+ relative_position_index[0:, 0] = self.num_relative_distance - 2
237
+ relative_position_index[0, 0] = self.num_relative_distance - 1
238
+
239
+ self.register_buffer("relative_position_index", relative_position_index)
240
+ else:
241
+ self.window_size = None
242
+ self.relative_position_bias_table = None
243
+ self.relative_position_index = None
244
+
245
+ self.attn_drop = nn.Dropout(attn_drop)
246
+ self.inner_attn_ln = norm_layer(all_head_dim) if subln else nn.Identity()
247
+ # self.proj = nn.Linear(all_head_dim, all_head_dim)
248
+ self.proj = nn.Linear(all_head_dim, dim)
249
+ self.proj_drop = nn.Dropout(proj_drop)
250
+ self.xattn = xattn
251
+ self.xattn_drop = attn_drop
252
+
253
+ self.rope = rope
254
+
255
+ def forward(self, x, rel_pos_bias=None, attn_mask=None):
256
+ B, N, C = x.shape
257
+ if self.subln:
258
+ q = F.linear(input=x, weight=self.q_proj.weight, bias=self.q_bias)
259
+ k = F.linear(input=x, weight=self.k_proj.weight, bias=None)
260
+ v = F.linear(input=x, weight=self.v_proj.weight, bias=self.v_bias)
261
+
262
+ q = q.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3) # B, num_heads, N, C
263
+ k = k.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3)
264
+ v = v.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3)
265
+ else:
266
+
267
+ qkv_bias = None
268
+ if self.q_bias is not None:
269
+ qkv_bias = torch.cat((self.q_bias, torch.zeros_like(self.v_bias, requires_grad=False), self.v_bias))
270
+
271
+ qkv = F.linear(input=x, weight=self.qkv.weight, bias=qkv_bias)
272
+ qkv = qkv.reshape(B, N, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) # 3, B, num_heads, N, C
273
+ q, k, v = qkv[0], qkv[1], qkv[2]
274
+
275
+ if self.rope:
276
+ # slightly fast impl
277
+ q_t = q[:, :, 1:, :]
278
+ ro_q_t = self.rope(q_t)
279
+ q = torch.cat((q[:, :, :1, :], ro_q_t), -2).type_as(v)
280
+
281
+ k_t = k[:, :, 1:, :]
282
+ ro_k_t = self.rope(k_t)
283
+ k = torch.cat((k[:, :, :1, :], ro_k_t), -2).type_as(v)
284
+
285
+ if self.xattn:
286
+ q = q.permute(0, 2, 1, 3) # B, num_heads, N, C -> B, N, num_heads, C
287
+ k = k.permute(0, 2, 1, 3)
288
+ v = v.permute(0, 2, 1, 3)
289
+
290
+ x = xops.memory_efficient_attention(
291
+ q, k, v,
292
+ p=self.xattn_drop,
293
+ scale=self.scale,
294
+ )
295
+ x = x.reshape(B, N, -1)
296
+ x = self.inner_attn_ln(x)
297
+ x = self.proj(x)
298
+ x = self.proj_drop(x)
299
+ else:
300
+ q = q * self.scale
301
+ attn = (q @ k.transpose(-2, -1))
302
+
303
+ if self.relative_position_bias_table is not None:
304
+ relative_position_bias = \
305
+ self.relative_position_bias_table[self.relative_position_index.view(-1)].view(
306
+ self.window_size[0] * self.window_size[1] + 1,
307
+ self.window_size[0] * self.window_size[1] + 1, -1) # Wh*Ww,Wh*Ww,nH
308
+ relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
309
+ attn = attn + relative_position_bias.unsqueeze(0).type_as(attn)
310
+
311
+ if rel_pos_bias is not None:
312
+ attn = attn + rel_pos_bias.type_as(attn)
313
+
314
+ if attn_mask is not None:
315
+ attn_mask = attn_mask.bool()
316
+ attn = attn.masked_fill(~attn_mask[:, None, None, :], float("-inf"))
317
+
318
+ attn = attn.softmax(dim=-1)
319
+ attn = self.attn_drop(attn)
320
+
321
+ x = (attn @ v).transpose(1, 2).reshape(B, N, -1)
322
+ x = self.inner_attn_ln(x)
323
+ x = self.proj(x)
324
+ x = self.proj_drop(x)
325
+ return x
326
+
327
+
328
+ class Block(nn.Module):
329
+
330
+ def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
331
+ drop_path=0., init_values=None, act_layer=nn.GELU, norm_layer=nn.LayerNorm,
332
+ window_size=None, attn_head_dim=None, xattn=False, rope=None, postnorm=False,
333
+ subln=False, naiveswiglu=False):
334
+ super().__init__()
335
+ self.norm1 = norm_layer(dim)
336
+ self.attn = Attention(
337
+ dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale,
338
+ attn_drop=attn_drop, proj_drop=drop, window_size=window_size, attn_head_dim=attn_head_dim,
339
+ xattn=xattn, rope=rope, subln=subln, norm_layer=norm_layer)
340
+ # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
341
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
342
+ self.norm2 = norm_layer(dim)
343
+ mlp_hidden_dim = int(dim * mlp_ratio)
344
+
345
+ if naiveswiglu:
346
+ self.mlp = SwiGLU(
347
+ in_features=dim,
348
+ hidden_features=mlp_hidden_dim,
349
+ subln=subln,
350
+ norm_layer=norm_layer,
351
+ )
352
+ else:
353
+ self.mlp = Mlp(
354
+ in_features=dim,
355
+ hidden_features=mlp_hidden_dim,
356
+ act_layer=act_layer,
357
+ subln=subln,
358
+ drop=drop
359
+ )
360
+
361
+ if init_values is not None and init_values > 0:
362
+ self.gamma_1 = nn.Parameter(init_values * torch.ones((dim)),requires_grad=True)
363
+ self.gamma_2 = nn.Parameter(init_values * torch.ones((dim)),requires_grad=True)
364
+ else:
365
+ self.gamma_1, self.gamma_2 = None, None
366
+
367
+ self.postnorm = postnorm
368
+
369
+ def forward(self, x, rel_pos_bias=None, attn_mask=None):
370
+ if self.gamma_1 is None:
371
+ if self.postnorm:
372
+ x = x + self.drop_path(self.norm1(self.attn(x, rel_pos_bias=rel_pos_bias, attn_mask=attn_mask)))
373
+ x = x + self.drop_path(self.norm2(self.mlp(x)))
374
+ else:
375
+ x = x + self.drop_path(self.attn(self.norm1(x), rel_pos_bias=rel_pos_bias, attn_mask=attn_mask))
376
+ x = x + self.drop_path(self.mlp(self.norm2(x)))
377
+ else:
378
+ if self.postnorm:
379
+ x = x + self.drop_path(self.gamma_1 * self.norm1(self.attn(x, rel_pos_bias=rel_pos_bias, attn_mask=attn_mask)))
380
+ x = x + self.drop_path(self.gamma_2 * self.norm2(self.mlp(x)))
381
+ else:
382
+ x = x + self.drop_path(self.gamma_1 * self.attn(self.norm1(x), rel_pos_bias=rel_pos_bias, attn_mask=attn_mask))
383
+ x = x + self.drop_path(self.gamma_2 * self.mlp(self.norm2(x)))
384
+ return x
385
+
386
+
387
+ class PatchEmbed(nn.Module):
388
+ """ Image to Patch Embedding
389
+ """
390
+ def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768):
391
+ super().__init__()
392
+ img_size = to_2tuple(img_size)
393
+ patch_size = to_2tuple(patch_size)
394
+ num_patches = (img_size[1] // patch_size[1]) * (img_size[0] // patch_size[0])
395
+ self.patch_shape = (img_size[0] // patch_size[0], img_size[1] // patch_size[1])
396
+ self.img_size = img_size
397
+ self.patch_size = patch_size
398
+ self.num_patches = num_patches
399
+
400
+ self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
401
+
402
+ def forward(self, x, **kwargs):
403
+ B, C, H, W = x.shape
404
+ # FIXME look at relaxing size constraints
405
+ assert H == self.img_size[0] and W == self.img_size[1], \
406
+ f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
407
+ x = self.proj(x).flatten(2).transpose(1, 2)
408
+ return x
409
+
410
+
411
+ class RelativePositionBias(nn.Module):
412
+
413
+ def __init__(self, window_size, num_heads):
414
+ super().__init__()
415
+ self.window_size = window_size
416
+ self.num_relative_distance = (2 * window_size[0] - 1) * (2 * window_size[1] - 1) + 3
417
+ self.relative_position_bias_table = nn.Parameter(
418
+ torch.zeros(self.num_relative_distance, num_heads)) # 2*Wh-1 * 2*Ww-1, nH
419
+ # cls to token & token 2 cls & cls to cls
420
+
421
+ # get pair-wise relative position index for each token inside the window
422
+ coords_h = torch.arange(window_size[0])
423
+ coords_w = torch.arange(window_size[1])
424
+ coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
425
+ coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
426
+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
427
+ relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
428
+ relative_coords[:, :, 0] += window_size[0] - 1 # shift to start from 0
429
+ relative_coords[:, :, 1] += window_size[1] - 1
430
+ relative_coords[:, :, 0] *= 2 * window_size[1] - 1
431
+ relative_position_index = \
432
+ torch.zeros(size=(window_size[0] * window_size[1] + 1,) * 2, dtype=relative_coords.dtype)
433
+ relative_position_index[1:, 1:] = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
434
+ relative_position_index[0, 0:] = self.num_relative_distance - 3
435
+ relative_position_index[0:, 0] = self.num_relative_distance - 2
436
+ relative_position_index[0, 0] = self.num_relative_distance - 1
437
+
438
+ self.register_buffer("relative_position_index", relative_position_index)
439
+
440
+ def forward(self):
441
+ relative_position_bias = \
442
+ self.relative_position_bias_table[self.relative_position_index.view(-1)].view(
443
+ self.window_size[0] * self.window_size[1] + 1,
444
+ self.window_size[0] * self.window_size[1] + 1, -1) # Wh*Ww,Wh*Ww,nH
445
+ return relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
446
+
447
+
448
+ class EVAVisionTransformer(nn.Module):
449
+ """ Vision Transformer with support for patch or hybrid CNN input stage
450
+ """
451
+ def __init__(self, img_size=224, patch_size=16, in_chans=3, num_classes=1000, embed_dim=768, depth=12,
452
+ num_heads=12, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop_rate=0., attn_drop_rate=0.,
453
+ drop_path_rate=0., norm_layer=nn.LayerNorm, init_values=None, patch_dropout=0.,
454
+ use_abs_pos_emb=True, use_rel_pos_bias=False, use_shared_rel_pos_bias=False, rope=False,
455
+ use_mean_pooling=True, init_scale=0.001, grad_checkpointing=False, xattn=False, postnorm=False,
456
+ pt_hw_seq_len=16, intp_freq=False, naiveswiglu=False, subln=False):
457
+ super().__init__()
458
+
459
+ if not XFORMERS_IS_AVAILBLE:
460
+ xattn = False
461
+
462
+ self.image_size = img_size
463
+ self.num_classes = num_classes
464
+ self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
465
+
466
+ self.patch_embed = PatchEmbed(
467
+ img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim)
468
+ num_patches = self.patch_embed.num_patches
469
+
470
+ self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
471
+ # self.mask_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
472
+ if use_abs_pos_emb:
473
+ self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim))
474
+ else:
475
+ self.pos_embed = None
476
+ self.pos_drop = nn.Dropout(p=drop_rate)
477
+
478
+ if use_shared_rel_pos_bias:
479
+ self.rel_pos_bias = RelativePositionBias(window_size=self.patch_embed.patch_shape, num_heads=num_heads)
480
+ else:
481
+ self.rel_pos_bias = None
482
+
483
+ if rope:
484
+ half_head_dim = embed_dim // num_heads // 2
485
+ hw_seq_len = img_size // patch_size
486
+ self.rope = VisionRotaryEmbeddingFast(
487
+ dim=half_head_dim,
488
+ pt_seq_len=pt_hw_seq_len,
489
+ ft_seq_len=hw_seq_len if intp_freq else None,
490
+ # patch_dropout=patch_dropout
491
+ )
492
+ else:
493
+ self.rope = None
494
+
495
+ self.naiveswiglu = naiveswiglu
496
+
497
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
498
+ self.use_rel_pos_bias = use_rel_pos_bias
499
+ self.blocks = nn.ModuleList([
500
+ Block(
501
+ dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,
502
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer,
503
+ init_values=init_values, window_size=self.patch_embed.patch_shape if use_rel_pos_bias else None,
504
+ xattn=xattn, rope=self.rope, postnorm=postnorm, subln=subln, naiveswiglu=naiveswiglu)
505
+ for i in range(depth)])
506
+ self.norm = nn.Identity() if use_mean_pooling else norm_layer(embed_dim)
507
+ self.fc_norm = norm_layer(embed_dim) if use_mean_pooling else None
508
+ self.head = nn.Linear(embed_dim, num_classes) if num_classes > 0 else nn.Identity()
509
+
510
+ if self.pos_embed is not None:
511
+ trunc_normal_(self.pos_embed, std=.02)
512
+
513
+ trunc_normal_(self.cls_token, std=.02)
514
+ # trunc_normal_(self.mask_token, std=.02)
515
+
516
+ self.apply(self._init_weights)
517
+ self.fix_init_weight()
518
+
519
+ if isinstance(self.head, nn.Linear):
520
+ trunc_normal_(self.head.weight, std=.02)
521
+ self.head.weight.data.mul_(init_scale)
522
+ self.head.bias.data.mul_(init_scale)
523
+
524
+ # setting a patch_dropout of 0. would mean it is disabled and this function would be the identity fn
525
+ self.patch_dropout = PatchDropout(patch_dropout) if patch_dropout > 0. else nn.Identity()
526
+
527
+ self.grad_checkpointing = grad_checkpointing
528
+
529
+ def fix_init_weight(self):
530
+ def rescale(param, layer_id):
531
+ param.div_(math.sqrt(2.0 * layer_id))
532
+
533
+ for layer_id, layer in enumerate(self.blocks):
534
+ rescale(layer.attn.proj.weight.data, layer_id + 1)
535
+ if self.naiveswiglu:
536
+ rescale(layer.mlp.w3.weight.data, layer_id + 1)
537
+ else:
538
+ rescale(layer.mlp.fc2.weight.data, layer_id + 1)
539
+
540
+ def get_cast_dtype(self) -> torch.dtype:
541
+ return self.blocks[0].mlp.fc2.weight.dtype
542
+
543
+ def _init_weights(self, m):
544
+ if isinstance(m, nn.Linear):
545
+ trunc_normal_(m.weight, std=.02)
546
+ if m.bias is not None:
547
+ nn.init.constant_(m.bias, 0)
548
+ elif isinstance(m, nn.LayerNorm):
549
+ nn.init.constant_(m.bias, 0)
550
+ nn.init.constant_(m.weight, 1.0)
551
+
552
+ def get_num_layers(self):
553
+ return len(self.blocks)
554
+
555
+ def lock(self, unlocked_groups=0, freeze_bn_stats=False):
556
+ assert unlocked_groups == 0, 'partial locking not currently supported for this model'
557
+ for param in self.parameters():
558
+ param.requires_grad = False
559
+
560
+ @torch.jit.ignore
561
+ def set_grad_checkpointing(self, enable=True):
562
+ self.grad_checkpointing = enable
563
+
564
+ @torch.jit.ignore
565
+ def no_weight_decay(self):
566
+ return {'pos_embed', 'cls_token'}
567
+
568
+ def get_classifier(self):
569
+ return self.head
570
+
571
+ def reset_classifier(self, num_classes, global_pool=''):
572
+ self.num_classes = num_classes
573
+ self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity()
574
+
575
+ def forward_features(self, x, return_all_features=False, return_hidden=False, shuffle=False):
576
+
577
+ x = self.patch_embed(x)
578
+ batch_size, seq_len, _ = x.size()
579
+
580
+ if shuffle:
581
+ idx = torch.randperm(x.shape[1]) + 1
582
+ zero = torch.LongTensor([0, ])
583
+ idx = torch.cat([zero, idx])
584
+ pos_embed = self.pos_embed[:, idx]
585
+
586
+ cls_tokens = self.cls_token.expand(batch_size, -1, -1) # stole cls_tokens impl from Phil Wang, thanks
587
+ x = torch.cat((cls_tokens, x), dim=1)
588
+ if shuffle:
589
+ x = x + pos_embed
590
+ elif self.pos_embed is not None:
591
+ x = x + self.pos_embed
592
+ x = self.pos_drop(x)
593
+
594
+ # a patch_dropout of 0. would mean it is disabled and this function would do nothing but return what was passed in
595
+ if os.getenv('RoPE') == '1':
596
+ if self.training and not isinstance(self.patch_dropout, nn.Identity):
597
+ x, patch_indices_keep = self.patch_dropout(x)
598
+ self.rope.forward = partial(self.rope.forward, patch_indices_keep=patch_indices_keep)
599
+ else:
600
+ self.rope.forward = partial(self.rope.forward, patch_indices_keep=None)
601
+ x = self.patch_dropout(x)
602
+ else:
603
+ x = self.patch_dropout(x)
604
+
605
+ rel_pos_bias = self.rel_pos_bias() if self.rel_pos_bias is not None else None
606
+ hidden_states = []
607
+ for idx, blk in enumerate(self.blocks):
608
+ if (0 < idx <= 20) and (idx % 4 == 0) and return_hidden:
609
+ hidden_states.append(x)
610
+ if self.grad_checkpointing:
611
+ x = checkpoint(blk, x, (rel_pos_bias,))
612
+ else:
613
+ x = blk(x, rel_pos_bias=rel_pos_bias)
614
+
615
+ if not return_all_features:
616
+ x = self.norm(x)
617
+ if self.fc_norm is not None:
618
+ return self.fc_norm(x.mean(1)), hidden_states
619
+ else:
620
+ return x[:, 0], hidden_states
621
+ return x
622
+
623
+ def forward(self, x, return_all_features=False, return_hidden=False, shuffle=False):
624
+ if return_all_features:
625
+ return self.forward_features(x, return_all_features, return_hidden, shuffle)
626
+ x, hidden_states = self.forward_features(x, return_all_features, return_hidden, shuffle)
627
+ x = self.head(x)
628
+ if return_hidden:
629
+ return x, hidden_states
630
+ return x