revliter commited on
Commit
997d42e
·
verified ·
1 Parent(s): 8f1a72d

Upload 5 files

Browse files
internvideo_next_large_ps14_res224.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a6e767e1a3770b189940139283efc1fcc06a6a6bd649af1533b94a028c43d87b
3
+ size 622100416
models/InternVideo_next.py ADDED
@@ -0,0 +1,559 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ import torch.nn.functional as F
4
+ from timm.models.layers import DropPath, to_2tuple, trunc_normal_
5
+ from timm.models.registry import register_model
6
+ from torch import nn
7
+
8
+ import torch.utils.checkpoint as checkpoint
9
+ from functools import partial
10
+ from einops import rearrange
11
+
12
+ from .pos_embed import get_3d_sincos_pos_embed, get_2d_sincos_pos_embed, get_1d_sincos_pos_embed
13
+ from .flash_attention_class import FlashAttention
14
+ from flash_attn.modules.mlp import FusedMLP
15
+ from flash_attn.ops.rms_norm import DropoutAddRMSNorm
16
+
17
+ import einops
18
+
19
+ class CrossAttention(nn.Module):
20
+ def __init__(
21
+ self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.,
22
+ proj_drop=0., attn_head_dim=None, out_dim=None):
23
+ super().__init__()
24
+ if out_dim is None:
25
+ out_dim = dim
26
+ self.num_heads = num_heads
27
+ head_dim = dim // num_heads
28
+ if attn_head_dim is not None:
29
+ head_dim = attn_head_dim
30
+ all_head_dim = head_dim * self.num_heads
31
+ self.scale = qk_scale or head_dim ** -0.5
32
+ assert all_head_dim == dim
33
+
34
+ self.q = nn.Linear(dim, all_head_dim, bias=False)
35
+ self.k = nn.Linear(dim, all_head_dim, bias=False)
36
+ self.v = nn.Linear(dim, all_head_dim, bias=False)
37
+
38
+ if qkv_bias:
39
+ self.q_bias = nn.Parameter(torch.zeros(all_head_dim))
40
+ self.k_bias = nn.Parameter(torch.zeros(all_head_dim))
41
+ self.v_bias = nn.Parameter(torch.zeros(all_head_dim))
42
+ else:
43
+ self.q_bias = None
44
+ self.k_bias = None
45
+ self.v_bias = None
46
+
47
+ self.attn_drop = nn.Dropout(attn_drop)
48
+ self.proj = nn.Linear(all_head_dim, out_dim)
49
+ self.proj_drop = nn.Dropout(proj_drop)
50
+
51
+ def forward(self, x, k=None, v=None):
52
+ B, N, C = x.shape
53
+ N_k = k.shape[1]
54
+ N_v = v.shape[1]
55
+
56
+ q_bias, k_bias, v_bias = None, None, None
57
+ if self.q_bias is not None:
58
+ q_bias = self.q_bias
59
+ k_bias = self.k_bias
60
+ v_bias = self.v_bias
61
+
62
+ q = F.linear(input=x, weight=self.q.weight, bias=q_bias)
63
+ q = q.reshape(B, N, 1, self.num_heads, -1).permute(2, 0, 3, 1, 4).squeeze(0) # (B, N_head, N_q, dim)
64
+
65
+ k = F.linear(input=k, weight=self.k.weight, bias=k_bias)
66
+ k = k.reshape(B, N_k, 1, self.num_heads, -1).permute(2, 0, 3, 1, 4).squeeze(0)
67
+
68
+ v = F.linear(input=v, weight=self.v.weight, bias=v_bias)
69
+ v = v.reshape(B, N_v, 1, self.num_heads, -1).permute(2, 0, 3, 1, 4).squeeze(0)
70
+
71
+ q = q * self.scale
72
+ attn = (q @ k.transpose(-2, -1)) # (B, N_head, N_q, N_k)
73
+
74
+ attn = attn.softmax(dim=-1)
75
+ attn = self.attn_drop(attn)
76
+
77
+ x = (attn @ v).transpose(1, 2).reshape(B, N, -1)
78
+ x = self.proj(x)
79
+ x = self.proj_drop(x)
80
+
81
+ return x
82
+
83
+
84
+ class AttentiveBlock(nn.Module):
85
+
86
+ def __init__(self, dim, num_heads, qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
87
+ drop_path=0., norm_layer=nn.LayerNorm, attn_head_dim=None, out_dim=None):
88
+ super().__init__()
89
+
90
+ self.norm1_q = norm_layer(dim)
91
+ self.norm1_k = norm_layer(dim)
92
+ self.norm1_v = norm_layer(dim)
93
+ self.cross_attn = CrossAttention(
94
+ dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop,
95
+ proj_drop=drop, attn_head_dim=attn_head_dim, out_dim=out_dim)
96
+
97
+ if drop_path > 0.:
98
+ print(f"Use DropPath in projector: {drop_path}")
99
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
100
+
101
+ def forward(self, x_q, x_kv, pos_q, pos_k, bool_masked_pos, rel_pos_bias=None):
102
+ x_q = self.norm1_q(x_q + pos_q)
103
+ x_k = self.norm1_k(x_kv + pos_k)
104
+ x_v = self.norm1_v(x_kv)
105
+ x = self.cross_attn(x_q, k=x_k, v=x_v)
106
+
107
+ return x
108
+
109
+
110
+ class AttentionPoolingBlock(AttentiveBlock):
111
+
112
+ def forward(self, x):
113
+ x_q = x.mean(1, keepdim=True)
114
+ x_kv, pos_q, pos_k = x, 0, 0
115
+ x = super().forward(x_q, x_kv, pos_q, pos_k, bool_masked_pos=None, rel_pos_bias=None)
116
+ x = x.squeeze(1)
117
+ return x
118
+
119
+
120
+ class RMSNorm(nn.Module):
121
+ def __init__(self, hidden_size, eps=1e-6):
122
+ super().__init__()
123
+ self.weight = nn.Parameter(torch.ones(hidden_size))
124
+ self.variance_epsilon = eps
125
+
126
+ def forward(self, hidden_states):
127
+ input_dtype = hidden_states.dtype
128
+ hidden_states = hidden_states.to(torch.float32)
129
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
130
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
131
+ return self.weight * hidden_states.to(input_dtype)
132
+
133
+
134
+ class LayerScale(nn.Module):
135
+ def __init__(self, dim, init_values=1e-5, inplace=False, force_fp32=False):
136
+ super().__init__()
137
+ self.inplace = inplace
138
+ self.gamma = nn.Parameter(init_values * torch.ones(dim))
139
+ self.force_fp32 = force_fp32
140
+
141
+ @torch.cuda.amp.autocast(enabled=False)
142
+ def forward(self, x):
143
+ if self.force_fp32:
144
+ output_type = x.dtype
145
+ out = x.float().mul_(self.gamma.float()) if self.inplace else x.float() * self.gamma.float()
146
+ return out.to(dtype=output_type)
147
+ else:
148
+ out = x.mul_(self.gamma) if self.inplace else x * self.gamma
149
+ return out
150
+
151
+
152
+ class Attention(nn.Module):
153
+ def __init__(self, dim, num_heads=8, qkv_bias=False, attn_drop=0., proj_drop=0., use_flash_attn=False,
154
+ causal=False, norm_layer=nn.LayerNorm, qk_normalization=False, use_fused_rmsnorm=False):
155
+ super().__init__()
156
+ assert dim % num_heads == 0, 'dim should be divisible by num_heads'
157
+ self.num_heads = num_heads
158
+ head_dim = dim // num_heads
159
+ self.scale = head_dim ** -0.5
160
+
161
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
162
+ self.attn_drop = nn.Dropout(attn_drop)
163
+ self.proj = nn.Linear(dim, dim)
164
+ self.proj_drop = nn.Dropout(proj_drop)
165
+
166
+ self.use_flash_attn = use_flash_attn
167
+ if use_flash_attn:
168
+ self.causal = causal
169
+ self.inner_attn = FlashAttention(attention_dropout=attn_drop)
170
+
171
+ self.qk_normalization = qk_normalization
172
+ self.q_norm = norm_layer(dim) if qk_normalization else nn.Identity()
173
+ self.k_norm = norm_layer(dim) if qk_normalization else nn.Identity()
174
+ self.use_fused_rmsnorm = use_fused_rmsnorm
175
+
176
+ def _naive_attn(self, x):
177
+ B, N, C = x.shape
178
+ qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
179
+ q, k, v = qkv.unbind(0) # make torchscript happy (cannot use tensor as tuple)
180
+
181
+ if self.qk_normalization:
182
+ B_, H_, N_, D_ = q.shape
183
+ q = self.q_norm(q.transpose(1, 2).flatten(-2, -1)).view(B_, N_, H_, D_).transpose(1, 2)
184
+ k = self.k_norm(k.transpose(1, 2).flatten(-2, -1)).view(B_, N_, H_, D_).transpose(1, 2)
185
+
186
+ attn = ((q * self.scale) @ k.transpose(-2, -1))
187
+ # attn = attn - attn.max(-1)[0].unsqueeze(-1) # in case of overflow for fp16
188
+ attn = attn.softmax(dim=-1)
189
+ attn = self.attn_drop(attn)
190
+
191
+ x = (attn @ v).transpose(1, 2).reshape(B, N, C)
192
+ x = self.proj(x)
193
+ x = self.proj_drop(x)
194
+ return x
195
+
196
+ def _flash_attn(self, x, key_padding_mask=None, need_weights=False):
197
+
198
+ qkv = self.qkv(x)
199
+ qkv = rearrange(qkv, "b s (three h d) -> b s three h d", three=3, h=self.num_heads)
200
+
201
+ if self.qk_normalization:
202
+ q, k, v = qkv.unbind(2)
203
+ if self.use_fused_rmsnorm:
204
+ q = self.q_norm(q.flatten(-2, -1))[0].view(q.shape)
205
+ k = self.k_norm(k.flatten(-2, -1))[0].view(k.shape)
206
+ else:
207
+ q = self.q_norm(q.flatten(-2, -1)).view(q.shape)
208
+ k = self.k_norm(k.flatten(-2, -1)).view(k.shape)
209
+ qkv = torch.stack([q, k, v], dim=2)
210
+
211
+ context, _ = self.inner_attn(
212
+ qkv, key_padding_mask=key_padding_mask, need_weights=need_weights, causal=self.causal
213
+ )
214
+ outs = self.proj(rearrange(context, "b s h d -> b s (h d)"))
215
+ outs = self.proj_drop(outs)
216
+ return outs
217
+
218
+ def forward(self, x):
219
+ x = self._naive_attn(x) if not self.use_flash_attn else self._flash_attn(x)
220
+ return x
221
+
222
+
223
+ class Mlp(nn.Module):
224
+ """ MLP as used in Vision Transformer, MLP-Mixer and related networks
225
+ """
226
+
227
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU,
228
+ bias=True, drop=0.):
229
+ super().__init__()
230
+ out_features = out_features or in_features
231
+ hidden_features = hidden_features or in_features
232
+ bias = to_2tuple(bias)
233
+ drop_probs = to_2tuple(drop)
234
+
235
+ self.fc1 = nn.Linear(in_features, hidden_features, bias=bias[0])
236
+ self.act = act_layer()
237
+ self.drop1 = nn.Dropout(drop_probs[0])
238
+ self.fc2 = nn.Linear(hidden_features, out_features, bias=bias[1])
239
+ self.drop2 = nn.Dropout(drop_probs[1])
240
+
241
+ def forward(self, x):
242
+ x = self.fc1(x)
243
+ x = self.act(x)
244
+ x = self.drop1(x)
245
+ x = self.fc2(x)
246
+ x = self.drop2(x)
247
+ return x
248
+
249
+
250
+ class Block(nn.Module):
251
+
252
+ def __init__(
253
+ self, dim, num_heads, mlp_ratio=4., qkv_bias=False, drop=0., attn_drop=0., init_values=None,
254
+ drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, use_flash_attn=False, use_fused_mlp=False,
255
+ fused_mlp_heuristic=1, with_cp=False, qk_normalization=False, layerscale_no_force_fp32=False,
256
+ use_fused_rmsnorm=False):
257
+ super().__init__()
258
+
259
+ self.norm1 = norm_layer(dim)
260
+ self.attn = Attention(dim, num_heads=num_heads, qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop,
261
+ use_flash_attn=use_flash_attn, causal=False, norm_layer=norm_layer,
262
+ qk_normalization=qk_normalization,
263
+ use_fused_rmsnorm=use_fused_rmsnorm)
264
+ self.ls1 = LayerScale(dim, init_values=init_values,
265
+ force_fp32=(not layerscale_no_force_fp32)) if init_values else nn.Identity()
266
+ # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
267
+ self.drop_path1 = DropPath(drop_path) if drop_path > 0. else nn.Identity()
268
+
269
+ self.norm2 = norm_layer(dim)
270
+ mlp_hidden_dim = int(dim * mlp_ratio)
271
+ if use_fused_mlp:
272
+ self.mlp = FusedMLP(in_features=dim, hidden_features=mlp_hidden_dim, heuristic=fused_mlp_heuristic)
273
+ else:
274
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
275
+ self.ls2 = LayerScale(dim, init_values=init_values,
276
+ force_fp32=(not layerscale_no_force_fp32)) if init_values else nn.Identity()
277
+ self.drop_path2 = DropPath(drop_path) if drop_path > 0. else nn.Identity()
278
+
279
+ self.with_cp = with_cp
280
+ self.use_fused_rmsnorm = use_fused_rmsnorm
281
+
282
+ def forward(self, x, residual=None):
283
+
284
+ def _inner_forward(x, residual=None):
285
+ if self.use_fused_rmsnorm:
286
+ x, residual = self.norm1(x, residual)
287
+ x = self.drop_path1(self.ls1(self.attn(x)))
288
+ x, residual = self.norm2(x, residual)
289
+ x = self.drop_path2(self.ls2(self.mlp(x)))
290
+ return x, residual
291
+ else:
292
+ assert residual is None
293
+ x = x + self.drop_path1(self.ls1(self.attn(self.norm1(x))))
294
+ x = x + self.drop_path2(self.ls2(self.mlp(self.norm2(x))))
295
+ return x
296
+
297
+ if self.with_cp:
298
+ return checkpoint.checkpoint(_inner_forward, x, residual)
299
+ else:
300
+ return _inner_forward(x, residual=residual)
301
+
302
+ class PatchEmbed(nn.Module):
303
+ """ 3D Image to Patch Embedding
304
+ """
305
+
306
+ def __init__(
307
+ self, img_size=224, patch_size=16, in_chans=3, embed_dim=768,
308
+ num_frames=8, tubelet_size=1, norm_layer=None
309
+ ):
310
+ super().__init__()
311
+ img_size = to_2tuple(img_size)
312
+ patch_size = to_2tuple(patch_size)
313
+ self.img_size = img_size
314
+ self.patch_size = patch_size
315
+ self.tubelet_size = tubelet_size
316
+ self.grid_size = (
317
+ num_frames // tubelet_size,
318
+ img_size[0] // patch_size[0],
319
+ img_size[1] // patch_size[1]
320
+ ) # (T, H, W)
321
+ self.num_patches = self.grid_size[0] * self.grid_size[1] * self.grid_size[2]
322
+
323
+ self.proj = nn.Conv3d(
324
+ in_channels=in_chans, out_channels=embed_dim,
325
+ kernel_size=(tubelet_size, patch_size[0], patch_size[1]),
326
+ stride=(tubelet_size, patch_size[0], patch_size[1])
327
+ )
328
+
329
+ self.norm = norm_layer(embed_dim)
330
+ self.norm_before = norm_layer(tubelet_size * math.prod(patch_size) * 3)
331
+
332
+ def forward(self, x):
333
+ B, C, T, H, W = x.shape
334
+ x = x.permute(0, 2, 3, 4, 1)
335
+ x = einops.rearrange(x, "b (t1 t2) (ht hp) (wt wp) c -> b (t1 ht wt) (t2 hp wp c)", t2=self.tubelet_size, hp=self.patch_size[0], wp=self.patch_size[1])
336
+ x = self.norm_before(x) # x.shape: [B, T, HW, C]
337
+ x = einops.rearrange(x, "b (t1 ht wt) (t2 hp wp c) -> b (t1 t2) (ht hp) (wt wp) c", t1=T//self.tubelet_size, ht=H//self.patch_size[0], t2=self.tubelet_size, hp=self.patch_size[0], wp=self.patch_size[1])
338
+ x = x.permute(0, 4, 1, 2, 3)
339
+ x = self.proj(x)
340
+ x = x.flatten(3).permute(0, 2, 3, 1)
341
+ x = self.norm(x)
342
+ return x
343
+
344
+
345
+ class InternVideo2(nn.Module):
346
+ def __init__(
347
+ self,
348
+ in_chans: int = 3,
349
+ patch_size: int = 14,
350
+ img_size: int = 224,
351
+ qkv_bias: bool = False,
352
+ drop_path_rate: float = 0.25,
353
+ embed_dim: int = 1408,
354
+ head_drop_path_rate: float = 0.,
355
+ num_heads: int = 16,
356
+ mlp_ratio: float = 4.3637,
357
+ init_values: float = 1e-5,
358
+ qk_normalization: bool = True,
359
+ depth: int = 40,
360
+ use_flash_attn: bool = True,
361
+ use_fused_rmsnorm: bool = True,
362
+ use_fused_mlp: bool = True,
363
+ fused_mlp_heuristic: int = 1,
364
+ attn_pool_num_heads: int = 16,
365
+ clip_embed_dim: int = 768,
366
+ layerscale_no_force_fp32: bool = False,
367
+ num_frames: int = 16,
368
+ tubelet_size: int = 1,
369
+ sep_pos_embed: bool = False,
370
+ use_checkpoint: bool = False,
371
+ checkpoint_num: int = 0,
372
+ cls_token_num: int = 4,
373
+ ):
374
+ super().__init__()
375
+ self.cls_token_num = cls_token_num
376
+ assert use_flash_attn == use_fused_rmsnorm == use_fused_mlp, print(
377
+ 'use_flash_attn, use_fused_rmsnorm and use_fused_mlp should be consistent')
378
+ print(mlp_ratio)
379
+
380
+ self.use_flash_attn = use_flash_attn
381
+ self.embed_dim = embed_dim
382
+
383
+ if use_fused_rmsnorm:
384
+ norm_layer_for_blocks = partial(DropoutAddRMSNorm, eps=1e-6, prenorm=True)
385
+ else:
386
+ norm_layer_for_blocks = partial(RMSNorm, eps=1e-6)
387
+ self.norm_layer_for_blocks = norm_layer_for_blocks
388
+ self.patch_embed = PatchEmbed(
389
+ img_size, patch_size, in_chans, embed_dim,
390
+ num_frames=num_frames, tubelet_size=tubelet_size, norm_layer=partial(RMSNorm, eps=1e-6)
391
+ )
392
+ num_patches = self.patch_embed.num_patches
393
+ self.cls_token = nn.Parameter(torch.zeros(1, cls_token_num, embed_dim))
394
+
395
+ self.sep_pos_embed = sep_pos_embed
396
+ if sep_pos_embed:
397
+ print("Use seperable position embedding")
398
+ grid_size = self.patch_embed.grid_size
399
+ self.grid_size = grid_size
400
+ self.pos_embed_spatial = nn.Parameter(torch.zeros(1, grid_size[1] * grid_size[2], embed_dim))
401
+ self.pos_embed_temporal = nn.Parameter(torch.zeros(1, grid_size[0], embed_dim))
402
+ self.pos_embed_cls = nn.Parameter(torch.zeros(1, 1, embed_dim))
403
+ else:
404
+ print("Use joint position embedding")
405
+ self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + cls_token_num, embed_dim))
406
+
407
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)]
408
+ # choose which layer to use checkpoint
409
+ with_cp_list = [False] * depth
410
+ if use_checkpoint:
411
+ for idx in range(depth):
412
+ if idx < checkpoint_num:
413
+ with_cp_list[idx] = True
414
+ print(f"Droppath rate: {dpr}")
415
+ print(f"Checkpoint list: {with_cp_list}")
416
+
417
+ self.blocks = nn.ModuleList([
418
+ Block(embed_dim, num_heads, mlp_ratio, qkv_bias=qkv_bias,
419
+ norm_layer=norm_layer_for_blocks,
420
+ drop_path=dpr[i], init_values=init_values, attn_drop=0.,
421
+ use_flash_attn=use_flash_attn, use_fused_mlp=use_fused_mlp,
422
+ fused_mlp_heuristic=fused_mlp_heuristic,
423
+ with_cp=with_cp_list[i],
424
+ qk_normalization=qk_normalization,
425
+ layerscale_no_force_fp32=layerscale_no_force_fp32,
426
+ use_fused_rmsnorm=use_fused_rmsnorm)
427
+ for i in range(depth)])
428
+ self.clip_projector = AttentionPoolingBlock(
429
+ dim=embed_dim, num_heads=attn_pool_num_heads, qkv_bias=True, qk_scale=None,
430
+ drop=0., attn_drop=0., drop_path=head_drop_path_rate,
431
+ norm_layer=partial(nn.LayerNorm, eps=1e-5), out_dim=clip_embed_dim
432
+ )
433
+
434
+ self.init_pos_embed()
435
+ trunc_normal_(self.cls_token, std=.02)
436
+ self.apply(self._init_weights)
437
+ self.fix_init_weight()
438
+
439
+ def init_pos_embed(self):
440
+ print("Init pos_embed from sincos pos_embed")
441
+ if self.sep_pos_embed:
442
+ pos_embed_spatial = get_2d_sincos_pos_embed(
443
+ self.pos_embed_spatial.shape[-1],
444
+ self.patch_embed.grid_size[1], # height & weight
445
+ )
446
+ self.pos_embed_spatial.data.copy_(torch.from_numpy(pos_embed_spatial).float().unsqueeze(0))
447
+ pos_embed_temporal = get_1d_sincos_pos_embed(
448
+ self.pos_embed_spatial.shape[-1],
449
+ self.patch_embed.grid_size[0], # t_size
450
+ )
451
+ self.pos_embed_temporal.data.copy_(torch.from_numpy(pos_embed_temporal).float().unsqueeze(0))
452
+ else:
453
+ pos_embed = get_3d_sincos_pos_embed(
454
+ self.pos_embed.shape[-1],
455
+ self.patch_embed.grid_size[1], # height & weight
456
+ self.patch_embed.grid_size[0], # t_size
457
+ cls_token=True,
458
+ cls_token_num=self.cls_token_num
459
+ )
460
+ self.pos_embed.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0))
461
+
462
+ def _init_weights(self, m):
463
+ if isinstance(m, nn.Linear):
464
+ trunc_normal_(m.weight, std=.02)
465
+ if isinstance(m, nn.Linear) and m.bias is not None:
466
+ nn.init.constant_(m.bias, 0)
467
+ elif isinstance(m, nn.LayerNorm):
468
+ nn.init.constant_(m.bias, 0)
469
+ nn.init.constant_(m.weight, 1.0)
470
+
471
+ def fix_init_weight(self):
472
+ def rescale(param, layer_id):
473
+ param.div_(math.sqrt(2.0 * layer_id))
474
+
475
+ for layer_id, layer in enumerate(self.blocks):
476
+ rescale(layer.attn.proj.weight.data, layer_id + 1)
477
+ rescale(layer.mlp.fc2.weight.data, layer_id + 1)
478
+
479
+ @property
480
+ def dtype(self):
481
+ return self.patch_embed.proj.weight.dtype
482
+
483
+ def get_num_layers(self):
484
+ return len(self.blocks)
485
+
486
+ @torch.jit.ignore
487
+ def no_weight_decay(self):
488
+ return {
489
+ 'pos_embed',
490
+ 'pos_embed_spatial',
491
+ 'pos_embed_temporal',
492
+ 'pos_embed_cls',
493
+ 'cls_token'
494
+ }
495
+
496
+ def forward(self, x, projected=False):
497
+ x = self.patch_embed(x.type(self.dtype))
498
+ B, T, L, C = x.shape # T: temporal; L: spatial
499
+ x = x.view([B, T * L, C])
500
+
501
+ # append cls token
502
+ cls_tokens = self.cls_token.expand(B, -1, -1)
503
+ x = torch.cat((cls_tokens, x), dim=1)
504
+
505
+ # add pos_embed
506
+ if self.sep_pos_embed:
507
+ pos_embed = self.pos_embed_spatial.repeat(
508
+ 1, self.grid_size[0], 1
509
+ ) + torch.repeat_interleave(
510
+ self.pos_embed_temporal,
511
+ self.grid_size[1] * self.grid_size[2],
512
+ dim=1,
513
+ )
514
+ pos_embed = torch.cat(
515
+ [
516
+ self.pos_embed_cls.expand(pos_embed.shape[0], -1, -1),
517
+ pos_embed,
518
+ ],
519
+ 1,
520
+ )
521
+ else:
522
+ pos_embed = self.pos_embed
523
+ x = x + pos_embed
524
+
525
+ residual = None
526
+ for blk in self.blocks:
527
+ if isinstance(x, tuple) and len(x) == 2:
528
+ x, residual = x
529
+ x = blk(x, residual=residual)
530
+ if isinstance(x, tuple) and len(x) == 2:
531
+ x, residual = x
532
+ if residual is not None:
533
+ x = x + residual
534
+
535
+ if projected:
536
+ return self.clip_projector(x)
537
+
538
+ return x[:, self.cls_token_num:, :]
539
+
540
+
541
+ @register_model
542
+ def internvideo_next_base_patch14_224(pretrained=False, **kwargs):
543
+ model = InternVideo2(
544
+ img_size=224, patch_size=14, embed_dim=768,
545
+ depth=12, num_heads=12, mlp_ratio=4,
546
+ attn_pool_num_heads=16, clip_embed_dim=768,
547
+ **kwargs
548
+ )
549
+ return model
550
+
551
+ @register_model
552
+ def internvideo_next_large_patch14_224(pretrained=False, **kwargs):
553
+ model = InternVideo2(
554
+ img_size=224, patch_size=14, embed_dim=1024,
555
+ depth=24, num_heads=16, mlp_ratio=4,
556
+ attn_pool_num_heads=16, clip_embed_dim=768,
557
+ **kwargs
558
+ )
559
+ return model
models/__init__.py ADDED
File without changes
models/flash_attention_class.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+ from einops import rearrange
5
+
6
+ from flash_attn.flash_attn_interface import flash_attn_varlen_qkvpacked_func
7
+ from flash_attn.bert_padding import unpad_input, pad_input
8
+
9
+
10
+ class FlashAttention(nn.Module):
11
+ """Implement the scaled dot product attention with softmax.
12
+ Arguments
13
+ ---------
14
+ softmax_scale: The temperature to use for the softmax attention.
15
+ (default: 1/sqrt(d_keys) where d_keys is computed at
16
+ runtime)
17
+ attention_dropout: The dropout rate to apply to the attention
18
+ (default: 0.0)
19
+ """
20
+
21
+ def __init__(self, softmax_scale=None, attention_dropout=0.0, device=None, dtype=None):
22
+ super().__init__()
23
+ self.softmax_scale = softmax_scale
24
+ self.dropout_p = attention_dropout
25
+
26
+ def forward(self, qkv, key_padding_mask=None, causal=False, cu_seqlens=None,
27
+ max_s=None, need_weights=False):
28
+ """Implements the multihead softmax attention.
29
+ Arguments
30
+ ---------
31
+ qkv: The tensor containing the query, key, and value. (B, S, 3, H, D) if key_padding_mask is None
32
+ if unpadded: (nnz, 3, h, d)
33
+ key_padding_mask: a bool tensor of shape (B, S)
34
+ """
35
+ assert not need_weights
36
+ assert qkv.dtype in [torch.float16, torch.bfloat16]
37
+ assert qkv.is_cuda
38
+
39
+ if cu_seqlens is None:
40
+ batch_size = qkv.shape[0]
41
+ seqlen = qkv.shape[1]
42
+ if key_padding_mask is None:
43
+ qkv = rearrange(qkv, 'b s ... -> (b s) ...')
44
+ max_s = seqlen
45
+ cu_seqlens = torch.arange(0, (batch_size + 1) * seqlen, step=seqlen, dtype=torch.int32,
46
+ device=qkv.device)
47
+ output = flash_attn_varlen_qkvpacked_func(
48
+ qkv, cu_seqlens, max_s, self.dropout_p if self.training else 0.0,
49
+ softmax_scale=self.softmax_scale, causal=causal
50
+ )
51
+ output = rearrange(output, '(b s) ... -> b s ...', b=batch_size)
52
+ else:
53
+ nheads = qkv.shape[-2]
54
+ x = rearrange(qkv, 'b s three h d -> b s (three h d)')
55
+ x_unpad, indices, cu_seqlens, max_s = unpad_input(x, key_padding_mask)
56
+ x_unpad = rearrange(x_unpad, 'nnz (three h d) -> nnz three h d', three=3, h=nheads)
57
+ output_unpad = flash_attn_varlen_qkvpacked_func(
58
+ x_unpad, cu_seqlens, max_s, self.dropout_p if self.training else 0.0,
59
+ softmax_scale=self.softmax_scale, causal=causal
60
+ )
61
+ output = rearrange(pad_input(rearrange(output_unpad, 'nnz h d -> nnz (h d)'),
62
+ indices, batch_size, seqlen),
63
+ 'b s (h d) -> b s h d', h=nheads)
64
+ else:
65
+ assert max_s is not None
66
+ output = flash_attn_varlen_qkvpacked_func(
67
+ qkv, cu_seqlens, max_s, self.dropout_p if self.training else 0.0,
68
+ softmax_scale=self.softmax_scale, causal=causal
69
+ )
70
+
71
+ return output, None
models/pos_embed.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+
4
+ # --------------------------------------------------------
5
+ # 3D sine-cosine position embedding
6
+ # References:
7
+ # MVD: https://github.com/ruiwang2021/mvd/blob/main/modeling_finetune.py
8
+ # --------------------------------------------------------
9
+ def get_3d_sincos_pos_embed(embed_dim, grid_size, t_size, cls_token=False, cls_token_num=4):
10
+ """
11
+ grid_size: int of the grid height and width
12
+ t_size: int of the temporal size
13
+ return:
14
+ pos_embed: [t_size*grid_size*grid_size, embed_dim] or [1+t_size*grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
15
+ """
16
+ assert embed_dim % 4 == 0
17
+ embed_dim_spatial = embed_dim // 4 * 3
18
+ embed_dim_temporal = embed_dim // 4
19
+
20
+ # spatial
21
+ grid_h = np.arange(grid_size, dtype=np.float32)
22
+ grid_w = np.arange(grid_size, dtype=np.float32)
23
+ grid = np.meshgrid(grid_w, grid_h) # here w goes first
24
+ grid = np.stack(grid, axis=0)
25
+
26
+ grid = grid.reshape([2, 1, grid_size, grid_size])
27
+ pos_embed_spatial = get_2d_sincos_pos_embed_from_grid(
28
+ embed_dim_spatial, grid
29
+ )
30
+
31
+ # temporal
32
+ grid_t = np.arange(t_size, dtype=np.float32)
33
+ pos_embed_temporal = get_1d_sincos_pos_embed_from_grid(
34
+ embed_dim_temporal, grid_t
35
+ )
36
+
37
+ # concate: [T, H, W] order
38
+ pos_embed_temporal = pos_embed_temporal[:, np.newaxis, :]
39
+ pos_embed_temporal = np.repeat(
40
+ pos_embed_temporal, grid_size**2, axis=1
41
+ ) # [T, H*W, D // 4]
42
+ pos_embed_spatial = pos_embed_spatial[np.newaxis, :, :]
43
+ pos_embed_spatial = np.repeat(
44
+ pos_embed_spatial, t_size, axis=0
45
+ ) # [T, H*W, D // 4 * 3]
46
+
47
+ pos_embed = np.concatenate([pos_embed_temporal, pos_embed_spatial], axis=-1)
48
+ pos_embed = pos_embed.reshape([-1, embed_dim]) # [T*H*W, D]
49
+
50
+ if cls_token:
51
+ pos_embed = np.concatenate(
52
+ [np.zeros([cls_token_num, embed_dim]), pos_embed], axis=0
53
+ )
54
+ return pos_embed
55
+
56
+ def get_3d_sincos_pos_embed_new(embed_dim, grid_size, t_size, cls_token=False, cls_token_num=4):
57
+ """
58
+ grid_size: tuple or list of (grid_height, grid_width)
59
+ t_size: int of the temporal size
60
+ return:
61
+ pos_embed: [t_size*grid_height*grid_width, embed_dim] or [1+t_size*grid_height*grid_width, embed_dim] (w/ or w/o cls_token)
62
+ """
63
+ assert embed_dim % 4 == 0
64
+ embed_dim_spatial = embed_dim // 4 * 3
65
+ embed_dim_temporal = embed_dim // 4
66
+
67
+ # 处理 grid_size 参数,支持 int 或 tuple/list
68
+ if isinstance(grid_size, int):
69
+ grid_h = grid_size
70
+ grid_w = grid_size
71
+ else:
72
+ grid_h, grid_w = grid_size
73
+
74
+ # spatial
75
+ grid_h_arange = np.arange(grid_h, dtype=np.float32)
76
+ grid_w_arange = np.arange(grid_w, dtype=np.float32)
77
+ grid = np.meshgrid(grid_w_arange, grid_h_arange) # here w goes first
78
+ grid = np.stack(grid, axis=0)
79
+
80
+ grid = grid.reshape([2, 1, grid_h, grid_w])
81
+ pos_embed_spatial = get_2d_sincos_pos_embed_from_grid(
82
+ embed_dim_spatial, grid
83
+ )
84
+
85
+ # temporal
86
+ grid_t = np.arange(t_size, dtype=np.float32)
87
+ pos_embed_temporal = get_1d_sincos_pos_embed_from_grid(
88
+ embed_dim_temporal, grid_t
89
+ )
90
+
91
+ # concate: [T, H, W] order
92
+ pos_embed_temporal = pos_embed_temporal[:, np.newaxis, :]
93
+ pos_embed_temporal = np.repeat(
94
+ pos_embed_temporal, grid_h * grid_w, axis=1 # 修改为 grid_h * grid_w
95
+ ) # [T, H*W, D // 4]
96
+
97
+ pos_embed_spatial = pos_embed_spatial[np.newaxis, :, :]
98
+ pos_embed_spatial = np.repeat(
99
+ pos_embed_spatial, t_size, axis=0
100
+ ) # [T, H*W, D // 4 * 3]
101
+
102
+ pos_embed = np.concatenate([pos_embed_temporal, pos_embed_spatial], axis=-1)
103
+ pos_embed = pos_embed.reshape([-1, embed_dim]) # [T*H*W, D]
104
+
105
+ if cls_token:
106
+ pos_embed = np.concatenate(
107
+ [np.zeros([cls_token_num, embed_dim]), pos_embed], axis=0
108
+ )
109
+ return pos_embed
110
+
111
+ # --------------------------------------------------------
112
+ # 2D sine-cosine position embedding
113
+ # References:
114
+ # Transformer: https://github.com/tensorflow/models/blob/master/official/nlp/transformer/model_utils.py
115
+ # MoCo v3: https://github.com/facebookresearch/moco-v3
116
+ # --------------------------------------------------------
117
+ def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False):
118
+ """
119
+ grid_size: int of the grid height and width
120
+ return:
121
+ pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
122
+ """
123
+ grid_h = np.arange(grid_size, dtype=np.float32)
124
+ grid_w = np.arange(grid_size, dtype=np.float32)
125
+ grid = np.meshgrid(grid_w, grid_h) # here w goes first
126
+ grid = np.stack(grid, axis=0)
127
+
128
+ grid = grid.reshape([2, 1, grid_size, grid_size])
129
+ pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
130
+ if cls_token:
131
+ pos_embed = np.concatenate(
132
+ [np.zeros([1, embed_dim]), pos_embed], axis=0
133
+ )
134
+ return pos_embed
135
+
136
+
137
+ def get_1d_sincos_pos_embed(embed_dim, t_size, cls_token=False):
138
+ """
139
+ t_size: int of the temporal size
140
+ return:
141
+ pos_embed: [t_size, embed_dim] or [1+t_size, embed_dim] (w/ or w/o cls_token)
142
+ """
143
+ grid_t = np.arange(t_size, dtype=np.float32)
144
+ pos_embed = get_1d_sincos_pos_embed_from_grid(embed_dim, grid_t)
145
+ if cls_token:
146
+ pos_embed = np.concatenate(
147
+ [np.zeros([1, embed_dim]), pos_embed], axis=0
148
+ )
149
+ return pos_embed
150
+
151
+
152
+ def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
153
+ assert embed_dim % 2 == 0
154
+
155
+ # use half of dimensions to encode grid_h
156
+ emb_h = get_1d_sincos_pos_embed_from_grid(
157
+ embed_dim // 2, grid[0]
158
+ ) # (H*W, D/2)
159
+ emb_w = get_1d_sincos_pos_embed_from_grid(
160
+ embed_dim // 2, grid[1]
161
+ ) # (H*W, D/2)
162
+
163
+ emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)
164
+ return emb
165
+
166
+
167
+ def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
168
+ """
169
+ embed_dim: output dimension for each position
170
+ pos: a list of positions to be encoded: size (M,)
171
+ out: (M, D)
172
+ """
173
+ assert embed_dim % 2 == 0
174
+ omega = np.arange(embed_dim // 2, dtype=np.float32)
175
+ omega /= embed_dim / 2.0
176
+ omega = 1.0 / 10000**omega # (D/2,)
177
+
178
+ pos = pos.reshape(-1) # (M,)
179
+ out = np.einsum("m,d->md", pos, omega) # (M, D/2), outer product
180
+
181
+ emb_sin = np.sin(out) # (M, D/2)
182
+ emb_cos = np.cos(out) # (M, D/2)
183
+
184
+ emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
185
+ return emb
186
+
187
+
188
+ def interpolate_pos_embed(checkpoint_model, model, orig_t_size=4, pos_name='vision_encoder.pos_embed'):
189
+ if pos_name in checkpoint_model:
190
+ pos_embed_checkpoint = checkpoint_model[pos_name]
191
+ embedding_size = pos_embed_checkpoint.shape[-1] # channel dim
192
+ num_patches = model.patch_embed.num_patches #
193
+ num_extra_tokens = model.pos_embed.shape[-2] - num_patches # 0/1
194
+
195
+ # we use 4 frames for pretraining
196
+ new_t_size = model.T
197
+ # height (== width) for the checkpoint position embedding
198
+ orig_size = int(((pos_embed_checkpoint.shape[-2] - num_extra_tokens)//(orig_t_size)) ** 0.5)
199
+ # height (== width) for the new position embedding
200
+ new_size = int((num_patches // (new_t_size))** 0.5)
201
+
202
+ # class_token and dist_token are kept unchanged
203
+ if orig_t_size != new_t_size:
204
+ print(f"Temporal interpolate from {orig_t_size} to {new_t_size} ({pos_name})")
205
+ extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens]
206
+ # only the position tokens are interpolated
207
+ pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:]
208
+ # B, L, C -> B, T, HW, C -> BHW, C, T (B = 1)
209
+ pos_tokens = pos_tokens.view(1, orig_t_size, -1, embedding_size)
210
+ pos_tokens = pos_tokens.permute(0, 2, 3, 1).reshape(-1, embedding_size, orig_t_size)
211
+ pos_tokens = torch.nn.functional.interpolate(pos_tokens, size=new_t_size, mode='linear')
212
+ pos_tokens = pos_tokens.view(1, -1, embedding_size, new_t_size)
213
+ pos_tokens = pos_tokens.permute(0, 3, 1, 2).reshape(1, -1, embedding_size)
214
+ new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1)
215
+ checkpoint_model[pos_name] = new_pos_embed
216
+ pos_embed_checkpoint = new_pos_embed
217
+
218
+ # class_token and dist_token are kept unchanged
219
+ if orig_size != new_size:
220
+ print(f"Position interpolate from {orig_size}x{orig_size} to {new_size}x{new_size} ({pos_name})")
221
+ extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens]
222
+ # only the position tokens are interpolated
223
+ pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:]
224
+ # B, L, C -> BT, H, W, C -> BT, C, H, W
225
+ pos_tokens = pos_tokens.reshape(-1, new_t_size, orig_size, orig_size, embedding_size)
226
+ pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, embedding_size).permute(0, 3, 1, 2)
227
+ pos_tokens = torch.nn.functional.interpolate(
228
+ pos_tokens, size=(new_size, new_size), mode='bicubic', align_corners=False)
229
+ # BT, C, H, W -> BT, H, W, C -> B, T, H, W, C
230
+ pos_tokens = pos_tokens.permute(0, 2, 3, 1).reshape(-1, new_t_size, new_size, new_size, embedding_size)
231
+ pos_tokens = pos_tokens.flatten(1, 3) # B, L, C
232
+ new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1)
233
+ checkpoint_model[pos_name] = new_pos_embed
234
+ else:
235
+ raise NotImplementedError