Upload folder using huggingface_hub
Browse files- config.json +26 -0
- model.safetensors +3 -0
- modeling_config.py +21 -0
- modeling_internvideo_next.py +884 -0
config.json
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_name_or_path": "/mnt/petrelfs/wangchenting/code/internvideonext_hf_large",
|
| 3 |
+
"architectures": [
|
| 4 |
+
"InternVideoNext"
|
| 5 |
+
],
|
| 6 |
+
"auto_map": {
|
| 7 |
+
"AutoConfig": "modeling_config.InternVideoNextConfig",
|
| 8 |
+
"AutoModel": "modeling_internvideo_next.InternVideoNext"
|
| 9 |
+
},
|
| 10 |
+
"model_config": {
|
| 11 |
+
"attn_pool_num_heads": 16,
|
| 12 |
+
"clip_embed_dim": 768,
|
| 13 |
+
"depth": 24,
|
| 14 |
+
"embed_dim": 1024,
|
| 15 |
+
"img_size": 224,
|
| 16 |
+
"mlp_ratio": 4,
|
| 17 |
+
"num_frames": 16,
|
| 18 |
+
"num_heads": 16,
|
| 19 |
+
"patch_size": 14,
|
| 20 |
+
"tubelet_size": 1
|
| 21 |
+
},
|
| 22 |
+
"model_type": "InternVideoNext_Large",
|
| 23 |
+
"torch_dtype": "float16",
|
| 24 |
+
"transformers_version": "4.40.1",
|
| 25 |
+
"use_cache": true
|
| 26 |
+
}
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:538d64384706e96b7b01844bd9debc8fe8f9e3c86ee0162d8d0cb51c28fea51d
|
| 3 |
+
size 622102256
|
modeling_config.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy
|
| 2 |
+
import re, ast
|
| 3 |
+
from transformers import AutoConfig, LlamaConfig
|
| 4 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 5 |
+
from transformers.utils import logging
|
| 6 |
+
|
| 7 |
+
from easydict import EasyDict as MyEasyDict
|
| 8 |
+
from importlib import import_module
|
| 9 |
+
import os.path as osp
|
| 10 |
+
import argparse
|
| 11 |
+
import json
|
| 12 |
+
from copy import deepcopy
|
| 13 |
+
import sys
|
| 14 |
+
|
| 15 |
+
class InternVideoNextConfig(PretrainedConfig):
|
| 16 |
+
model_type = 'InternVideoNext_Large'
|
| 17 |
+
def __init__(
|
| 18 |
+
self,
|
| 19 |
+
**kwargs
|
| 20 |
+
):
|
| 21 |
+
super().__init__(**kwargs)
|
modeling_internvideo_next.py
ADDED
|
@@ -0,0 +1,884 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
| 72 |
+
|
| 73 |
+
import numpy as np
|
| 74 |
+
import torch
|
| 75 |
+
|
| 76 |
+
# --------------------------------------------------------
|
| 77 |
+
# 3D sine-cosine position embedding
|
| 78 |
+
# References:
|
| 79 |
+
# MVD: https://github.com/ruiwang2021/mvd/blob/main/modeling_finetune.py
|
| 80 |
+
# --------------------------------------------------------
|
| 81 |
+
def get_3d_sincos_pos_embed(embed_dim, grid_size, t_size, cls_token=False, cls_token_num=4):
|
| 82 |
+
"""
|
| 83 |
+
grid_size: int of the grid height and width
|
| 84 |
+
t_size: int of the temporal size
|
| 85 |
+
return:
|
| 86 |
+
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)
|
| 87 |
+
"""
|
| 88 |
+
assert embed_dim % 4 == 0
|
| 89 |
+
embed_dim_spatial = embed_dim // 4 * 3
|
| 90 |
+
embed_dim_temporal = embed_dim // 4
|
| 91 |
+
|
| 92 |
+
# spatial
|
| 93 |
+
grid_h = np.arange(grid_size, dtype=np.float32)
|
| 94 |
+
grid_w = np.arange(grid_size, dtype=np.float32)
|
| 95 |
+
grid = np.meshgrid(grid_w, grid_h) # here w goes first
|
| 96 |
+
grid = np.stack(grid, axis=0)
|
| 97 |
+
|
| 98 |
+
grid = grid.reshape([2, 1, grid_size, grid_size])
|
| 99 |
+
pos_embed_spatial = get_2d_sincos_pos_embed_from_grid(
|
| 100 |
+
embed_dim_spatial, grid
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
# temporal
|
| 104 |
+
grid_t = np.arange(t_size, dtype=np.float32)
|
| 105 |
+
pos_embed_temporal = get_1d_sincos_pos_embed_from_grid(
|
| 106 |
+
embed_dim_temporal, grid_t
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
# concate: [T, H, W] order
|
| 110 |
+
pos_embed_temporal = pos_embed_temporal[:, np.newaxis, :]
|
| 111 |
+
pos_embed_temporal = np.repeat(
|
| 112 |
+
pos_embed_temporal, grid_size**2, axis=1
|
| 113 |
+
) # [T, H*W, D // 4]
|
| 114 |
+
pos_embed_spatial = pos_embed_spatial[np.newaxis, :, :]
|
| 115 |
+
pos_embed_spatial = np.repeat(
|
| 116 |
+
pos_embed_spatial, t_size, axis=0
|
| 117 |
+
) # [T, H*W, D // 4 * 3]
|
| 118 |
+
|
| 119 |
+
pos_embed = np.concatenate([pos_embed_temporal, pos_embed_spatial], axis=-1)
|
| 120 |
+
pos_embed = pos_embed.reshape([-1, embed_dim]) # [T*H*W, D]
|
| 121 |
+
|
| 122 |
+
if cls_token:
|
| 123 |
+
pos_embed = np.concatenate(
|
| 124 |
+
[np.zeros([cls_token_num, embed_dim]), pos_embed], axis=0
|
| 125 |
+
)
|
| 126 |
+
return pos_embed
|
| 127 |
+
|
| 128 |
+
def get_3d_sincos_pos_embed_new(embed_dim, grid_size, t_size, cls_token=False, cls_token_num=4):
|
| 129 |
+
"""
|
| 130 |
+
grid_size: tuple or list of (grid_height, grid_width)
|
| 131 |
+
t_size: int of the temporal size
|
| 132 |
+
return:
|
| 133 |
+
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)
|
| 134 |
+
"""
|
| 135 |
+
assert embed_dim % 4 == 0
|
| 136 |
+
embed_dim_spatial = embed_dim // 4 * 3
|
| 137 |
+
embed_dim_temporal = embed_dim // 4
|
| 138 |
+
|
| 139 |
+
# 处理 grid_size 参数,支持 int 或 tuple/list
|
| 140 |
+
if isinstance(grid_size, int):
|
| 141 |
+
grid_h = grid_size
|
| 142 |
+
grid_w = grid_size
|
| 143 |
+
else:
|
| 144 |
+
grid_h, grid_w = grid_size
|
| 145 |
+
|
| 146 |
+
# spatial
|
| 147 |
+
grid_h_arange = np.arange(grid_h, dtype=np.float32)
|
| 148 |
+
grid_w_arange = np.arange(grid_w, dtype=np.float32)
|
| 149 |
+
grid = np.meshgrid(grid_w_arange, grid_h_arange) # here w goes first
|
| 150 |
+
grid = np.stack(grid, axis=0)
|
| 151 |
+
|
| 152 |
+
grid = grid.reshape([2, 1, grid_h, grid_w])
|
| 153 |
+
pos_embed_spatial = get_2d_sincos_pos_embed_from_grid(
|
| 154 |
+
embed_dim_spatial, grid
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
# temporal
|
| 158 |
+
grid_t = np.arange(t_size, dtype=np.float32)
|
| 159 |
+
pos_embed_temporal = get_1d_sincos_pos_embed_from_grid(
|
| 160 |
+
embed_dim_temporal, grid_t
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
# concate: [T, H, W] order
|
| 164 |
+
pos_embed_temporal = pos_embed_temporal[:, np.newaxis, :]
|
| 165 |
+
pos_embed_temporal = np.repeat(
|
| 166 |
+
pos_embed_temporal, grid_h * grid_w, axis=1 # 修改为 grid_h * grid_w
|
| 167 |
+
) # [T, H*W, D // 4]
|
| 168 |
+
|
| 169 |
+
pos_embed_spatial = pos_embed_spatial[np.newaxis, :, :]
|
| 170 |
+
pos_embed_spatial = np.repeat(
|
| 171 |
+
pos_embed_spatial, t_size, axis=0
|
| 172 |
+
) # [T, H*W, D // 4 * 3]
|
| 173 |
+
|
| 174 |
+
pos_embed = np.concatenate([pos_embed_temporal, pos_embed_spatial], axis=-1)
|
| 175 |
+
pos_embed = pos_embed.reshape([-1, embed_dim]) # [T*H*W, D]
|
| 176 |
+
|
| 177 |
+
if cls_token:
|
| 178 |
+
pos_embed = np.concatenate(
|
| 179 |
+
[np.zeros([cls_token_num, embed_dim]), pos_embed], axis=0
|
| 180 |
+
)
|
| 181 |
+
return pos_embed
|
| 182 |
+
|
| 183 |
+
# --------------------------------------------------------
|
| 184 |
+
# 2D sine-cosine position embedding
|
| 185 |
+
# References:
|
| 186 |
+
# Transformer: https://github.com/tensorflow/models/blob/master/official/nlp/transformer/model_utils.py
|
| 187 |
+
# MoCo v3: https://github.com/facebookresearch/moco-v3
|
| 188 |
+
# --------------------------------------------------------
|
| 189 |
+
def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False):
|
| 190 |
+
"""
|
| 191 |
+
grid_size: int of the grid height and width
|
| 192 |
+
return:
|
| 193 |
+
pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
|
| 194 |
+
"""
|
| 195 |
+
grid_h = np.arange(grid_size, dtype=np.float32)
|
| 196 |
+
grid_w = np.arange(grid_size, dtype=np.float32)
|
| 197 |
+
grid = np.meshgrid(grid_w, grid_h) # here w goes first
|
| 198 |
+
grid = np.stack(grid, axis=0)
|
| 199 |
+
|
| 200 |
+
grid = grid.reshape([2, 1, grid_size, grid_size])
|
| 201 |
+
pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
|
| 202 |
+
if cls_token:
|
| 203 |
+
pos_embed = np.concatenate(
|
| 204 |
+
[np.zeros([1, embed_dim]), pos_embed], axis=0
|
| 205 |
+
)
|
| 206 |
+
return pos_embed
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def get_1d_sincos_pos_embed(embed_dim, t_size, cls_token=False):
|
| 210 |
+
"""
|
| 211 |
+
t_size: int of the temporal size
|
| 212 |
+
return:
|
| 213 |
+
pos_embed: [t_size, embed_dim] or [1+t_size, embed_dim] (w/ or w/o cls_token)
|
| 214 |
+
"""
|
| 215 |
+
grid_t = np.arange(t_size, dtype=np.float32)
|
| 216 |
+
pos_embed = get_1d_sincos_pos_embed_from_grid(embed_dim, grid_t)
|
| 217 |
+
if cls_token:
|
| 218 |
+
pos_embed = np.concatenate(
|
| 219 |
+
[np.zeros([1, embed_dim]), pos_embed], axis=0
|
| 220 |
+
)
|
| 221 |
+
return pos_embed
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
|
| 225 |
+
assert embed_dim % 2 == 0
|
| 226 |
+
|
| 227 |
+
# use half of dimensions to encode grid_h
|
| 228 |
+
emb_h = get_1d_sincos_pos_embed_from_grid(
|
| 229 |
+
embed_dim // 2, grid[0]
|
| 230 |
+
) # (H*W, D/2)
|
| 231 |
+
emb_w = get_1d_sincos_pos_embed_from_grid(
|
| 232 |
+
embed_dim // 2, grid[1]
|
| 233 |
+
) # (H*W, D/2)
|
| 234 |
+
|
| 235 |
+
emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)
|
| 236 |
+
return emb
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
|
| 240 |
+
"""
|
| 241 |
+
embed_dim: output dimension for each position
|
| 242 |
+
pos: a list of positions to be encoded: size (M,)
|
| 243 |
+
out: (M, D)
|
| 244 |
+
"""
|
| 245 |
+
assert embed_dim % 2 == 0
|
| 246 |
+
omega = np.arange(embed_dim // 2, dtype=np.float32)
|
| 247 |
+
omega /= embed_dim / 2.0
|
| 248 |
+
omega = 1.0 / 10000**omega # (D/2,)
|
| 249 |
+
|
| 250 |
+
pos = pos.reshape(-1) # (M,)
|
| 251 |
+
out = np.einsum("m,d->md", pos, omega) # (M, D/2), outer product
|
| 252 |
+
|
| 253 |
+
emb_sin = np.sin(out) # (M, D/2)
|
| 254 |
+
emb_cos = np.cos(out) # (M, D/2)
|
| 255 |
+
|
| 256 |
+
emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
|
| 257 |
+
return emb
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def interpolate_pos_embed(checkpoint_model, model, orig_t_size=4, pos_name='vision_encoder.pos_embed'):
|
| 261 |
+
if pos_name in checkpoint_model:
|
| 262 |
+
pos_embed_checkpoint = checkpoint_model[pos_name]
|
| 263 |
+
embedding_size = pos_embed_checkpoint.shape[-1] # channel dim
|
| 264 |
+
num_patches = model.patch_embed.num_patches #
|
| 265 |
+
num_extra_tokens = model.pos_embed.shape[-2] - num_patches # 0/1
|
| 266 |
+
|
| 267 |
+
# we use 4 frames for pretraining
|
| 268 |
+
new_t_size = model.T
|
| 269 |
+
# height (== width) for the checkpoint position embedding
|
| 270 |
+
orig_size = int(((pos_embed_checkpoint.shape[-2] - num_extra_tokens)//(orig_t_size)) ** 0.5)
|
| 271 |
+
# height (== width) for the new position embedding
|
| 272 |
+
new_size = int((num_patches // (new_t_size))** 0.5)
|
| 273 |
+
|
| 274 |
+
# class_token and dist_token are kept unchanged
|
| 275 |
+
if orig_t_size != new_t_size:
|
| 276 |
+
print(f"Temporal interpolate from {orig_t_size} to {new_t_size} ({pos_name})")
|
| 277 |
+
extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens]
|
| 278 |
+
# only the position tokens are interpolated
|
| 279 |
+
pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:]
|
| 280 |
+
# B, L, C -> B, T, HW, C -> BHW, C, T (B = 1)
|
| 281 |
+
pos_tokens = pos_tokens.view(1, orig_t_size, -1, embedding_size)
|
| 282 |
+
pos_tokens = pos_tokens.permute(0, 2, 3, 1).reshape(-1, embedding_size, orig_t_size)
|
| 283 |
+
pos_tokens = torch.nn.functional.interpolate(pos_tokens, size=new_t_size, mode='linear')
|
| 284 |
+
pos_tokens = pos_tokens.view(1, -1, embedding_size, new_t_size)
|
| 285 |
+
pos_tokens = pos_tokens.permute(0, 3, 1, 2).reshape(1, -1, embedding_size)
|
| 286 |
+
new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1)
|
| 287 |
+
checkpoint_model[pos_name] = new_pos_embed
|
| 288 |
+
pos_embed_checkpoint = new_pos_embed
|
| 289 |
+
|
| 290 |
+
# class_token and dist_token are kept unchanged
|
| 291 |
+
if orig_size != new_size:
|
| 292 |
+
print(f"Position interpolate from {orig_size}x{orig_size} to {new_size}x{new_size} ({pos_name})")
|
| 293 |
+
extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens]
|
| 294 |
+
# only the position tokens are interpolated
|
| 295 |
+
pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:]
|
| 296 |
+
# B, L, C -> BT, H, W, C -> BT, C, H, W
|
| 297 |
+
pos_tokens = pos_tokens.reshape(-1, new_t_size, orig_size, orig_size, embedding_size)
|
| 298 |
+
pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, embedding_size).permute(0, 3, 1, 2)
|
| 299 |
+
pos_tokens = torch.nn.functional.interpolate(
|
| 300 |
+
pos_tokens, size=(new_size, new_size), mode='bicubic', align_corners=False)
|
| 301 |
+
# BT, C, H, W -> BT, H, W, C -> B, T, H, W, C
|
| 302 |
+
pos_tokens = pos_tokens.permute(0, 2, 3, 1).reshape(-1, new_t_size, new_size, new_size, embedding_size)
|
| 303 |
+
pos_tokens = pos_tokens.flatten(1, 3) # B, L, C
|
| 304 |
+
new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1)
|
| 305 |
+
checkpoint_model[pos_name] = new_pos_embed
|
| 306 |
+
else:
|
| 307 |
+
raise NotImplementedError
|
| 308 |
+
|
| 309 |
+
import math
|
| 310 |
+
import torch
|
| 311 |
+
import torch.nn.functional as F
|
| 312 |
+
from timm.models.layers import DropPath, to_2tuple, trunc_normal_
|
| 313 |
+
from timm.models.registry import register_model
|
| 314 |
+
from torch import nn
|
| 315 |
+
|
| 316 |
+
import torch.utils.checkpoint as checkpoint
|
| 317 |
+
from functools import partial
|
| 318 |
+
from einops import rearrange
|
| 319 |
+
|
| 320 |
+
from flash_attn.modules.mlp import FusedMLP
|
| 321 |
+
from flash_attn.ops.rms_norm import DropoutAddRMSNorm
|
| 322 |
+
|
| 323 |
+
import einops
|
| 324 |
+
|
| 325 |
+
class CrossAttention(nn.Module):
|
| 326 |
+
def __init__(
|
| 327 |
+
self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.,
|
| 328 |
+
proj_drop=0., attn_head_dim=None, out_dim=None):
|
| 329 |
+
super().__init__()
|
| 330 |
+
if out_dim is None:
|
| 331 |
+
out_dim = dim
|
| 332 |
+
self.num_heads = num_heads
|
| 333 |
+
head_dim = dim // num_heads
|
| 334 |
+
if attn_head_dim is not None:
|
| 335 |
+
head_dim = attn_head_dim
|
| 336 |
+
all_head_dim = head_dim * self.num_heads
|
| 337 |
+
self.scale = qk_scale or head_dim ** -0.5
|
| 338 |
+
assert all_head_dim == dim
|
| 339 |
+
|
| 340 |
+
self.q = nn.Linear(dim, all_head_dim, bias=False)
|
| 341 |
+
self.k = nn.Linear(dim, all_head_dim, bias=False)
|
| 342 |
+
self.v = nn.Linear(dim, all_head_dim, bias=False)
|
| 343 |
+
|
| 344 |
+
if qkv_bias:
|
| 345 |
+
self.q_bias = nn.Parameter(torch.zeros(all_head_dim))
|
| 346 |
+
self.k_bias = nn.Parameter(torch.zeros(all_head_dim))
|
| 347 |
+
self.v_bias = nn.Parameter(torch.zeros(all_head_dim))
|
| 348 |
+
else:
|
| 349 |
+
self.q_bias = None
|
| 350 |
+
self.k_bias = None
|
| 351 |
+
self.v_bias = None
|
| 352 |
+
|
| 353 |
+
self.attn_drop = nn.Dropout(attn_drop)
|
| 354 |
+
self.proj = nn.Linear(all_head_dim, out_dim)
|
| 355 |
+
self.proj_drop = nn.Dropout(proj_drop)
|
| 356 |
+
|
| 357 |
+
def forward(self, x, k=None, v=None):
|
| 358 |
+
B, N, C = x.shape
|
| 359 |
+
N_k = k.shape[1]
|
| 360 |
+
N_v = v.shape[1]
|
| 361 |
+
|
| 362 |
+
q_bias, k_bias, v_bias = None, None, None
|
| 363 |
+
if self.q_bias is not None:
|
| 364 |
+
q_bias = self.q_bias
|
| 365 |
+
k_bias = self.k_bias
|
| 366 |
+
v_bias = self.v_bias
|
| 367 |
+
|
| 368 |
+
q = F.linear(input=x, weight=self.q.weight, bias=q_bias)
|
| 369 |
+
q = q.reshape(B, N, 1, self.num_heads, -1).permute(2, 0, 3, 1, 4).squeeze(0) # (B, N_head, N_q, dim)
|
| 370 |
+
|
| 371 |
+
k = F.linear(input=k, weight=self.k.weight, bias=k_bias)
|
| 372 |
+
k = k.reshape(B, N_k, 1, self.num_heads, -1).permute(2, 0, 3, 1, 4).squeeze(0)
|
| 373 |
+
|
| 374 |
+
v = F.linear(input=v, weight=self.v.weight, bias=v_bias)
|
| 375 |
+
v = v.reshape(B, N_v, 1, self.num_heads, -1).permute(2, 0, 3, 1, 4).squeeze(0)
|
| 376 |
+
|
| 377 |
+
q = q * self.scale
|
| 378 |
+
attn = (q @ k.transpose(-2, -1)) # (B, N_head, N_q, N_k)
|
| 379 |
+
|
| 380 |
+
attn = attn.softmax(dim=-1)
|
| 381 |
+
attn = self.attn_drop(attn)
|
| 382 |
+
|
| 383 |
+
x = (attn @ v).transpose(1, 2).reshape(B, N, -1)
|
| 384 |
+
x = self.proj(x)
|
| 385 |
+
x = self.proj_drop(x)
|
| 386 |
+
|
| 387 |
+
return x
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
class AttentiveBlock(nn.Module):
|
| 391 |
+
|
| 392 |
+
def __init__(self, dim, num_heads, qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
|
| 393 |
+
drop_path=0., norm_layer=nn.LayerNorm, attn_head_dim=None, out_dim=None):
|
| 394 |
+
super().__init__()
|
| 395 |
+
|
| 396 |
+
self.norm1_q = norm_layer(dim)
|
| 397 |
+
self.norm1_k = norm_layer(dim)
|
| 398 |
+
self.norm1_v = norm_layer(dim)
|
| 399 |
+
self.cross_attn = CrossAttention(
|
| 400 |
+
dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop,
|
| 401 |
+
proj_drop=drop, attn_head_dim=attn_head_dim, out_dim=out_dim)
|
| 402 |
+
|
| 403 |
+
if drop_path > 0.:
|
| 404 |
+
print(f"Use DropPath in projector: {drop_path}")
|
| 405 |
+
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
|
| 406 |
+
|
| 407 |
+
def forward(self, x_q, x_kv, pos_q, pos_k, bool_masked_pos, rel_pos_bias=None):
|
| 408 |
+
x_q = self.norm1_q(x_q + pos_q)
|
| 409 |
+
x_k = self.norm1_k(x_kv + pos_k)
|
| 410 |
+
x_v = self.norm1_v(x_kv)
|
| 411 |
+
x = self.cross_attn(x_q, k=x_k, v=x_v)
|
| 412 |
+
|
| 413 |
+
return x
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
class AttentionPoolingBlock(AttentiveBlock):
|
| 417 |
+
|
| 418 |
+
def forward(self, x):
|
| 419 |
+
x_q = x.mean(1, keepdim=True)
|
| 420 |
+
x_kv, pos_q, pos_k = x, 0, 0
|
| 421 |
+
x = super().forward(x_q, x_kv, pos_q, pos_k, bool_masked_pos=None, rel_pos_bias=None)
|
| 422 |
+
x = x.squeeze(1)
|
| 423 |
+
return x
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
class RMSNorm(nn.Module):
|
| 427 |
+
def __init__(self, hidden_size, eps=1e-6):
|
| 428 |
+
super().__init__()
|
| 429 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 430 |
+
self.variance_epsilon = eps
|
| 431 |
+
|
| 432 |
+
def forward(self, hidden_states):
|
| 433 |
+
input_dtype = hidden_states.dtype
|
| 434 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 435 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 436 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 437 |
+
return self.weight * hidden_states.to(input_dtype)
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
class LayerScale(nn.Module):
|
| 441 |
+
def __init__(self, dim, init_values=1e-5, inplace=False, force_fp32=False):
|
| 442 |
+
super().__init__()
|
| 443 |
+
self.inplace = inplace
|
| 444 |
+
self.lr_scale = nn.Parameter(init_values * torch.ones(dim))
|
| 445 |
+
self.force_fp32 = force_fp32
|
| 446 |
+
|
| 447 |
+
@torch.cuda.amp.autocast(enabled=False)
|
| 448 |
+
def forward(self, x):
|
| 449 |
+
if self.force_fp32:
|
| 450 |
+
output_type = x.dtype
|
| 451 |
+
out = x.float().mul_(self.lr_scale.float()) if self.inplace else x.float() * self.lr_scale.float()
|
| 452 |
+
return out.to(dtype=output_type)
|
| 453 |
+
else:
|
| 454 |
+
out = x.mul_(self.lr_scale) if self.inplace else x * self.lr_scale
|
| 455 |
+
return out
|
| 456 |
+
|
| 457 |
+
|
| 458 |
+
class Attention(nn.Module):
|
| 459 |
+
def __init__(self, dim, num_heads=8, qkv_bias=False, attn_drop=0., proj_drop=0., use_flash_attn=False,
|
| 460 |
+
causal=False, norm_layer=nn.LayerNorm, qk_normalization=False, use_fused_rmsnorm=False):
|
| 461 |
+
super().__init__()
|
| 462 |
+
assert dim % num_heads == 0, 'dim should be divisible by num_heads'
|
| 463 |
+
self.num_heads = num_heads
|
| 464 |
+
head_dim = dim // num_heads
|
| 465 |
+
self.scale = head_dim ** -0.5
|
| 466 |
+
|
| 467 |
+
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
|
| 468 |
+
self.attn_drop = nn.Dropout(attn_drop)
|
| 469 |
+
self.proj = nn.Linear(dim, dim)
|
| 470 |
+
self.proj_drop = nn.Dropout(proj_drop)
|
| 471 |
+
|
| 472 |
+
self.use_flash_attn = use_flash_attn
|
| 473 |
+
if use_flash_attn:
|
| 474 |
+
self.causal = causal
|
| 475 |
+
self.inner_attn = FlashAttention(attention_dropout=attn_drop)
|
| 476 |
+
|
| 477 |
+
self.qk_normalization = qk_normalization
|
| 478 |
+
self.q_norm = norm_layer(dim) if qk_normalization else nn.Identity()
|
| 479 |
+
self.k_norm = norm_layer(dim) if qk_normalization else nn.Identity()
|
| 480 |
+
self.use_fused_rmsnorm = use_fused_rmsnorm
|
| 481 |
+
|
| 482 |
+
def _naive_attn(self, x):
|
| 483 |
+
B, N, C = x.shape
|
| 484 |
+
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
|
| 485 |
+
q, k, v = qkv.unbind(0) # make torchscript happy (cannot use tensor as tuple)
|
| 486 |
+
|
| 487 |
+
if self.qk_normalization:
|
| 488 |
+
B_, H_, N_, D_ = q.shape
|
| 489 |
+
q = self.q_norm(q.transpose(1, 2).flatten(-2, -1)).view(B_, N_, H_, D_).transpose(1, 2)
|
| 490 |
+
k = self.k_norm(k.transpose(1, 2).flatten(-2, -1)).view(B_, N_, H_, D_).transpose(1, 2)
|
| 491 |
+
|
| 492 |
+
attn = ((q * self.scale) @ k.transpose(-2, -1))
|
| 493 |
+
# attn = attn - attn.max(-1)[0].unsqueeze(-1) # in case of overflow for fp16
|
| 494 |
+
attn = attn.softmax(dim=-1)
|
| 495 |
+
attn = self.attn_drop(attn)
|
| 496 |
+
|
| 497 |
+
x = (attn @ v).transpose(1, 2).reshape(B, N, C)
|
| 498 |
+
x = self.proj(x)
|
| 499 |
+
x = self.proj_drop(x)
|
| 500 |
+
return x
|
| 501 |
+
|
| 502 |
+
def _flash_attn(self, x, key_padding_mask=None, need_weights=False):
|
| 503 |
+
|
| 504 |
+
qkv = self.qkv(x)
|
| 505 |
+
qkv = rearrange(qkv, "b s (three h d) -> b s three h d", three=3, h=self.num_heads)
|
| 506 |
+
|
| 507 |
+
if self.qk_normalization:
|
| 508 |
+
q, k, v = qkv.unbind(2)
|
| 509 |
+
if self.use_fused_rmsnorm:
|
| 510 |
+
q = self.q_norm(q.flatten(-2, -1))[0].view(q.shape)
|
| 511 |
+
k = self.k_norm(k.flatten(-2, -1))[0].view(k.shape)
|
| 512 |
+
else:
|
| 513 |
+
q = self.q_norm(q.flatten(-2, -1)).view(q.shape)
|
| 514 |
+
k = self.k_norm(k.flatten(-2, -1)).view(k.shape)
|
| 515 |
+
qkv = torch.stack([q, k, v], dim=2)
|
| 516 |
+
|
| 517 |
+
context, _ = self.inner_attn(
|
| 518 |
+
qkv, key_padding_mask=key_padding_mask, need_weights=need_weights, causal=self.causal
|
| 519 |
+
)
|
| 520 |
+
outs = self.proj(rearrange(context, "b s h d -> b s (h d)"))
|
| 521 |
+
outs = self.proj_drop(outs)
|
| 522 |
+
return outs
|
| 523 |
+
|
| 524 |
+
def forward(self, x):
|
| 525 |
+
x = self._naive_attn(x) if not self.use_flash_attn else self._flash_attn(x)
|
| 526 |
+
return x
|
| 527 |
+
|
| 528 |
+
|
| 529 |
+
class Mlp(nn.Module):
|
| 530 |
+
""" MLP as used in Vision Transformer, MLP-Mixer and related networks
|
| 531 |
+
"""
|
| 532 |
+
|
| 533 |
+
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU,
|
| 534 |
+
bias=True, drop=0.):
|
| 535 |
+
super().__init__()
|
| 536 |
+
out_features = out_features or in_features
|
| 537 |
+
hidden_features = hidden_features or in_features
|
| 538 |
+
bias = to_2tuple(bias)
|
| 539 |
+
drop_probs = to_2tuple(drop)
|
| 540 |
+
|
| 541 |
+
self.fc1 = nn.Linear(in_features, hidden_features, bias=bias[0])
|
| 542 |
+
self.act = act_layer()
|
| 543 |
+
self.drop1 = nn.Dropout(drop_probs[0])
|
| 544 |
+
self.fc2 = nn.Linear(hidden_features, out_features, bias=bias[1])
|
| 545 |
+
self.drop2 = nn.Dropout(drop_probs[1])
|
| 546 |
+
|
| 547 |
+
def forward(self, x):
|
| 548 |
+
x = self.fc1(x)
|
| 549 |
+
x = self.act(x)
|
| 550 |
+
x = self.drop1(x)
|
| 551 |
+
x = self.fc2(x)
|
| 552 |
+
x = self.drop2(x)
|
| 553 |
+
return x
|
| 554 |
+
|
| 555 |
+
|
| 556 |
+
class Block(nn.Module):
|
| 557 |
+
|
| 558 |
+
def __init__(
|
| 559 |
+
self, dim, num_heads, mlp_ratio=4., qkv_bias=False, drop=0., attn_drop=0., init_values=None,
|
| 560 |
+
drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, use_flash_attn=False, use_fused_mlp=False,
|
| 561 |
+
fused_mlp_heuristic=1, with_cp=False, qk_normalization=False, layerscale_no_force_fp32=False,
|
| 562 |
+
use_fused_rmsnorm=False):
|
| 563 |
+
super().__init__()
|
| 564 |
+
|
| 565 |
+
self.norm1 = norm_layer(dim)
|
| 566 |
+
self.attn = Attention(dim, num_heads=num_heads, qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop,
|
| 567 |
+
use_flash_attn=use_flash_attn, causal=False, norm_layer=norm_layer,
|
| 568 |
+
qk_normalization=qk_normalization,
|
| 569 |
+
use_fused_rmsnorm=use_fused_rmsnorm)
|
| 570 |
+
self.ls1 = LayerScale(dim, init_values=init_values,
|
| 571 |
+
force_fp32=(not layerscale_no_force_fp32)) if init_values else nn.Identity()
|
| 572 |
+
# NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
|
| 573 |
+
self.drop_path1 = DropPath(drop_path) if drop_path > 0. else nn.Identity()
|
| 574 |
+
|
| 575 |
+
self.norm2 = norm_layer(dim)
|
| 576 |
+
mlp_hidden_dim = int(dim * mlp_ratio)
|
| 577 |
+
if use_fused_mlp:
|
| 578 |
+
self.mlp = FusedMLP(in_features=dim, hidden_features=mlp_hidden_dim, heuristic=fused_mlp_heuristic)
|
| 579 |
+
else:
|
| 580 |
+
self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
|
| 581 |
+
self.ls2 = LayerScale(dim, init_values=init_values,
|
| 582 |
+
force_fp32=(not layerscale_no_force_fp32)) if init_values else nn.Identity()
|
| 583 |
+
self.drop_path2 = DropPath(drop_path) if drop_path > 0. else nn.Identity()
|
| 584 |
+
|
| 585 |
+
self.with_cp = with_cp
|
| 586 |
+
self.use_fused_rmsnorm = use_fused_rmsnorm
|
| 587 |
+
|
| 588 |
+
def forward(self, x, residual=None):
|
| 589 |
+
|
| 590 |
+
def _inner_forward(x, residual=None):
|
| 591 |
+
if self.use_fused_rmsnorm:
|
| 592 |
+
x, residual = self.norm1(x, residual)
|
| 593 |
+
x = self.drop_path1(self.ls1(self.attn(x)))
|
| 594 |
+
x, residual = self.norm2(x, residual)
|
| 595 |
+
x = self.drop_path2(self.ls2(self.mlp(x)))
|
| 596 |
+
return x, residual
|
| 597 |
+
else:
|
| 598 |
+
assert residual is None
|
| 599 |
+
x = x + self.drop_path1(self.ls1(self.attn(self.norm1(x))))
|
| 600 |
+
x = x + self.drop_path2(self.ls2(self.mlp(self.norm2(x))))
|
| 601 |
+
return x
|
| 602 |
+
|
| 603 |
+
if self.with_cp:
|
| 604 |
+
return checkpoint.checkpoint(_inner_forward, x, residual)
|
| 605 |
+
else:
|
| 606 |
+
return _inner_forward(x, residual=residual)
|
| 607 |
+
|
| 608 |
+
class PatchEmbed(nn.Module):
|
| 609 |
+
""" 3D Image to Patch Embedding
|
| 610 |
+
"""
|
| 611 |
+
|
| 612 |
+
def __init__(
|
| 613 |
+
self, img_size=224, patch_size=16, in_chans=3, embed_dim=768,
|
| 614 |
+
num_frames=8, tubelet_size=1, norm_layer=None
|
| 615 |
+
):
|
| 616 |
+
super().__init__()
|
| 617 |
+
img_size = to_2tuple(img_size)
|
| 618 |
+
patch_size = to_2tuple(patch_size)
|
| 619 |
+
self.img_size = img_size
|
| 620 |
+
self.patch_size = patch_size
|
| 621 |
+
self.tubelet_size = tubelet_size
|
| 622 |
+
self.grid_size = (
|
| 623 |
+
num_frames // tubelet_size,
|
| 624 |
+
img_size[0] // patch_size[0],
|
| 625 |
+
img_size[1] // patch_size[1]
|
| 626 |
+
) # (T, H, W)
|
| 627 |
+
self.num_patches = self.grid_size[0] * self.grid_size[1] * self.grid_size[2]
|
| 628 |
+
|
| 629 |
+
self.proj = nn.Conv3d(
|
| 630 |
+
in_channels=in_chans, out_channels=embed_dim,
|
| 631 |
+
kernel_size=(tubelet_size, patch_size[0], patch_size[1]),
|
| 632 |
+
stride=(tubelet_size, patch_size[0], patch_size[1])
|
| 633 |
+
)
|
| 634 |
+
|
| 635 |
+
self.norm = norm_layer(embed_dim)
|
| 636 |
+
self.norm_before = norm_layer(tubelet_size * math.prod(patch_size) * 3)
|
| 637 |
+
|
| 638 |
+
def forward(self, x):
|
| 639 |
+
B, C, T, H, W = x.shape
|
| 640 |
+
x = x.permute(0, 2, 3, 4, 1)
|
| 641 |
+
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])
|
| 642 |
+
x = self.norm_before(x) # x.shape: [B, T, HW, C]
|
| 643 |
+
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])
|
| 644 |
+
x = x.permute(0, 4, 1, 2, 3)
|
| 645 |
+
x = self.proj(x)
|
| 646 |
+
x = x.flatten(3).permute(0, 2, 3, 1)
|
| 647 |
+
x = self.norm(x)
|
| 648 |
+
return x
|
| 649 |
+
|
| 650 |
+
|
| 651 |
+
class InternVideoNextBackbone(nn.Module):
|
| 652 |
+
def __init__(
|
| 653 |
+
self,
|
| 654 |
+
in_chans: int = 3,
|
| 655 |
+
patch_size: int = 14,
|
| 656 |
+
img_size: int = 224,
|
| 657 |
+
qkv_bias: bool = False,
|
| 658 |
+
drop_path_rate: float = 0.25,
|
| 659 |
+
embed_dim: int = 1408,
|
| 660 |
+
head_drop_path_rate: float = 0.,
|
| 661 |
+
num_heads: int = 16,
|
| 662 |
+
mlp_ratio: float = 4.3637,
|
| 663 |
+
init_values: float = 1e-5,
|
| 664 |
+
qk_normalization: bool = True,
|
| 665 |
+
depth: int = 40,
|
| 666 |
+
use_flash_attn: bool = True,
|
| 667 |
+
use_fused_rmsnorm: bool = True,
|
| 668 |
+
use_fused_mlp: bool = True,
|
| 669 |
+
fused_mlp_heuristic: int = 1,
|
| 670 |
+
attn_pool_num_heads: int = 16,
|
| 671 |
+
clip_embed_dim: int = 768,
|
| 672 |
+
layerscale_no_force_fp32: bool = False,
|
| 673 |
+
num_frames: int = 16,
|
| 674 |
+
tubelet_size: int = 1,
|
| 675 |
+
sep_pos_embed: bool = False,
|
| 676 |
+
use_checkpoint: bool = False,
|
| 677 |
+
checkpoint_num: int = 0,
|
| 678 |
+
cls_token_num: int = 4,
|
| 679 |
+
):
|
| 680 |
+
super().__init__()
|
| 681 |
+
self.cls_token_num = cls_token_num
|
| 682 |
+
assert use_flash_attn == use_fused_rmsnorm == use_fused_mlp, print(
|
| 683 |
+
'use_flash_attn, use_fused_rmsnorm and use_fused_mlp should be consistent')
|
| 684 |
+
print(mlp_ratio)
|
| 685 |
+
|
| 686 |
+
self.use_flash_attn = use_flash_attn
|
| 687 |
+
self.embed_dim = embed_dim
|
| 688 |
+
|
| 689 |
+
if use_fused_rmsnorm:
|
| 690 |
+
norm_layer_for_blocks = partial(DropoutAddRMSNorm, eps=1e-6, prenorm=True)
|
| 691 |
+
else:
|
| 692 |
+
norm_layer_for_blocks = partial(RMSNorm, eps=1e-6)
|
| 693 |
+
self.norm_layer_for_blocks = norm_layer_for_blocks
|
| 694 |
+
self.patch_embed = PatchEmbed(
|
| 695 |
+
img_size, patch_size, in_chans, embed_dim,
|
| 696 |
+
num_frames=num_frames, tubelet_size=tubelet_size, norm_layer=partial(RMSNorm, eps=1e-6)
|
| 697 |
+
)
|
| 698 |
+
num_patches = self.patch_embed.num_patches
|
| 699 |
+
self.cls_token = nn.Parameter(torch.zeros(1, cls_token_num, embed_dim))
|
| 700 |
+
|
| 701 |
+
self.sep_pos_embed = sep_pos_embed
|
| 702 |
+
if sep_pos_embed:
|
| 703 |
+
print("Use seperable position embedding")
|
| 704 |
+
grid_size = self.patch_embed.grid_size
|
| 705 |
+
self.grid_size = grid_size
|
| 706 |
+
self.pos_embed_spatial = nn.Parameter(torch.zeros(1, grid_size[1] * grid_size[2], embed_dim))
|
| 707 |
+
self.pos_embed_temporal = nn.Parameter(torch.zeros(1, grid_size[0], embed_dim))
|
| 708 |
+
self.pos_embed_cls = nn.Parameter(torch.zeros(1, 1, embed_dim))
|
| 709 |
+
else:
|
| 710 |
+
print("Use joint position embedding")
|
| 711 |
+
self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + cls_token_num, embed_dim))
|
| 712 |
+
|
| 713 |
+
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)]
|
| 714 |
+
# choose which layer to use checkpoint
|
| 715 |
+
with_cp_list = [False] * depth
|
| 716 |
+
if use_checkpoint:
|
| 717 |
+
for idx in range(depth):
|
| 718 |
+
if idx < checkpoint_num:
|
| 719 |
+
with_cp_list[idx] = True
|
| 720 |
+
print(f"Droppath rate: {dpr}")
|
| 721 |
+
print(f"Checkpoint list: {with_cp_list}")
|
| 722 |
+
|
| 723 |
+
self.blocks = nn.ModuleList([
|
| 724 |
+
Block(embed_dim, num_heads, mlp_ratio, qkv_bias=qkv_bias,
|
| 725 |
+
norm_layer=norm_layer_for_blocks,
|
| 726 |
+
drop_path=dpr[i], init_values=init_values, attn_drop=0.,
|
| 727 |
+
use_flash_attn=use_flash_attn, use_fused_mlp=use_fused_mlp,
|
| 728 |
+
fused_mlp_heuristic=fused_mlp_heuristic,
|
| 729 |
+
with_cp=with_cp_list[i],
|
| 730 |
+
qk_normalization=qk_normalization,
|
| 731 |
+
layerscale_no_force_fp32=layerscale_no_force_fp32,
|
| 732 |
+
use_fused_rmsnorm=use_fused_rmsnorm)
|
| 733 |
+
for i in range(depth)])
|
| 734 |
+
self.clip_projector = AttentionPoolingBlock(
|
| 735 |
+
dim=embed_dim, num_heads=attn_pool_num_heads, qkv_bias=True, qk_scale=None,
|
| 736 |
+
drop=0., attn_drop=0., drop_path=head_drop_path_rate,
|
| 737 |
+
norm_layer=partial(nn.LayerNorm, eps=1e-5), out_dim=clip_embed_dim
|
| 738 |
+
)
|
| 739 |
+
|
| 740 |
+
self.init_pos_embed()
|
| 741 |
+
trunc_normal_(self.cls_token, std=.02)
|
| 742 |
+
self.apply(self._init_weights)
|
| 743 |
+
self.fix_init_weight()
|
| 744 |
+
|
| 745 |
+
def init_pos_embed(self):
|
| 746 |
+
print("Init pos_embed from sincos pos_embed")
|
| 747 |
+
if self.sep_pos_embed:
|
| 748 |
+
pos_embed_spatial = get_2d_sincos_pos_embed(
|
| 749 |
+
self.pos_embed_spatial.shape[-1],
|
| 750 |
+
self.patch_embed.grid_size[1], # height & weight
|
| 751 |
+
)
|
| 752 |
+
self.pos_embed_spatial.data.copy_(torch.from_numpy(pos_embed_spatial).float().unsqueeze(0))
|
| 753 |
+
pos_embed_temporal = get_1d_sincos_pos_embed(
|
| 754 |
+
self.pos_embed_spatial.shape[-1],
|
| 755 |
+
self.patch_embed.grid_size[0], # t_size
|
| 756 |
+
)
|
| 757 |
+
self.pos_embed_temporal.data.copy_(torch.from_numpy(pos_embed_temporal).float().unsqueeze(0))
|
| 758 |
+
else:
|
| 759 |
+
pos_embed = get_3d_sincos_pos_embed(
|
| 760 |
+
self.pos_embed.shape[-1],
|
| 761 |
+
self.patch_embed.grid_size[1], # height & weight
|
| 762 |
+
self.patch_embed.grid_size[0], # t_size
|
| 763 |
+
cls_token=True,
|
| 764 |
+
cls_token_num=self.cls_token_num
|
| 765 |
+
)
|
| 766 |
+
self.pos_embed.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0))
|
| 767 |
+
|
| 768 |
+
def _init_weights(self, m):
|
| 769 |
+
if isinstance(m, nn.Linear):
|
| 770 |
+
trunc_normal_(m.weight, std=.02)
|
| 771 |
+
if isinstance(m, nn.Linear) and m.bias is not None:
|
| 772 |
+
nn.init.constant_(m.bias, 0)
|
| 773 |
+
elif isinstance(m, nn.LayerNorm):
|
| 774 |
+
nn.init.constant_(m.bias, 0)
|
| 775 |
+
nn.init.constant_(m.weight, 1.0)
|
| 776 |
+
|
| 777 |
+
def fix_init_weight(self):
|
| 778 |
+
def rescale(param, layer_id):
|
| 779 |
+
param.div_(math.sqrt(2.0 * layer_id))
|
| 780 |
+
|
| 781 |
+
for layer_id, layer in enumerate(self.blocks):
|
| 782 |
+
rescale(layer.attn.proj.weight.data, layer_id + 1)
|
| 783 |
+
rescale(layer.mlp.fc2.weight.data, layer_id + 1)
|
| 784 |
+
|
| 785 |
+
@property
|
| 786 |
+
def dtype(self):
|
| 787 |
+
return self.patch_embed.proj.weight.dtype
|
| 788 |
+
|
| 789 |
+
def get_num_layers(self):
|
| 790 |
+
return len(self.blocks)
|
| 791 |
+
|
| 792 |
+
@torch.jit.ignore
|
| 793 |
+
def no_weight_decay(self):
|
| 794 |
+
return {
|
| 795 |
+
'pos_embed',
|
| 796 |
+
'pos_embed_spatial',
|
| 797 |
+
'pos_embed_temporal',
|
| 798 |
+
'pos_embed_cls',
|
| 799 |
+
'cls_token'
|
| 800 |
+
}
|
| 801 |
+
|
| 802 |
+
def forward(self, x, projected=False):
|
| 803 |
+
x = self.patch_embed(x.type(self.dtype))
|
| 804 |
+
B, T, L, C = x.shape # T: temporal; L: spatial
|
| 805 |
+
x = x.view([B, T * L, C])
|
| 806 |
+
|
| 807 |
+
# append cls token
|
| 808 |
+
cls_tokens = self.cls_token.expand(B, -1, -1)
|
| 809 |
+
x = torch.cat((cls_tokens, x), dim=1)
|
| 810 |
+
|
| 811 |
+
# add pos_embed
|
| 812 |
+
if self.sep_pos_embed:
|
| 813 |
+
pos_embed = self.pos_embed_spatial.repeat(
|
| 814 |
+
1, self.grid_size[0], 1
|
| 815 |
+
) + torch.repeat_interleave(
|
| 816 |
+
self.pos_embed_temporal,
|
| 817 |
+
self.grid_size[1] * self.grid_size[2],
|
| 818 |
+
dim=1,
|
| 819 |
+
)
|
| 820 |
+
pos_embed = torch.cat(
|
| 821 |
+
[
|
| 822 |
+
self.pos_embed_cls.expand(pos_embed.shape[0], -1, -1),
|
| 823 |
+
pos_embed,
|
| 824 |
+
],
|
| 825 |
+
1,
|
| 826 |
+
)
|
| 827 |
+
else:
|
| 828 |
+
pos_embed = self.pos_embed
|
| 829 |
+
x = x + pos_embed
|
| 830 |
+
|
| 831 |
+
residual = None
|
| 832 |
+
for blk in self.blocks:
|
| 833 |
+
if isinstance(x, tuple) and len(x) == 2:
|
| 834 |
+
x, residual = x
|
| 835 |
+
x = blk(x, residual=residual)
|
| 836 |
+
if isinstance(x, tuple) and len(x) == 2:
|
| 837 |
+
x, residual = x
|
| 838 |
+
if residual is not None:
|
| 839 |
+
x = x + residual
|
| 840 |
+
|
| 841 |
+
if projected:
|
| 842 |
+
return self.clip_projector(x)
|
| 843 |
+
|
| 844 |
+
return x[:, self.cls_token_num:, :]
|
| 845 |
+
|
| 846 |
+
|
| 847 |
+
@register_model
|
| 848 |
+
def internvideo_next_base_patch14_224(pretrained=False, **kwargs):
|
| 849 |
+
model = InternVideoNextBackbone(
|
| 850 |
+
img_size=224, patch_size=14, embed_dim=768,
|
| 851 |
+
depth=12, num_heads=12, mlp_ratio=4,
|
| 852 |
+
attn_pool_num_heads=16, clip_embed_dim=768,
|
| 853 |
+
**kwargs
|
| 854 |
+
)
|
| 855 |
+
return model
|
| 856 |
+
|
| 857 |
+
@register_model
|
| 858 |
+
def internvideo_next_large_patch14_224(pretrained=False, **kwargs):
|
| 859 |
+
model = InternVideoNextBackbone(
|
| 860 |
+
img_size=224, patch_size=14, embed_dim=1024,
|
| 861 |
+
depth=24, num_heads=16, mlp_ratio=4,
|
| 862 |
+
attn_pool_num_heads=16, clip_embed_dim=768,
|
| 863 |
+
**kwargs
|
| 864 |
+
)
|
| 865 |
+
return model
|
| 866 |
+
|
| 867 |
+
from transformers import AutoConfig, PreTrainedModel
|
| 868 |
+
from .modeling_config import InternVideoNextConfig
|
| 869 |
+
import logging
|
| 870 |
+
logger = logging.getLogger(__name__)
|
| 871 |
+
|
| 872 |
+
class InternVideoNext(PreTrainedModel):
|
| 873 |
+
config_class = InternVideoNextConfig
|
| 874 |
+
def __init__(self, config=None):
|
| 875 |
+
super().__init__(config=config)
|
| 876 |
+
self.model_config = config.model_config
|
| 877 |
+
logger.info("Model config: {}".format(self.model_config))
|
| 878 |
+
self.model = InternVideoNextBackbone(**self.model_config)
|
| 879 |
+
|
| 880 |
+
def forward(self, pixel_values):
|
| 881 |
+
return self.model(pixel_values, projected=True)
|
| 882 |
+
|
| 883 |
+
def extract_features(self, pixel_values):
|
| 884 |
+
return self.model(pixel_values)
|