分析:① # Copyright (c) 2015-present, Facebook, Inc. All… · The Chat Archive
Explore / Programming 分析:① # Copyright (c) 2015-present, Facebook, Inc. All rights reserved. import torch… Save Share Download ▾ ReportJump to turn (17) 1 分析:① # Copyright (c) 2015-present, Facebook, Inc. All rights reserved. import to 2 但是②中虽然增加了resnet特征提取模块,但是还是得保留①中的 def forward(self, staticz, dynamicz, x, returnf 3 那么在import torch import torch.nn as nn import numpy as np import torchvision from 4 那么在# Copyright (c) 2015-present, Facebook, Inc. All rights reserved. import torc 5 原始模型是:# Copyright (c) 2015-present, Facebook, Inc. All rights reserved. import t 6 class Vencoder(nn.Module): def init(self, embsize, featuresize): super(Vencoder, 7 那么综上,在# Copyright (c) 2015-present, Facebook, Inc. All rights reserved. import t 8 现在对比:① class ResNetExtractor(nn.Module): def init(self, resnettype ="resnet18"): 9 那么现在的研究目标是跟踪任务,且数据后续需要采用mamba处理数据,那么采用哪个resnet类更合适? 10 global definition UNKTOKEN = " " PADTOKEN = " " BOSTOKEN = " " EOSTOKEN = " " SI 11 综上,ResNetExtractor 类 和 resnet 类区别是什么? 12 分析:① # Copyright (c) 2015-present, Facebook, Inc. All rights reserved. import to 13 是这样,createblock 在# Copyright (c) 2015-present, Facebook, Inc. All rights reserve 14 当前模型:# Copyright (c) 2015-present, Facebook, Inc. All rights reserved. import to 15 现在我们需要确定,是否调用了Resnet网络处理,应该如何设置? 16 将# Copyright (c) 2015-present, Facebook, Inc. All rights reserved. import torch 17 import torch import torch.nn as nn import numpy as np import torchvision from tr Copy first prompt
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 17 (34 messages)
Language zh
Conversation date Sep 9, 2024
Added to archive Nov 16, 2026
ID 01m7h41tq1qst6tn4y0cn5596mSource & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: 93bc8595f0e015a7655d0f50a7baa061
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
分析:① # Copyright (c) 2015-present, Facebook, Inc.
All rights reserved.
import torch
import torch.nn as nn
from functools import partial
from torch import Tensor
from typing import Optional
from timm.models.vision_transformer import VisionTransformer, cfg
from timm.models.registry import register_model
from timm.models.layers import trunc_normal , lecun_normal_
from timm.models.layers import DropPath, to_2tuple
from timm.models.vision_transformer import _load_weights
import math
from collections import namedtuple
from mamba_ssm.modules.mamba_simple import Mamba
from mamba_ssm.utils.generation import GenerationMixin
from mamba_ssm.utils.hf import load_config_hf, load_state_dict_hf
from lib.models.ostrack.rope import *
import random
from lib.models.layers.head import build_box_head
import importlib
import lib.train.admin.settings as ws_settings
from .utils import combine_tokens, recover_tokens
try:
from mamba_ssm.ops.triton.layernorm import RMSNorm, layer_norm_fn, rms_norm_fn
except ImportError:
RMSNorm, layer_norm_fn, rms_norm_fn = None, None, None
all = [
'vim_tiny_patch16_224', 'vim_small_patch16_224', 'vim_base_patch16_224',
'vim_tiny_patch16_384', 'vim_small_patch16_384', 'vim_base_patch16_384',
]
class PatchEmbed(nn.Module):
""" 2D Image to Patch Embedding
"""
def init (self, img_size=224, patch_size=16, stride=16, in_chans=3, embed_dim=768, norm_layer=None, flatten=True):
super().init ()
img_size = to_2tuple(img_size)
patch_size = to_2tuple(patch_size)
self.img_size = img_size
self.patch_size = patch_size
self.grid_size = ((img_size[0] - patch_size[0]) // stride + 1, (img_size[1] - patch_size[1]) // stride + 1)
self.num_patches = self.grid_size[0] * self.grid_size[1]
self.flatten = flatten
code Copy code
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=stride)
self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
def forward(self, x):
B, C, H, W = x.shape
# print('11x.shape:', x.shape) # 11x.shape: torch.Size([2, 3, 128, 128])
# assert H == self.img_size[0] and W == self.img_size[1], \
# f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
x = self.proj(x)
if self.flatten:
x = x.flatten(2).transpose(1, 2) # BCHW -> BNC
x = self.norm(x)
return x
class Block(nn.Module):
def init (
self, dim, mixer_cls, norm_cls=nn.LayerNorm, fused_add_norm=False, residual_in_fp32=False,drop_path=0.,
):
"""
Simple block wrapping a mixer class with LayerNorm/RMSNorm and residual connection"
code Copy code
This Block has a slightly different structure compared to a regular
prenorm Transformer block.
The standard block is: LN -> MHA/MLP -> Add.
[Ref: https://arxiv.org/abs/2002.04745]
Here we have: Add -> LN -> Mixer, returning both
the hidden_states (output of the mixer) and the residual.
This is purely for performance reasons, as we can fuse add and LayerNorm.
The residual needs to be provided (except for the very first block).
"""
super().__init__()
self.residual_in_fp32 = residual_in_fp32
self.fused_add_norm = fused_add_norm
self.mixer = mixer_cls(dim)
self.norm = norm_cls(dim)
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
if self.fused_add_norm:
assert RMSNorm is not None, "RMSNorm import fails"
assert isinstance(
self.norm, (nn.LayerNorm, RMSNorm)
), "Only LayerNorm and RMSNorm are supported for fused_add_norm"
def forward(
self, hidden_states: Tensor, residual: Optional[Tensor] = None, inference_params=None
):
r"""Pass the input through the encoder layer.
Args:
hidden_states: the sequence to the encoder layer (required).
residual: hidden_states = Mixer(LN(residual))
"""
fused_add_norm_fn = rms_norm_fn if isinstance(self.norm, RMSNorm) else layer_norm_fn
hidden_states, residual = fused_add_norm_fn(
hidden_states,
self.norm.weight,
self.norm.bias,
residual=residual,
prenorm=True,
residual_in_fp32=self.residual_in_fp32,
eps=self.norm.eps,
)
hidden_states = self.mixer(hidden_states, inference_params=inference_params)
return hidden_states, residual
def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
return self.mixer.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs)
def create_block(
d_model,
ssm_cfg=None,
norm_epsilon=1e-5,
drop_path=0.,
rms_norm=False,
residual_in_fp32=False,
fused_add_norm=False,
layer_idx=None,
device=None,
dtype=None,
if_bimamba=False,
bimamba_type="none",
if_devide_out=False,
init_layer_scale=None,
):
if if_bimamba:
bimamba_type = "v1"
if ssm_cfg is None:
ssm_cfg = {}
factory_kwargs = {"device": device, "dtype": dtype}
mixer_cls = partial(Mamba, layer_idx=layer_idx, bimamba_type=bimamba_type, if_devide_out=if_devide_out, init_layer_scale=init_layer_scale, **ssm_cfg, **factory_kwargs)
norm_cls = partial(
nn.LayerNorm if not rms_norm else RMSNorm, eps=norm_epsilon, **factory_kwargs
)
block = Block(
d_model,
mixer_cls,
norm_cls=norm_cls,
drop_path=drop_path,
fused_add_norm=fused_add_norm,
residual_in_fp32=residual_in_fp32,
)
block.layer_idx = layer_idx
return block
def init_weights(
module,
n_layer,
initializer_range=0.02, # Now only used for embedding layer.
rescale_prenorm_residual=True,
n_residuals_per_layer=1, # Change to 2 if we have MLP
):
if isinstance(module, nn.Linear):
if module.bias is not None:
if not getattr(module.bias, "no_reinit", False):
nn.init.zeros (module.bias)
elif isinstance(module, nn.Embedding):
nn.init.normal (module.weight, std=initializer_range)
code Copy code
if rescale_prenorm_residual:
# Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
# > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
# > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
# > -- GPT-2 :: https://openai.com/blog/better-language-models/
#
# Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
for name, p in module.named_parameters():
if name in ["out_proj.weight", "fc2.weight"]:
# Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
# Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
# We need to reinit p since this code could be called multiple times
# Having just p *= scale would repeatedly scale it down
nn.init.kaiming_uniform_(p, a=math.sqrt(5))
with torch.no_grad():
p /= math.sqrt(n_residuals_per_layer * n_layer)
def segm_init_weights(m):
if isinstance(m, nn.Linear):
trunc_normal_(m.weight, std=0.02)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.Conv2d):
# NOTE conv was left to pytorch default in my original init
lecun_normal_(m.weight)
if m.bias is not None:
nn.init.zeros_(m.bias)
elif isinstance(m, (nn.LayerNorm, nn.GroupNorm, nn.BatchNorm2d)):
nn.init.zeros_(m.bias)
nn.init.ones_(m.weight)
class VisionMamba(nn.Module):
def init (self,
img_size=224,
patch_size=16,
stride=16,
depth=24,
embed_dim=192,
channels=3,
num_classes=1000,
ssm_cfg=None,
drop_rate=0.,
drop_path_rate=0.1,
norm_epsilon: float = 1e-5,
rms_norm: bool = False,
initializer_cfg=None,
fused_add_norm=False,
residual_in_fp32=False,
device=None,
dtype=None,
ft_seq_len=None,
pt_hw_seq_len=14,
if_bidirectional=False,
final_pool_type='none',
if_abs_pos_embed=False,
if_rope=False,
if_rope_residual=False,
flip_img_sequences_ratio=-1.,
if_bimamba=False,
bimamba_type="none",
if_cls_token=False,
if_devide_out=False,
init_layer_scale=None,
use_double_cls_token=False,
use_middle_cls_token=False,
**kwargs):
factory_kwargs = {"device": device, "dtype": dtype}
# add factory_kwargs into kwargs
kwargs.update(factory_kwargs)
super().init ()
self.residual_in_fp32 = residual_in_fp32
self.fused_add_norm = fused_add_norm
self.if_bidirectional = if_bidirectional
self.final_pool_type = final_pool_type
self.if_abs_pos_embed = if_abs_pos_embed
self.if_rope = if_rope
self.if_rope_residual = if_rope_residual
self.flip_img_sequences_ratio = flip_img_sequences_ratio
# self.if_cls_token = if_cls_token
self.if_cls_token = False
self.use_double_cls_token = use_double_cls_token
self.use_middle_cls_token = use_middle_cls_token
self.num_tokens = 1 if if_cls_token else 0
@register_model
def vim_tiny_patch16_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, embed_dim=192, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='mean', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
checkpoint = torch.hub.load_state_dict_from_url(
url="to.do",
map_location="cpu", check_hash=True
)
model.load_state_dict(checkpoint["model"])
return model
@register_model
def vim_tiny_patch16_stride8_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, stride=8, embed_dim=192, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='mean', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
checkpoint = torch.hub.load_state_dict_from_url(
url="to.do",
map_location="cpu", check_hash=True
)
model.load_state_dict(checkpoint["model"])
return model
LIGHT
@register_model
def vim_small_patch16_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, embed_dim=384, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='all', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
# checkpoint = torch.hub.load_state_dict_from_url(
# url="to.do",
# map_location="cpu", check_hash=True
# )
# model.load_state_dict(checkpoint["model"])
code Copy code
checkpoint = torch.load(pretrained, map_location="cpu")
missing_keys, unexpected_keys = model.load_state_dict(checkpoint["model"], strict=False)
print('Load pretrained model from: ' + pretrained)
return model
@register_model
def vim_small_patch16_stride8_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, stride=8, embed_dim=384, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='mean', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
checkpoint = torch.hub.load_state_dict_from_url(
url="to.do",
map_location="cpu", check_hash=True
)
model.load_state_dict(checkpoint["model"])
return model 和 ② # Copyright (c) 2015-present, Facebook, Inc.
All rights reserved.
import torch
import torch.nn as nn
from functools import partial
from torch import Tensor
from typing import Optional
from timm.models.vision_transformer import VisionTransformer, cfg
from timm.models.registry import register_model
from timm.models.layers import trunc_normal , lecun_normal_
from timm.models.layers import DropPath, to_2tuple
from timm.models.vision_transformer import _load_weights
import math
from collections import namedtuple
from mamba_ssm.modules.mamba_simple import Mamba
from mamba_ssm.utils.generation import GenerationMixin
from mamba_ssm.utils.hf import load_config_hf, load_state_dict_hf
from lib.models.ostrack.rope import *
import random
from lib.models.layers.head import build_box_head
import importlib
import lib.train.admin.settings as ws_settings
from .utils import combine_tokens, recover_tokens
try:
from mamba_ssm.ops.triton.layernorm import RMSNorm, layer_norm_fn, rms_norm_fn
except ImportError:
RMSNorm, layer_norm_fn, rms_norm_fn = None, None, None
################# 添加 Resnet 网络
import torchvision
from torch.nn.utils.rnn import pad_sequence
from einops import rearrange
class ResNetExtractor(nn.Module):
def init (self, resnet_type ="resnet18"):
super(ResNetExtractor, self).init ()
self.resnet = getattr(torchvision.models, resnet_type)(pretrained=True)
self.resnet.fc = nn.Identity()
code Copy code
def forward(self, x):
return self.resnet(x)
class TemporalConv(nn.Module):
def init (self, input_size, hidden_size, conv_type=2):
super(TemporalConv, self).init ()
self.input_size = input_size
self.hidden_size = hidden_size
self.kernel_size = ['K5','P2'] if conv_type == 2 else ['K3']
code Copy code
modules = []
for layer_idx, ks in enumerate(self.kernel_size):
input_sz = self.input_size if layer_idx == 0 else self.hidden_size
if ks[0] == 'P':
modules.append(nn.MaxPool1d(kernel_size=int(ks[1]), ceil_mode=False))
elif ks[0] == 'K':
modules.append(nn.Conv1d(input_sz, self.hidden_size, kernel_size=int(ks[1]), stride=1, padding=0))
modules.append(nn.BatchNorm1d(self.hidden_size))
modules.append(nn.ReLU(inplace=True))
self.temporal_conv = nn.Sequential(*modules)
def forward(self, x):
x = self.temporal_conv(x.permute(0, 2, 1))
return x.permute(0, 2, 1)
all = [
'vim_tiny_patch16_224', 'vim_small_patch16_224', 'vim_base_patch16_224',
'vim_tiny_patch16_384', 'vim_small_patch16_384', 'vim_base_patch16_384',
]
class PatchEmbed(nn.Module):
""" 2D Image to Patch Embedding
"""
def init (self, img_size=224, patch_size=16, stride=16, in_chans=3, embed_dim=768, norm_layer=None, flatten=True):
super().init ()
img_size = to_2tuple(img_size)
patch_size = to_2tuple(patch_size)
self.img_size = img_size
self.patch_size = patch_size
self.grid_size = ((img_size[0] - patch_size[0]) // stride + 1, (img_size[1] - patch_size[1]) // stride + 1)
self.num_patches = self.grid_size[0] * self.grid_size[1]
self.flatten = flatten
code Copy code
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=stride)
self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
def forward(self, x):
B, C, H, W = x.shape
x = self.proj(x)
if self.flatten:
x = x.flatten(2).transpose(1, 2) # BCHW -> BNC
x = self.norm(x)
return x
class Block(nn.Module):
def init (
self, dim, mixer_cls, norm_cls=nn.LayerNorm, fused_add_norm=False, residual_in_fp32=False,drop_path=0.,
):
"""
Simple block wrapping a mixer class with LayerNorm/RMSNorm and residual connection"
code Copy code
This Block has a slightly different structure compared to a regular
prenorm Transformer block.
The standard block is: LN -> MHA/MLP -> Add.
[Ref: https://arxiv.org/abs/2002.04745]
Here we have: Add -> LN -> Mixer, returning both
the hidden_states (output of the mixer) and the residual.
This is purely for performance reasons, as we can fuse add and LayerNorm.
The residual needs to be provided (except for the very first block).
"""
super().__init__()
self.residual_in_fp32 = residual_in_fp32
self.fused_add_norm = fused_add_norm
self.mixer = mixer_cls(dim)
self.norm = norm_cls(dim)
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
if self.fused_add_norm:
assert RMSNorm is not None, "RMSNorm import fails"
assert isinstance(
self.norm, (nn.LayerNorm, RMSNorm)
), "Only LayerNorm and RMSNorm are supported for fused_add_norm"
def forward(
self, hidden_states: Tensor, residual: Optional[Tensor] = None, inference_params=None
):
r"""Pass the input through the encoder layer.
Args:
hidden_states: the sequence to the encoder layer (required).
residual: hidden_states = Mixer(LN(residual))
"""
fused_add_norm_fn = rms_norm_fn if isinstance(self.norm, RMSNorm) else layer_norm_fn
hidden_states, residual = fused_add_norm_fn(
hidden_states,
self.norm.weight,
self.norm.bias,
residual=residual,
prenorm=True,
residual_in_fp32=self.residual_in_fp32,
eps=self.norm.eps,
)
hidden_states = self.mixer(hidden_states, inference_params=inference_params)
return hidden_states, residual
def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
return self.mixer.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs)
def create_block(
d_model,
ssm_cfg=None,
norm_epsilon=1e-5,
drop_path=0.,
rms_norm=False,
residual_in_fp32=False,
fused_add_norm=False,
layer_idx=None,
device=None,
dtype=None,
if_bimamba=False,
bimamba_type="none",
if_devide_out=False,
init_layer_scale=None,
):
if if_bimamba:
bimamba_type = "v1"
if ssm_cfg is None:
ssm_cfg = {}
factory_kwargs = {"device": device, "dtype": dtype}
mixer_cls = partial(Mamba, layer_idx=layer_idx, bimamba_type=bimamba_type, if_devide_out=if_devide_out, init_layer_scale=init_layer_scale, **ssm_cfg, **factory_kwargs)
norm_cls = partial(
nn.LayerNorm if not rms_norm else RMSNorm, eps=norm_epsilon, **factory_kwargs
)
block = Block(
d_model,
mixer_cls,
norm_cls=norm_cls,
drop_path=drop_path,
fused_add_norm=fused_add_norm,
residual_in_fp32=residual_in_fp32,
)
block.layer_idx = layer_idx
return block
#################### 新增类
class VisionMamba(nn.Module):
def init (self,
img_size =224,
patch_size=16,
stride=16,
depth =24,
embed_dim = 192,
channels = 3,
num_classes = 1000,
ssm_cfg = None,
drop_rate = 0.,
drop_path_rate = 0.1,
norm_epsilon: float = 1e-5,
rms_norm: bool = False,
initializer_cfg = None,
fused_add_norm = False,
residual_in_fp32 = False,
device = None,
dtype = None,
ft_seq_len = None,
pt_hw_seq_len = 14,
if_bidirectional = False,
final_pool_type = 'none',
if_abs_pos_embed = False,
if_rope = False,
if_rope_residual = False,
flip_img_sequences_ratio = -1.,
if_bimamba = False,
bimamba_type = "none",
if_cls_token = False,
if_devide_out = False,
init_layer_scale = None,
use_double_cls_token = False,
use_middle_cls_token = False,
**kwargs):
factory_kwargs = {"device": device, "dtype": dtype}
kwargs.update(factory_kwargs)
super().init ()
self.residual_in_fp32 = residual_in_fp32
self.fused_add_norm = fused_add_norm
self.if_bidirectional = if_bidirectional
self.final_pool_type = final_pool_type
self.if_abs_pos_embed = if_abs_pos_embed
self.if_rope = if_rope
self.if_rope_residual = if_rope_residual
self.flip_img_sequences_ratio = flip_img_sequences_ratio
self.if_cls_token = if_cls_token
self.use_double_cls_token = use_double_cls_token
self.use_middle_cls_token = use_middle_cls_token
self.num_tokens = 1 if if_cls_token else 0
########## 下文中加载 预训练模型权重
@register_model
def vim_tiny_patch16_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, embed_dim=192, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='mean', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
checkpoint = torch.hub.load_state_dict_from_url(
url="to.do",
map_location="cpu", check_hash=True
)
model.load_state_dict(checkpoint["model"])
return model
@register_model
def vim_tiny_patch16_stride8_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, stride=8, embed_dim=192, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='mean', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
checkpoint = torch.hub.load_state_dict_from_url(
url="to.do",
map_location="cpu", check_hash=True
)
model.load_state_dict(checkpoint["model"])
return model
LIGHT
@register_model
def vim_small_patch16_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, embed_dim=384, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='all', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
# checkpoint = torch.hub.load_state_dict_from_url(
# url="to.do",
# map_location="cpu", check_hash=True
# )
# model.load_state_dict(checkpoint["model"])
code Copy code
checkpoint = torch.load(pretrained, map_location="cpu")
missing_keys, unexpected_keys = model.load_state_dict(checkpoint["model"], strict=False)
print('Load pretrained model from: ' + pretrained)
return model
@register_model
def vim_small_patch16_stride8_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, stride=8, embed_dim=384, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='mean', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
checkpoint = torch.hub.load_state_dict_from_url(
url="to.do",
map_location="cpu", check_hash=True
)
model.load_state_dict(checkpoint["model"])
return model的不同之处,中文回答。
Show full message · 1,068 lines Assistant2024-09-09 08:16 UTC Copy response
以下是代码①和代码②的不同之处:
ResNet特征提取器 :
代码②中新增了ResNetExtractor类,这是一个基于ResNet的特征提取模块。它使用torchvision库中的预训练ResNet(例如,resnet18)来提取图像特征。
在VisionMamba类中,代码②新增了一个self.resnet字段,初始化为ResNetExtractor对象。
时间卷积层 :
代码②中新增了TemporalConv类,这是一个时间卷积模块,用于处理序列数据。
VisionMamba类中,在代码②新增了一个self.temporal_conv字段,用于时间维度的卷积操作。
VisionMamba类的初始化 :
代码②中在VisionMamba类的初始化方法中增加了ResNetExtractor和TemporalConv模块的实例化。这两个模块用于提取和处理输入图像的特征。
VisionMamba类的forward_features方法 :
代码②中更新了forward_features方法,使用ResNet提取图像特征并通过时间卷积处理。这改变了特征提取的方式,使其不再依赖原始的卷积和嵌入,而是利用了ResNet和时间卷积的结合。
代码风格的微小差异 :
变量命名和逻辑流的组织略有不同,以反映新增加的功能模块。
代码①和代码②整体上共享了大部分定义和方法,但代码②引入了新的特征提取方法,可能用于更复杂的时间序列图像处理任务。该修改使网络能够从输入图像中提取更丰富的空间和时间特征。
但是②中虽然增加了resnet特征提取模块,但是还是得保留①中的 def forward(self, static_z, dynamic_z, x, return_features=False, inference_params=None,
if_random_cls_token_position=False, if_random_token_rank=False,
feat_len_s=None, feat_len_z=None):
dynamic_z = self.foward_dynamic_features(dynamic_z)[:, -feat_len_z:]
code Copy code
x = self.forward_tripple_features(dynamic_z, static_z, x,
inference_params, if_random_cls_token_position=if_random_cls_token_position,
if_random_token_rank=if_random_token_rank)
这个逻辑。
Assistant2024-09-09 08:21 UTC Copy response
如果需要在代码②中保留代码①的forward方法逻辑,同时引入ResNet特征提取模块,那么可以对代码进行如下调整:
保留原有的forward方法逻辑 :
将代码①的forward方法直接转移到代码②中,不改变其逻辑。
确保该方法中所引用的所有其他方法(如foward_dynamic_features和forward_tripple_features)也正确地保留或者实现。
集成ResNet特征提取模块 :
在不影响原有forward逻辑的情况下,引入ResNet特征提取功能。可以在某些特定阶段(如初始化阶段)根据需要使用self.resnet提取输入图像的特征。
如果新引入的特征在与forward_tripple_features结合时有特别的需求,确保在适当的部分对特征进行处理。
以下提供一个如何合并这两种需求的示例代码结构:
python Copy code
class VisionMamba(nn.Module):
def __init__(self, ...):
...
self.resnet = ResNetExtractor(resnet_type="resnet18") # 初始化ResNet
...
def foward_dynamic_features(self, dynamic_z, ...):
# 保留原有逻辑
...
def forward_tripple_features(self, dynamic_z, static_z, x, ...):
# 保留原有逻辑
...
def forward(self, static_z, dynamic_z, x, return_features=False, inference_params=None,
if_random_cls_token_position=False, if_random_token_rank=False,
feat_len_s=None, feat_len_z=None):
# 在需要的地方进行ResNet特征提取,这里提供一种可能的方案
# x = self.resnet(x) # 如果想用ResNet处理输入x
dynamic_z = self.foward_dynamic_features(dynamic_z)[:, -feat_len_z:]
x = self.forward_tripple_features(dynamic_z, static_z, x,
inference_params, if_random_cls_token_position=if_random_cls_token_position,
if_random_token_rank=if_random_token_rank)
if return_features:
return x
return x
在这种结构下,通过self.resnet可以随时提取图像特征,而不动原有的forward逻辑。您可以根据任务的具体需求选择在forward流程中的哪个位置或阶段对输入应用ResNet特征提取。
那么在import torch
import torch.nn as nn
import numpy as np
import torchvision
from transformers import MBartForConditionalGeneration, MBartPreTrainedModel, MBartModel, MBartConfig
from torch.nn.utils.rnn import pad_sequence
global definition
from definition import *
from models_mamba import create_block
import math
from einops import rearrange, repeat
def make_resnet(name='resnet18'):
if name == 'resnet18':
model = torchvision.models.resnet18(pretrained=True)
elif name == 'resnet34':
model = torchvision.models.resnet34(pretrained=True)
elif name == 'resnet50':
model = torchvision.models.resnet50(pretrained=True)
elif name == 'resnet101':
model = torchvision.models.resnet101(pretrained=True)
else:
raise Exception('There are no supported resnet model {}.'.format(_('resnet')))
code Copy code
model.fc = nn.Identity()
return model
class resnet(nn.Module):
def init (self, name="resnet18"):
super(resnet, self).init ()
self.resnet = make_resnet(name=name)
code Copy code
def forward(self, x, lengths):
x = self.resnet(x)
x_batch = []
start = 0
for length in lengths:
end = start + length
x_batch.append(x[start:end])
start = end
x = pad_sequence(x_batch,padding_value=PAD_IDX,batch_first=True)
return x
class time_mamba(nn.Module):
def init (self):
super(time_mamba, self).init ()
code Copy code
self.mamba_block = create_block(d_model=512)
def forward(self, x):
hidden_x, res_x = self.mamba_block(x)
return hidden_x
class TemporalConv(nn.Module):
def init (self, input_size, hidden_size, conv_type=2):
super(TemporalConv, self).init ()
self.input_size = input_size
self.hidden_size = hidden_size
self.conv_type = conv_type
Show full message · 163 lines Assistant2024-09-09 08:27 UTC Copy response
在给定的代码中,视觉特征的提取主要涉及以下几个部分:
ResNet 模块 (resnet 类) :
resnet 类是一个封装了 ResNet 特征提取的模块。在 resnet 类中使用了 make_resnet 函数来创建一个指定类型的 ResNet(如 ResNet18)。其前向传播方法将输入图像通过 ResNet 生成特征,并按输入批次的长度对特征进行打包处理。
在 SignModel 类中,self.resnet 是对视频输入数据的初步特征提取调用,通过 self.resnet(src_input['input_ids'].cuda(), src_input['src_length_batch'])。
时间卷积模块 (TemporalConv 类) :
TemporalConv 是设计用来处理时间序列数据(视频特征)的卷积模块。它通过一系列 1D 卷积、批归一化和 ReLU 激活函数来处理从 ResNet 提取的特征。
在 SignModel 类中,self.conv_1d 用于对从 ResNet 提取的特征进行进一步的时间维度的卷积处理。
时间 Mamba 模块 (time_mamba 类) :
time_mamba 类通过 create_block 创建了一个 Mamba 块,该模块用于进一步处理提取的视觉特征。
视觉编码器 (V_encoder 类) :
V_encoder 通过线性层和批归一化处理来自时间卷积模块的特征,将其转化为适合输入到 MBart 模型的嵌入。
在 SignModel 中,通过 self.sign_emb 实例调用该编码器处理时间卷积的输出。
这些模块和方法的调用共同构成了输入数据从原始图像序列到深度网络特征的完整处理流水线。具体来说,数据通过 ResNet 进行初步的视觉特征提取,然后经过时间卷积、Mamba 和视觉编码器的处理,以便后续用于生成任务。
那么在# Copyright (c) 2015-present, Facebook, Inc.
All rights reserved.
import torch
import torch.nn as nn
from functools import partial
from torch import Tensor
from typing import Optional
from timm.models.vision_transformer import VisionTransformer, cfg
from timm.models.registry import register_model
from timm.models.layers import trunc_normal , lecun_normal_
from timm.models.layers import DropPath, to_2tuple
from timm.models.vision_transformer import _load_weights
import math
from collections import namedtuple
from mamba_ssm.modules.mamba_simple import Mamba
from mamba_ssm.utils.generation import GenerationMixin
from mamba_ssm.utils.hf import load_config_hf, load_state_dict_hf
from lib.models.ostrack.rope import *
import random
from lib.models.layers.head import build_box_head
import importlib
import lib.train.admin.settings as ws_settings
from .utils import combine_tokens, recover_tokens
try:
from mamba_ssm.ops.triton.layernorm import RMSNorm, layer_norm_fn, rms_norm_fn
except ImportError:
RMSNorm, layer_norm_fn, rms_norm_fn = None, None, None
################# 添加 Resnet 网络
import torchvision
from torch.nn.utils.rnn import pad_sequence
from einops import rearrange
class ResNetExtractor(nn.Module):
def init (self, resnet_type ="resnet18"):
super(ResNetExtractor, self).init ()
self.resnet = getattr(torchvision.models, resnet_type)(pretrained=True)
self.resnet.fc = nn.Identity()
code Copy code
def forward(self, x):
return self.resnet(x)
class TemporalConv(nn.Module):
def init (self, input_size, hidden_size, conv_type=2):
super(TemporalConv, self).init ()
self.input_size = input_size
self.hidden_size = hidden_size
self.kernel_size = ['K5','P2'] if conv_type == 2 else ['K3']
code Copy code
modules = []
for layer_idx, ks in enumerate(self.kernel_size):
input_sz = self.input_size if layer_idx == 0 else self.hidden_size
if ks[0] == 'P':
modules.append(nn.MaxPool1d(kernel_size=int(ks[1]), ceil_mode=False))
elif ks[0] == 'K':
modules.append(nn.Conv1d(input_sz, self.hidden_size, kernel_size=int(ks[1]), stride=1, padding=0))
modules.append(nn.BatchNorm1d(self.hidden_size))
modules.append(nn.ReLU(inplace=True))
self.temporal_conv = nn.Sequential(*modules)
def forward(self, x):
x = self.temporal_conv(x.permute(0, 2, 1))
return x.permute(0, 2, 1)
Show full message · 518 lines Assistant2024-09-09 08:28 UTC Copy response
在您所提供的代码中,提取视觉特征的部分主要包括以下几个模块:
ResNetExtractor 类 :
该类利用预训练的 ResNet 模型来提取视觉特征,并通过将最后的全连接层替换为身份映射 (nn.Identity) 来去除分类层,只保留特征提取部分。
方法 forward:接收输入张量并使用 ResNet 提取特征。
TemporalConv 类 :
该类实现了时间卷积,用于进一步处理由 ResNet 获得的特征。其结构包括若干个一维卷积、批处理归一化和激活函数。
方法 forward:接收输入张量并进行一维卷积处理。
VisionMamba 类 :
VisionMamba 类是在主模型中结合了 ResNet 特征提取器和时间卷积的模块。
在 forward_features 方法中:
使用 self.resnet(x) 调用 ResNet 特征提取器提取输入 x 的视觉特征。
使用 self.temporal_conv(x) 对从 ResNet 输出的特征进行时间卷积处理。
forward_dynamic_features 和 forward_tripple_features 方法中,也会涉及到对输入特征的处理以及与位置编码的结合。
在此代码中,提取视觉特征的关键步骤是通过 ResNetExtractor 的 ResNet 网络得到初步的视觉特征,然后再由 TemporalConv 进行时间序列上的卷积处理,以形成适合后续分析的特征表示。这两个扩展模块增强了对复杂视觉信息的提取和编码能力。
原始模型是:# Copyright (c) 2015-present, Facebook, Inc.
All rights reserved.
import torch
import torch.nn as nn
from functools import partial
from torch import Tensor
from typing import Optional
from timm.models.vision_transformer import VisionTransformer, cfg
from timm.models.registry import register_model
from timm.models.layers import trunc_normal , lecun_normal_
from timm.models.layers import DropPath, to_2tuple
from timm.models.vision_transformer import _load_weights
import math
from collections import namedtuple
from mamba_ssm.modules.mamba_simple import Mamba
from mamba_ssm.utils.generation import GenerationMixin
from mamba_ssm.utils.hf import load_config_hf, load_state_dict_hf
from lib.models.ostrack.rope import *
import random
from lib.models.layers.head import build_box_head
import importlib
import lib.train.admin.settings as ws_settings
from .utils import combine_tokens, recover_tokens
try:
from mamba_ssm.ops.triton.layernorm import RMSNorm, layer_norm_fn, rms_norm_fn
except ImportError:
RMSNorm, layer_norm_fn, rms_norm_fn = None, None, None
all = [
'vim_tiny_patch16_224', 'vim_small_patch16_224', 'vim_base_patch16_224',
'vim_tiny_patch16_384', 'vim_small_patch16_384', 'vim_base_patch16_384',
]
class PatchEmbed(nn.Module):
""" 2D Image to Patch Embedding
"""
def init (self, img_size=224, patch_size=16, stride=16, in_chans=3, embed_dim=768, norm_layer=None, flatten=True):
super().init ()
img_size = to_2tuple(img_size)
patch_size = to_2tuple(patch_size)
self.img_size = img_size
self.patch_size = patch_size
self.grid_size = ((img_size[0] - patch_size[0]) // stride + 1, (img_size[1] - patch_size[1]) // stride + 1)
self.num_patches = self.grid_size[0] * self.grid_size[1]
self.flatten = flatten
code Copy code
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=stride)
self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
def forward(self, x):
B, C, H, W = x.shape
# print('11x.shape:', x.shape) # 11x.shape: torch.Size([2, 3, 128, 128])
# assert H == self.img_size[0] and W == self.img_size[1], \
# f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
x = self.proj(x)
if self.flatten:
x = x.flatten(2).transpose(1, 2) # BCHW -> BNC
x = self.norm(x)
return x
Show full message · 1,329 lines Assistant2024-09-09 08:33 UTC Copy response
在您提供的代码中,您将一个基于ResNet的特征提取模块和时间卷积模块整合到了原本基于Vision Transformer的模型中。这种嵌入可以丰富输入特征的表达,从而可能增强模型的性能。然而,需要检查一下代码是否与总体目标一致,并可能进行一些改进。以下是一些建议和注意事项:
确保模型输入正确 :
ResNetExtractor和TemporalConv的输入应确保维度和数据类型与ResNet和卷积层的期望一致。
对于forward_features方法的输入,需要注意z和x的预处理是否与ResNet和时间卷积所需的输入格式一致。
ResNet的使用 :
ResNetExtractor的输出是每个输入样本的特征向量。既然您已经将ResNet和TemporalConv整合入forward_features方法中,那么可能需要仔细查看ResNet的输出维度,以确保能够传递给TemporalConv。
Feature Flattening及位置编码 :
在使用ResNet和时间卷积后,您应用位置编码的方式可能需要根据新的特征形状进行调整。确保位置编码的维度和形状与特征匹配。
模板提取和处理 :
在forward_dynamic_features等函数中,对于特征的打乱和展平处理,需要确保处理的特征维度正确地符合后续Transformer模块的输入要求。
参数与权重 :
如果代码中引入的新模块(如ResNet和TemporalConv)影响了模型的参数数量,注意根据需要调整训练策略或加载预训练权重的方式。
确保_init_weights方法和segm_init_weights方法对新的卷积层正确初始化。
反向传播与损失 :
请确认经过ResNet和时间卷积的特征在整个网络中能正确地进行反向传播,检查可能的梯度流动问题。
整体测试和调试 :
在代码运行之前或期间,通过单元测试或者过一些小的示例输入进行调试,以确保所有模块均按预期工作。
确保在运行时,如报错或输出异常,检查输入输出大小和模型内部的计算图,以便及时纠正。
综合这些建议,如果代码在调试过程中没有出现运行时错误,并且输出与目标相符,那么模型的集成是合理的。您还可以结合实际任务的需求,对各个模块进行微调和优化以获得更好的性能。
class V_encoder(nn.Module):
def init (self, emb_size, feature_size):
super(V_encoder, self).init ()
code Copy code
self.src_emb = nn.Linear(feature_size, emb_size)
modules = []
modules.append(nn.BatchNorm1d(emb_size))
modules.append(nn.ReLU(inplace=True))
self.bn_ac = nn.Sequential(*modules)
for m in self.modules():
if isinstance(m, (nn.Conv1d,nn.Linear)):
nn.init.xavier_uniform_(m.weight, gain=nn.init.calculate_gain('relu'))
elif isinstance(m, nn.BatchNorm1d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
def forward(self, src:torch.Tensor):
src = self.src_emb(src)
src = self.bn_ac(src.permute(0,2,1)).permute(0,2,1)
return src函数执行了什么功能?
Assistant2024-09-09 09:11 UTC Copy response
V_encoder类是一个基本的神经网络模块,其功能是处理输入特征以生成适合下游模型使用的嵌入。以下是该模块的详细功能描述:
初始化 :
self.src_emb:一个线性层(全连接层),其将输入特征从feature_size映射到一个目标嵌入维度emb_size。
self.bn_ac:一个顺序容器,包含批归一化和ReLU激活函数。它们一起对经过线性变换的特征进行归一化和非线性激活。
权重初始化 :
使用nn.init.xavier_uniform_对所有的卷积和线性层的权重进行Xavier均匀初始化。Xavier初始化能帮助稳定网络的初始训练过程。
对BatchNorm1d的权重初始化为1,偏置初始化为0。这样做通常是为了在训练初期不改变输入的分布。
前向传播方法 (forward) :
输入src是一个三维张量,其形状通常是(batch_size, sequence_length, feature_size)。
通过线性层self.src_emb将输入特征映射到目标嵌入维度。
然后利用BatchNorm1d对每个时间步的特征进行归一化,再通过ReLU进行激活。
由于BatchNorm1d要求输入形状为(batch_size, num_features, sequence_length),在使用批归一化时,输入张量需要调整维度顺序。通过permute函数,src.permute(0,2,1)改变此顺序,然后经过BatchNorm1d的处理后再恢复到原来的维度顺序。
总结来说,V_encoder类通过线性变换、批归一化和激活函数对输入特征进行预处理,提取有意义的嵌入特征以供下游模型使用。这种处理一般用于视觉特征或序列特征的转换,使得下一步的模型(例如Transformer)能够更有效地使用这些数据。
那么综上,在# Copyright (c) 2015-present, Facebook, Inc.
All rights reserved.
import torch
import torch.nn as nn
from functools import partial
from torch import Tensor
from typing import Optional
from timm.models.vision_transformer import VisionTransformer, cfg
from timm.models.registry import register_model
from timm.models.layers import trunc_normal , lecun_normal_
from timm.models.layers import DropPath, to_2tuple
from timm.models.vision_transformer import _load_weights
import math
from collections import namedtuple
from mamba_ssm.modules.mamba_simple import Mamba
from mamba_ssm.utils.generation import GenerationMixin
from mamba_ssm.utils.hf import load_config_hf, load_state_dict_hf
from lib.models.ostrack.rope import *
import random
from lib.models.layers.head import build_box_head
import importlib
import lib.train.admin.settings as ws_settings
from .utils import combine_tokens, recover_tokens
try:
from mamba_ssm.ops.triton.layernorm import RMSNorm, layer_norm_fn, rms_norm_fn
except ImportError:
RMSNorm, layer_norm_fn, rms_norm_fn = None, None, None
import torchvision
from torch.nn.utils.rnn import pad_sequence
from einops import rearrange
class ResNetExtractor(nn.Module):
def init (self, resnet_type ="resnet18"):
super(ResNetExtractor, self).init ()
self.resnet = getattr(torchvision.models, resnet_type)(pretrained=True)
self.resnet.fc = nn.Identity()
code Copy code
def forward(self, x):
return self.resnet(x)
class TemporalConv(nn.Module):
def init (self, input_size, hidden_size, conv_type=2):
super(TemporalConv, self).init ()
self.input_size = input_size
self.hidden_size = hidden_size
self.kernel_size = ['K5','P2'] if conv_type == 2 else ['K3']
code Copy code
modules = []
for layer_idx, ks in enumerate(self.kernel_size):
input_sz = self.input_size if layer_idx == 0 else self.hidden_size
if ks[0] == 'P':
modules.append(nn.MaxPool1d(kernel_size=int(ks[1]), ceil_mode=False))
elif ks[0] == 'K':
modules.append(nn.Conv1d(input_sz, self.hidden_size, kernel_size=int(ks[1]), stride=1, padding=0))
modules.append(nn.BatchNorm1d(self.hidden_size))
modules.append(nn.ReLU(inplace=True))
self.temporal_conv = nn.Sequential(*modules)
def forward(self, x):
x = self.temporal_conv(x.permute(0, 2, 1))
return x.permute(0, 2, 1)
Show full message · 687 lines Assistant2024-09-09 09:16 UTC Copy response
在您提供的修改后的代码中,VisionMamba 类已经包含了视觉特征提取模块(ResNetExtractor 和 TemporalConv),并将其整合进了原有的 VisionTransformer 流程。这已经为模型提供了一个有效的步骤来提取和处理视觉特征。然而,如果您考虑了 V_encoder 的功能及其用途,有可能需要将其整合但需视具体目标而定。
是否需要整合 V_encoder?
考虑 V_encoder 的用途 :
V_encoder 的功能是在输入特征基础上执行进一步的线性变换与批归一化。这可能对于在一些下游处理步骤需要隐藏层维度操作或重新映射时会有帮助。
目标和应用场景 :
如果您的最终目标包括在特征提取之后集中进行某种特定处理(比如融合多模态特征或适配特定任务输入特征,我们常在任务特定的训练阶段发现这种需求),则可能需要整合 V_encoder。
输入输出维度匹配的必要性 :
在将 V_encoder 加入到现有的 VisionMamba 流程中,需要确保其输入特征和输出特征的维度都与前后的模块匹配。这样可以避免由于维度不匹配导致的报错。
如何整合 V_encoder?
假设需要在当前 VisionMamba 特征提取和处理流程中加入 V_encoder,以下是一个示范性的思路:
python Copy code
class VisionMamba(nn.Module):
def __init__(self,
img_size=224,
patch_size=16,
embed_dim=192, # Assuming this to be input size for V_encoder
...
):
...
self.resnet = ResNetExtractor(resnet_type="resnet18")
self.temporal_conv = TemporalConv(input_size=512, hidden_size=embed_dim)
self.v_encoder = V_encoder(emb_size=embed_dim, feature_size=embed_dim) # Initialize V_encoder
def forward(self, static_z, dynamic_z, x, ...):
x = self.resnet(x)
x = self.temporal_conv(x)
x = self.v_encoder(x) # Apply V_encoder
...
关键注意事项:
确保 V_encoder 在这个步骤中所需的输入和输出都是合法而有效的。
确认该编解码环节对于模型最终的任务起到辅助作用并提高了模型性能。
如果整合之后出现维度不匹配,您可能需要在前后增加调整维度的层(如线性层)。
整合的具体与否应基于您对模型或者任务的深度需求分析,合理调整特征提取部分和编码部分之间的关系能促进模型的推断能力。
现在对比:① class ResNetExtractor(nn.Module):
def init (self, resnet_type ="resnet18"):
super(ResNetExtractor, self).init ()
self.resnet = getattr(torchvision.models, resnet_type)(pretrained=True)
self.resnet.fc = nn.Identity()
code Copy code
def forward(self, x):
return self.resnet(x) 和 ② def make_resnet(name='resnet18'):
if name == 'resnet18':
model = torchvision.models.resnet18(pretrained=True)
elif name == 'resnet34':
model = torchvision.models.resnet34(pretrained=True)
elif name == 'resnet50':
model = torchvision.models.resnet50(pretrained=True)
elif name == 'resnet101':
model = torchvision.models.resnet101(pretrained=True)
else:
raise Exception('There are no supported resnet model {}.'.format(_('resnet')))
model.fc = nn.Identity()
return model
class resnet(nn.Module):
def init (self, name="resnet18"):
super(resnet, self).init ()
self.resnet = make_resnet(name=name)
code Copy code
def forward(self, x, lengths):
x = self.resnet(x)
x_batch = []
start = 0
for length in lengths:
end = start + length
x_batch.append(x[start:end])
start = end
x = pad_sequence(x_batch,padding_value=PAD_IDX,batch_first=True)
return x
的逻辑有何不同。
Assistant2024-09-09 09:24 UTC Copy response
ResNetExtractor 和 resnet 两个类的实现逻辑有所不同,下面是它们之间的主要区别:
1. 结构设计
① ResNetExtractor 类:
该类直接定义了一个 ResNet 模型,并将其最后一个全连接层替换成 nn.Identity(),以便输出原始的特征向量,而不是分类结果。
forward 方法简单地将输入x通过 ResNet 模型进行前向传播。
② resnet 类和 make_resnet 函数:
make_resnet 是一个工厂函数,用于根据指定名称('resnet18', 'resnet34', 'resnet50', 'resnet101')创建相应的 ResNet 模型,并将最后的全连接层替换为 nn.Identity()。
resnet 类利用 make_resnet 函数来创建 ResNet 模型。
forward 方法不仅将输入x通过 ResNet 模型进行前向传播,还对输出进行了额外处理:根据给定的lengths参数将输出特征划分成若干子序列,然后使用 pad_sequence 对这些子序列进行补齐,以满足某种序列处理需求。
2. 输入和输出处理
① ResNetExtractor 的 forward 方法:
输入:只接收张量x。
输出:直接输出 ResNet 提取的特征,无其他处理。
② resnet 的 forward 方法:
输入:接收两个参数,x 和 lengths。
x 是输入的张量。
lengths 是一个序列长度列表,用于分割和处理输出特征。
输出:对 ResNet 输出的特征根据lengths进行分割,并使用 pad_sequence 将特征补齐处理。
3. 应用场景
ResNetExtractor 类非常简单,适合直接从 ResNet 中提取特征的场景,没有复杂的输出后处理需求。
resnet 类适合于序列数据处理的场景,特别是需要在后续网络模块进行序列化处理时很有帮助。通过长度信息,对批次中的数据按需分割和补齐。
综上,看您所需的任务需求和数据类型来选择适合的实现。resnet 类增加了一些灵活性,但可能不适合所有用例。
那么现在的研究目标是跟踪任务,且数据后续需要采用mamba处理数据,那么采用哪个resnet类更合适?
Assistant2024-09-09 10:09 UTC Copy response
在为跟踪任务选择适合的 ResNet 类用于特征提取,同时计划后续使用 Mamba 模块处理这些特征时,以下是考虑因素和建议:
考虑因素
数据结构和输入格式 :
跟踪任务中的输入图像数据通常是连续帧序列。如果需要处理具有可变长度序列或需要对特征序列进行操作,那么处理输出的灵活性会变得重要。
后续处理需求 :
Mamba 处理模块可能需要特定的序列格式或结构化的连续输入特征。
任务和应用场景需要 :
任务需要对输入批次中的各个样本进行单独且可变长的处理,还是只需进行统一的特征提取。
建议
直接选择 ResNetExtractor 类 :
如果跟踪任务的特征提取只需要从每一帧中进行简单特征提取,而不涉及复杂的序列分割或序列处理,那么 ResNetExtractor 类会是一个更简单直接的选择。
使用简洁的接口和结构只需关注于从模型中提取特征,在使用 Mamba 进行后续处理时可以灵活处理不同格式的输入。
选择 resnet 类处理序列数据 :
如果跟踪任务的输入包括序列图像,且每个样本序列的长度可能不同,这种情况下采用 resnet 类能提供将特征按序列分割和填充的能力,这样的输出可能对于需要顺序/时间维度的处理的 Mamba 模块非常有用。
通过 lengths 参数可以管理和操作不规则长度的序列数据,保证每个批次中的输入形式一致,以适应特定 Mamba 处理需求。
结论
若任务重点在于处理单帧图像或一致长度的图像序列,ResNetExtractor 是个不错的选择。
若任务需要处理可变长序列,并且这些序列数据在 Mamba 模块中会显著受益于结构化输出(如时间序列建模),则选择 resnet 类可能更有利。
务必仔细考虑您的数据格式和后续模块处理需求,从而在实现中选择最佳的 ResNet 变体。通过实验和测试来调整,以达到最佳的性能和处理效率。
global definition
UNK_TOKEN = ""
PAD_TOKEN = ""
BOS_TOKEN = ""
EOS_TOKEN = ""
SI_TOKEN = ""
SI_IDX,PAD_IDX,UNK_IDX,BOS_IDX, EOS_IDX = 0,1,2,3,4
SPECIAL_SYMBOLS = ['','', '','', '']
WORD_MASK = ""
Assistant2024-09-09 10:25 UTC Copy response
这个代码片段定义了一组全局常量和特殊符号,主要用于自然语言处理(NLP)中的文本预处理过程,尤其是在序列生成和处理任务中。以下是每个定义的解释:
特殊标记 :
UNK_TOKEN: Represents "", commonly used to indicate unknown words or tokens that are not found in the vocabulary.
PAD_TOKEN: Represents "", used to fill the sequences to a uniform length in a batch of data (padding).
BOS_TOKEN: Represents "" (beginning of sentence), used to denote the start of a sequence.
EOS_TOKEN: Represents "" (end of sentence), used to denote the end of a sequence.
SI_TOKEN: Represents "", typically used for task-specific markers or identifiers. Its specific role should be clarified in the context of its usage in the model.
索引定义 :
SI_IDX, PAD_IDX, UNK_IDX, BOS_IDX, EOS_IDX: These are integer indices associated with each of the special tokens. They are often used in models to map each special token to an integer index in the vocabulary, which simplifies the encoding and processing of sequences.
特殊符号列表 :
SPECIAL_SYMBOLS: A list containing all the special tokens defined above. This can be useful for iterating over special symbols, checking for membership, or other operations involving multiple special symbols at once.
其他标记 :
WORD_MASK: Represents "", which is commonly used in masked language modeling tasks (like BERT) where certain parts of the input are masked out to be predicted by the model.
使用场景
自然语言处理任务 : 这些定义通常用于处理和准备文本数据,例如在机器翻译、文本生成或其他需要处理序列数据的任务中。
模型训练与推理 : 利用这些标记及其索引,模型可以处理不同类型的文本输入,并正确理解序列的开始、结束及填充逻辑。
文本预处理 : 在批处理和序列化操作中自动化管理句子边界、未知或稀有词对应处理。
在实践中,这些常量需要和您所使用的词汇表和模型配置对齐确保正确性和一致性。
综上,ResNetExtractor 类 和 resnet 类区别是什么?
Assistant2024-09-09 10:34 UTC Copy response
ResNetExtractor 类和 resnet 类的区别主要体现在设计目的、输入输出的处理方式以及适用的场景:
1. 设计目的
ResNetExtractor 类 :
设计上更加简单,旨在利用预训练的 ResNet 提取图像特征,同时去除最后的全连接层以获得特征表示而非分类结果。
resnet 类 :
设计上更复杂,除利用预训练 ResNet 外,还考虑了序列化的操作,适配变长输入的需求,这在处理序列数据时尤为常见。
2. 输入和输出处理
ResNetExtractor :
输入:通常是图像数据,直接作为批次传入。
输出:经过 ResNet 处理后的特征向量,没有进一步的复杂处理。
resnet :
输入:图像数据加上一个 lengths 列表,用于指示批次中每个输入的长度。
输出:从 ResNet 提取特征后,对这些特征根据长度信息进行分割,然后进行补齐,以保证序列化的完整性。
3. 适用场景
ResNetExtractor :
适合于需要简单地从图像中提取固定长度特征的任务,没有对输出特征有序列化处理需求。
resnet :
更适合用于需要处理变长序列(如视频或时间序列图像数据)的场景,尤其是在后续处理模块(可能涉及到时间序列、变长序列建模等)需要这些格式化后的序列特征。
4. 代码逻辑
ResNetExtractor :
直接使用 ResNet 特征提取,输出特征无需分割和补齐。
resnet :
使用 make_resnet 工厂函数创建 ResNet。
对输出特征进行按序列长度切分并补齐,以为后续序列处理准备数据。
选择建议
在选择哪个实现更合适时,应根据实际的应用需求:
如果你的任务仅需要进行图像特征提取,且后续没有复杂的序列化需求,ResNetExtractor 是更简单直接的选择。
当你的任务涉及到序列化的处理,比如多帧图像数据或视频数据,以及需要对特征进行序列操作时,resnet 类则会更合适。
分析:① # Copyright (c) 2015-present, Facebook, Inc.
All rights reserved.
import torch
import torch.nn as nn
from functools import partial
from torch import Tensor
from typing import Optional
from timm.models.vision_transformer import VisionTransformer, cfg
from timm.models.registry import register_model
from timm.models.layers import trunc_normal , lecun_normal_
from timm.models.layers import DropPath, to_2tuple
from timm.models.vision_transformer import _load_weights
import math
from collections import namedtuple
from vim.mamba_1p1p1.mamba_ssm.modules.mamba_simple import Mamba
from vim.mamba_1p1p1.mamba_ssm.utils.generation import GenerationMixin
from vim.mamba_1p1p1.mamba_ssm.utils.hf import load_config_hf, load_state_dict_hf
from vim_new.mamba_1_1_1.mamba_ssm.modules.mamba_simple import Mamba
from vim_new.mamba_1_1_1.mamba_ssm.utils.generation import GenerationMixin
from vim_new.mamba_1_1_1.mamba_ssm.utils.hf import load_config_hf, load_state_dict_hf
from rope import *
import random
try:
from vim.mamba_1p1p1.mamba_ssm.ops.triton.layernorm import RMSNorm, layer_norm_fn, rms_norm_fn
except ImportError:
RMSNorm, layer_norm_fn, rms_norm_fn = None, None, None
all = [
'vim_tiny_patch16_224', 'vim_small_patch16_224', 'vim_base_patch16_224',
'vim_tiny_patch16_384', 'vim_small_patch16_384', 'vim_base_patch16_384',
]
class PatchEmbed(nn.Module):
""" 2D Image to Patch Embedding
"""
def init (self, img_size=224, patch_size=16, stride=16, in_chans=3, embed_dim=768, norm_layer=None, flatten=True):
super().init ()
img_size = to_2tuple(img_size)
patch_size = to_2tuple(patch_size)
self.img_size = img_size
self.patch_size = patch_size
self.grid_size = ((img_size[0] - patch_size[0]) // stride + 1, (img_size[1] - patch_size[1]) // stride + 1)
self.num_patches = self.grid_size[0] * self.grid_size[1]
self.flatten = flatten
code Copy code
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=stride)
self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
def forward(self, x):
B, C, H, W = x.shape
assert H == self.img_size[0] and W == self.img_size[1], \
f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
x = self.proj(x)
if self.flatten:
x = x.flatten(2).transpose(1, 2) # BCHW -> BNC
x = self.norm(x)
return x
Show full message · 766 lines Assistant2024-09-09 10:40 UTC Copy response
在比较两个代码段时,主要关注time_mamba相关的实现和逻辑。以下是两段代码及其相关的分析:
代码①:
代码①的主要目的是定义和实现与 Vision Transformer 相关的模型类,包括用于 Patch 嵌入的 PatchEmbed 类、用于处理输入特征的 Block 类以及作为整体模型的 VisionMamba 类。
代码②:
代码②中定义了一个叫做 time_mamba 的类,它涉及与时间序列特征处理相关的逻辑:
python Copy code
class time_mamba(nn.Module):
def __init__(self):
super(time_mamba, self).__init__()
self.mamba_block = create_block(d_model=512)
def forward(self, x):
hidden_x, res_x = self.mamba_block(x)
return hidden_x
解析:
类定义 :
time_mamba 是一个 PyTorch 的 nn.Module,它主要是为了处理输入特征。
构造函数 (__init__) :
在构造函数中,使用 create_block 函数创建了一个 mamba_block。虽然在代码中没有提供 create_block 的详细定义,但通常这种模块是用来实现一个特定的神经网络层或组件。
前向传播 (forward) :
forward 方法接收输入 x,并通过 mamba_block 来处理这些输入。
mamba_block 返回两个结果,但 forward 只返回 hidden_x,这暗示着 hidden_x 是处理过的特征,而 res_x 可能是某种中间或者残差信息,它未被进一步使用。
对比与用法:
模块化 :
time_mamba 可以被视作一个用于时间序列数据的模块化组件,可以在如 SignModel 这样的复杂结构中重复使用。
用途 :
在 SignModel 中,time_mamba 作为处理 ResNet 提取出的视觉特征的一个阶段,然后将其输出提供给后续的卷积处理(TemporalConv)和特征编码(V_encoder)。
选择与用途:
如果 Mamba 中包含特定时间序列处理逻辑或设计,它可以结合 create_block 来更好地处理时间维度相关数据,在 Transformer 类结构中执行功能。
如果任务需要包含对序列化输入较好的处理和处理效率,那么 time_mamba 可能与代码①中维持的结构和类更为兼容,且能在特定上下文下展现其独特的处理时间特性。
综上,如果项目的核心任务涉及时间序列数据的处理,那么 time_mamba 可能是根据该特征设计的一个特定层,有助于更有效地管理时间维度的信息传递。
是这样,create_block 在# Copyright (c) 2015-present, Facebook, Inc.
All rights reserved.
import torch
import torch.nn as nn
from functools import partial
from torch import Tensor
from typing import Optional
from timm.models.vision_transformer import VisionTransformer, cfg
from timm.models.registry import register_model
from timm.models.layers import trunc_normal , lecun_normal_
from timm.models.layers import DropPath, to_2tuple
from timm.models.vision_transformer import _load_weights
import math
from collections import namedtuple
from vim.mamba_1p1p1.mamba_ssm.modules.mamba_simple import Mamba
from vim.mamba_1p1p1.mamba_ssm.utils.generation import GenerationMixin
from vim.mamba_1p1p1.mamba_ssm.utils.hf import load_config_hf, load_state_dict_hf
from vim_new.mamba_1_1_1.mamba_ssm.modules.mamba_simple import Mamba
from vim_new.mamba_1_1_1.mamba_ssm.utils.generation import GenerationMixin
from vim_new.mamba_1_1_1.mamba_ssm.utils.hf import load_config_hf, load_state_dict_hf
from rope import *
import random
try:
from vim.mamba_1p1p1.mamba_ssm.ops.triton.layernorm import RMSNorm, layer_norm_fn, rms_norm_fn
except ImportError:
RMSNorm, layer_norm_fn, rms_norm_fn = None, None, None
all = [
'vim_tiny_patch16_224', 'vim_small_patch16_224', 'vim_base_patch16_224',
'vim_tiny_patch16_384', 'vim_small_patch16_384', 'vim_base_patch16_384',
]
class PatchEmbed(nn.Module):
""" 2D Image to Patch Embedding
"""
def init (self, img_size=224, patch_size=16, stride=16, in_chans=3, embed_dim=768, norm_layer=None, flatten=True):
super().init ()
img_size = to_2tuple(img_size)
patch_size = to_2tuple(patch_size)
self.img_size = img_size
self.patch_size = patch_size
self.grid_size = ((img_size[0] - patch_size[0]) // stride + 1, (img_size[1] - patch_size[1]) // stride + 1)
self.num_patches = self.grid_size[0] * self.grid_size[1]
self.flatten = flatten
code Copy code
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=stride)
self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
def forward(self, x):
B, C, H, W = x.shape
assert H == self.img_size[0] and W == self.img_size[1], \
f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
x = self.proj(x)
if self.flatten:
x = x.flatten(2).transpose(1, 2) # BCHW -> BNC
x = self.norm(x)
return x
Show full message · 604 lines Assistant2024-09-09 10:46 UTC Copy response
在您提到的代码中,create_block 函数的定义细节如下:
create_block 函数
python Copy code
def create_block(
d_model,
ssm_cfg=None,
norm_epsilon=1e-5,
drop_path=0.,
rms_norm=False,
residual_in_fp32=False,
fused_add_norm=False,
layer_idx=None,
device=None,
dtype=None,
if_bimamba=False,
bimamba_type="none",
if_devide_out=False,
init_layer_scale=None,
):
if if_bimamba:
bimamba_type = "v1"
if ssm_cfg is None:
ssm_cfg = {}
factory_kwargs = {"device": device, "dtype": dtype}
mixer_cls = partial(Mamba, layer_idx=layer_idx, bimamba_type=bimamba_type, if_devide_out=if_devide_out, init_layer_scale=init_layer_scale, **ssm_cfg, **factory_kwargs)
norm_cls = partial(
nn.LayerNorm if not rms_norm else RMSNorm, eps=norm_epsilon, **factory_kwargs
)
block = Block(
d_model,
mixer_cls,
norm_cls=norm_cls,
drop_path=drop_path,
fused_add_norm=fused_add_norm,
residual_in_fp32=residual_in_fp32,
)
block.layer_idx = layer_idx
return block
解析
总结
create_block 是一个用于构建以 Mamba 为核心模块的神经网络块的函数,能够快速配置和生成网络层,而不必直接处理各类底层组件的初始化和连接操作。这种设计有助于保持代码的整洁性和模块化。
当前模型:# Copyright (c) 2015-present, Facebook, Inc.
All rights reserved.
import torch
import torch.nn as nn
from functools import partial
from torch import Tensor
from typing import Optional
from timm.models.vision_transformer import VisionTransformer, cfg
from timm.models.registry import register_model
from timm.models.layers import trunc_normal , lecun_normal_
from timm.models.layers import DropPath, to_2tuple
from timm.models.vision_transformer import _load_weights
import math
from collections import namedtuple
from mamba_ssm.modules.mamba_simple import Mamba
from mamba_ssm.utils.generation import GenerationMixin
from mamba_ssm.utils.hf import load_config_hf, load_state_dict_hf
from lib.models.ostrack.rope import *
import random
from lib.models.layers.head import build_box_head
import importlib
import lib.train.admin.settings as ws_settings
from .utils import combine_tokens, recover_tokens
try:
from mamba_ssm.ops.triton.layernorm import RMSNorm, layer_norm_fn, rms_norm_fn
except ImportError:
RMSNorm, layer_norm_fn, rms_norm_fn = None, None, None
import torchvision
from torch.nn.utils.rnn import pad_sequence
from einops import rearrange
class ResNetExtractor(nn.Module):
def init (self, resnet_type ="resnet18"):
super(ResNetExtractor, self).init ()
self.resnet = getattr(torchvision.models, resnet_type)(pretrained=True)
self.resnet.fc = nn.Identity()
code Copy code
def forward(self, x):
return self.resnet(x)
class TemporalConv(nn.Module):
def init (self, input_size, hidden_size, conv_type=2):
super(TemporalConv, self).init ()
self.input_size = input_size
self.hidden_size = hidden_size
self.kernel_size = ['K5','P2'] if conv_type == 2 else ['K3']
code Copy code
modules = []
for layer_idx, ks in enumerate(self.kernel_size):
input_sz = self.input_size if layer_idx == 0 else self.hidden_size
if ks[0] == 'P':
modules.append(nn.MaxPool1d(kernel_size=int(ks[1]), ceil_mode=False))
elif ks[0] == 'K':
modules.append(nn.Conv1d(input_sz, self.hidden_size, kernel_size=int(ks[1]), stride=1, padding=0))
modules.append(nn.BatchNorm1d(self.hidden_size))
modules.append(nn.ReLU(inplace=True))
self.temporal_conv = nn.Sequential(*modules)
def forward(self, x):
x = self.temporal_conv(x.permute(0, 2, 1))
return x.permute(0, 2, 1)
Show full message · 720 lines Assistant2024-09-09 10:59 UTC Copy response
在给定的代码中,特征提取的网络主要由以下几个组件组成:
1. ResNetExtractor 类
目的 :从输入图像中提取初步的视觉特征。
结构 :
使用 torchvision.models 提供的预训练 ResNet 模型(例如,ResNet18),并将最终的全连接层替换为 nn.Identity(),确保输出特征而不是分类结果。
前向传播 :输入图像经过 ResNet 特征提取器,输出特征表示。
2. TemporalConv 类
目的 :对已经提取的视觉特征进行时间维度的卷积操作。
结构 :
通过一系列 1D 卷积、批标准化和 ReLU 激活函数对特征进行再处理。
提供了不同的卷积核和池化参数来调整特征处理的详细粒度。
前向传播 :输入特征通过一维卷积并应用批处理归一化和非线性激活,再将结果返回。
3. V_encoder 类
目的 :将特征从一个维度映射到目标嵌入维度,同时进行批处理归一化。
结构 :
使用 nn.Linear 进行维度转换,并通过 BatchNorm1d 和 ReLU 激活函数进行特征归一化与非线性激活。
前向传播 :对输入特征执行线性变换后,应用批处理和激活。
整合在 VisionMamba 类中
In the VisionMamba类中,这些特征提取组件与Transformer-like结构整合在一起:
现在我们需要确定,是否调用了Resnet网络处理,应该如何设置?
Assistant2024-09-09 11:29 UTC Copy response
要确定及设置是否调用了 ResNet 网络进行特征提取,可以通过代码中的调用点进行确认,并通过相应的配置或代码结构来进行控制。在您提供的代码中,ResNet 的调用逻辑位于 VisionMamba 类中, 以下是如何检查和设置这一过程的建议:
确认 ResNet 的调用
查找 ResNet 提取的具体调用 :
在 VisionMamba 类中,通过 self.resnet(x) 调用了 ResNet 特征提取器。这段代码意味着 x 在进入 Transformer 模块之前,被输入到 ResNet 中进行初始特征提取。
设置或控制 ResNet 调用
如果需要控制是否调用 ResNet 网络,可以通过以下几种方法来实现:
增加标识参数 :在 VisionMamba 类的初始化参数中添加一个标识参数(例如 use_resnet),用来控制是否使用 ResNet。
python Copy code
class VisionMamba(nn.Module):
def __init__(self, ... , use_resnet=True, ...):
self.use_resnet = use_resnet
# Initialization logic...
def forward(self, static_z, dynamic_z, x, ...):
if self.use_resnet:
x = self.resnet(x)
# Proceed with the rest of the forward method...
条件判断 :在 forward 方法的逻辑中,通过参数判断逻辑决定是否调用 ResNet。
python Copy code
def forward(self, static_z, dynamic_z, x, ...):
if self.use_resnet:
x = self.resnet(x)
# Rest of the logic...
使用配置文件 :如果您的项目使用了配置文件,可以在配置文件中设置标志性参数,并在模型初始化或者forward方法中引用该参数。
示例:
设置一个 use_resnet 参数,然后在 forward 方法中使用这个参数来控制功能开关:
python Copy code
# 初始化
model = VisionMamba(..., use_resnet=True)
# 前向过程调用
output = model(static_z, dynamic_z, x)
注意事项
确保条件判断的设置在您所需的代码路径中,这样无需手动每次更改模型代码即可实现灵活控制。
根据实际应用场景与任务需求,合理选择是否需要 ResNet 网络处理,以优化模型性能与训练效率。
增加这样的开关选项不仅方便调试,也能帮助在各种实验配置中进行灵活调整。
通过这种方式,您可以方便地控制是否进行 ResNet 的调用,从而满足不同实验条件下的特定需求。
将# Copyright (c) 2015-present, Facebook, Inc.
All rights reserved.
import torch
import torch.nn as nn
from functools import partial
from torch import Tensor
from typing import Optional
from timm.models.vision_transformer import VisionTransformer, cfg
from timm.models.registry import register_model
from timm.models.layers import trunc_normal , lecun_normal_
from timm.models.layers import DropPath, to_2tuple
from timm.models.vision_transformer import _load_weights
import math
from collections import namedtuple
from mamba_ssm.modules.mamba_simple import Mamba
from mamba_ssm.utils.generation import GenerationMixin
from mamba_ssm.utils.hf import load_config_hf, load_state_dict_hf
from lib.models.ostrack.rope import *
import random
from lib.models.layers.head import build_box_head
import importlib
import lib.train.admin.settings as ws_settings
from .utils import combine_tokens, recover_tokens
try:
from mamba_ssm.ops.triton.layernorm import RMSNorm, layer_norm_fn, rms_norm_fn
except ImportError:
RMSNorm, layer_norm_fn, rms_norm_fn = None, None, None
import torchvision
from torch.nn.utils.rnn import pad_sequence
from einops import rearrange
class ResNetExtractor(nn.Module):
def init (self, resnet_type ="resnet18"):
super(ResNetExtractor, self).init ()
self.resnet = getattr(torchvision.models, resnet_type)(pretrained=True)
self.resnet.fc = nn.Identity()
code Copy code
def forward(self, x):
print('1111111111111111111111111111111111111111111111111111')
return self.resnet(x)
class TemporalConv(nn.Module):
def init (self, input_size, hidden_size, conv_type=2):
super(TemporalConv, self).init ()
self.input_size = input_size
self.hidden_size = hidden_size
self.kernel_size = ['K5','P2'] if conv_type == 2 else ['K3']
code Copy code
modules = []
for layer_idx, ks in enumerate(self.kernel_size):
input_sz = self.input_size if layer_idx == 0 else self.hidden_size
if ks[0] == 'P':
modules.append(nn.MaxPool1d(kernel_size=int(ks[1]), ceil_mode=False))
elif ks[0] == 'K':
modules.append(nn.Conv1d(input_sz, self.hidden_size, kernel_size=int(ks[1]), stride=1, padding=0))
modules.append(nn.BatchNorm1d(self.hidden_size))
modules.append(nn.ReLU(inplace=True))
self.temporal_conv = nn.Sequential(*modules)
def forward(self, x):
x = self.temporal_conv(x.permute(0, 2, 1))
return x.permute(0, 2, 1)
Show full message · 719 lines Assistant2024-09-09 11:40 UTC Copy response
在现有的代码中,ResNetExtractor 已经在 VisionMamba 类中被实例化并用于特征提取。以下是如何确认和确保其集成正确,以及如何对其进行控制以适应不同的需求:
确认 ResNetExtractor 的集成
确认实例化 :
确认调用 :
控制 ResNetExtractor 的集成
如果要控制该特征提取器的启用以适用于不同实验或需求,可以通过以下几种方式实现:
添加配置参数 :
条件控制 :
注意事项
数据格式 :确保传递给 ResNetExtractor 的张量格式和大小正确,以匹配 ResNet 的输入要求。
性能考量 :对 ResNet 的调用会增加计算时间和资源消耗,应根据具体实验需求控制其使用。
调试输出 :您在 ResNetExtractor 的 forward 方法中加入了 print 语句,这可以帮助确认调用的实际发生,但需要注意在实际处理大规模数据时可能影响性能。
通过灵活的集成和控制,可以有效利用 ResNet 提供的强大特征提取能力,并根据实验要求进行配置和优化。
import torch
import torch.nn as nn
import numpy as np
import torchvision
from transformers import MBartForConditionalGeneration, MBartPreTrainedModel, MBartModel, MBartConfig
from torch.nn.utils.rnn import pad_sequence
global definition
from definition import *
from models_mamba import create_block
import math
from einops import rearrange, repeat
def make_resnet(name='resnet18'):
if name == 'resnet18':
model = torchvision.models.resnet18(pretrained=True)
elif name == 'resnet34':
model = torchvision.models.resnet34(pretrained=True)
elif name == 'resnet50':
model = torchvision.models.resnet50(pretrained=True)
elif name == 'resnet101':
model = torchvision.models.resnet101(pretrained=True)
else:
raise Exception('There are no supported resnet model {}.'.format(_('resnet')))
code Copy code
model.fc = nn.Identity()
return model
class resnet(nn.Module):
def init (self, name="resnet18"):
super(resnet, self).init ()
self.resnet = make_resnet(name=name)
code Copy code
def forward(self, x, lengths):
x = self.resnet(x)
x_batch = []
start = 0
for length in lengths:
end = start + length
x_batch.append(x[start:end])
start = end
x = pad_sequence(x_batch,padding_value=PAD_IDX,batch_first=True)
return x
class time_mamba(nn.Module):
def init (self):
super(time_mamba, self).init ()
code Copy code
self.mamba_block = create_block(d_model=512)
def forward(self, x):
hidden_x, res_x = self.mamba_block(x)
return hidden_x
class TemporalConv(nn.Module):
def init (self, input_size, hidden_size, conv_type=2):
super(TemporalConv, self).init ()
self.input_size = input_size
self.hidden_size = hidden_size
self.conv_type = conv_type
Show full message · 351 lines Assistant2024-09-09 12:26 UTC Copy response
在您提供的代码中,resnet 类及其在 SignModel 中的使用提供了对输入图像数据的特征提取功能。以下是关于 resnet 类在此上下文中的功能及使用方式的详细说明:
resnet 类
功能
模型初始化 :resnet 类是一个继承自 nn.Module 的类,利用 make_resnet 函数创造了一个指定类型(例如 resnet18)的 ResNet 模型。
特征提取 :在 forward 方法中,通过从 torchvision.models 加载的预训练 ResNet 模型进行初始特征提取。
序列处理 :从 ResNet 提取的特征按指定的 lengths 切分后再经过 pad_sequence 补齐,以形成一批规范化序列特征。其主要目的是将批次中的图像特征规范化成相同长度,适配后续处理层。
SignModel 中 resnet 的使用
在 SignModel 的 visual_forward 方法中,该类被用来处理通过 S2T_Dataset 加载的图像输入。
数据流程
输入 :visual_forward 接收 src_input,其中包含输入图像的 tensor 和相关的长度信息。
ResNet调用 :
调用 self.resnet 方法,将图像数据馈入到 ResNet 中生成特征,并按图像序列的长度进行处理。
lengths 参数确保了处理后的特征序列与输入数据逻辑上的对齐。
后续处理 :
通过 time_mamba 类进行进一步的处理,显然后的扩展是面向序列化特征变换。
后续还有 TemporalConv 和 V_encoder 的特征处理和嵌入转换环节。
数据准备
通过 S2T_Dataset 类加载的图像数据被传递给 resnet 模型进行特征提取,并且在 collate_fn 函数中,图像数据经过了归一化和增强(如旋转、平移和颜色变化),这为训练数据提供了更广泛的变换选择以提升模型的泛化能力。
总结
通过 ResNet 来负责初步的视觉特征提取,再通过后续模块处理以更好地适应模态转换需求(如用于序列建模等),确保数据流在高质量特征的基础上完成。这种设计能提供灵活且高效的特征表示,使模型能更好地理解输入数据并执行相关任务。
Copy first response
Not yet included in a published release.
Turns (17) 1 分析:① # Copyright (c) 2015-present, Facebook, Inc. All rights reserved. import to 2 但是②中虽然增加了resnet特征提取模块,但是还是得保留①中的 def forward(self, staticz, dynamicz, x, returnf 3 那么在import torch import torch.nn as nn import numpy as np import torchvision from 4 那么在# Copyright (c) 2015-present, Facebook, Inc. All rights reserved. import torc 5 原始模型是:# Copyright (c) 2015-present, Facebook, Inc. All rights reserved. import t 6 class Vencoder(nn.Module): def init(self, embsize, featuresize): super(Vencoder, 7 那么综上,在# Copyright (c) 2015-present, Facebook, Inc. All rights reserved. import t 8 现在对比:① class ResNetExtractor(nn.Module): def init(self, resnettype ="resnet18"): 9 那么现在的研究目标是跟踪任务,且数据后续需要采用mamba处理数据,那么采用哪个resnet类更合适? 10 global definition UNKTOKEN = " " PADTOKEN = " " BOSTOKEN = " " EOSTOKEN = " " SI 11 综上,ResNetExtractor 类 和 resnet 类区别是什么? 12 分析:① # Copyright (c) 2015-present, Facebook, Inc. All rights reserved. import to 13 是这样,createblock 在# Copyright (c) 2015-present, Facebook, Inc. All rights reserve 14 当前模型:# Copyright (c) 2015-present, Facebook, Inc. All rights reserved. import to 15 现在我们需要确定,是否调用了Resnet网络处理,应该如何设置? 16 将# Copyright (c) 2015-present, Facebook, Inc. All rights reserved. import torch 17 import torch import torch.nn as nn import numpy as np import torchvision from tr # pretrain parameters
self.num_classes = num_classes
self.d_model = self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
self.patch_embed = PatchEmbed(
img_size=img_size, patch_size=patch_size, stride=stride, in_chans=channels, embed_dim=embed_dim)
num_patches = self.patch_embed.num_patches
if if_cls_token:
if use_double_cls_token:
self.cls_token_head = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
self.cls_token_tail = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
self.num_tokens = 2
else:
self.cls_token = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
# self.num_tokens = 1
if if_abs_pos_embed:
# self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + self.num_tokens, self.embed_dim))
self.pos_embed_x = nn.Parameter(torch.zeros(1, 256, self.embed_dim))
self.pos_embed_z = nn.Parameter(torch.zeros(1, 64, self.embed_dim))
self.pos_embed_dynamic_z = nn.Parameter(torch.zeros(1, 64, self.embed_dim))
self.pos_drop = nn.Dropout(p=drop_rate)
if if_rope:
half_head_dim = embed_dim // 2
hw_seq_len = img_size // patch_size
self.rope = VisionRotaryEmbeddingFast(
dim=half_head_dim,
pt_seq_len=pt_hw_seq_len,
ft_seq_len=hw_seq_len
)
# self.head = nn.Linear(self.num_features, num_classes) if num_classes > 0 else nn.Identity()
# TODO: release this comment
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
# import ipdb;ipdb.set_trace()
inter_dpr = [0.0] + dpr
self.drop_path = DropPath(drop_path_rate) if drop_path_rate > 0. else nn.Identity()
# transformer blocks
self.layers = nn.ModuleList(
[
create_block(
embed_dim,
ssm_cfg=ssm_cfg,
norm_epsilon=norm_epsilon,
rms_norm=rms_norm,
residual_in_fp32=residual_in_fp32,
fused_add_norm=fused_add_norm,
layer_idx=i,
if_bimamba=if_bimamba,
bimamba_type=bimamba_type,
drop_path=inter_dpr[i],
if_devide_out=if_devide_out,
init_layer_scale=init_layer_scale,
**factory_kwargs,
)
for i in range(depth)
]
)
# output head
self.norm_f = (nn.LayerNorm if not rms_norm else RMSNorm)(
embed_dim, eps=norm_epsilon, **factory_kwargs
)
# self.pre_logits = nn.Identity()
# original init
self.patch_embed.apply(segm_init_weights)
# self.head.apply(segm_init_weights)
if if_abs_pos_embed:
trunc_normal_(self.pos_embed_x, std=.02)
trunc_normal_(self.pos_embed_z, std=.02)
if if_cls_token:
if use_double_cls_token:
trunc_normal_(self.cls_token_head, std=.02)
trunc_normal_(self.cls_token_tail, std=.02)
else:
trunc_normal_(self.cls_token, std=.02)
# mamba init
self.apply(
partial(
_init_weights,
n_layer=depth,
**(initializer_cfg if initializer_cfg is not None else {}),
)
)
def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
return {
i: layer.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs)
for i, layer in enumerate(self.layers)
}
@torch.jit.ignore
def no_weight_decay(self):
return {"pos_embed", "cls_token", "dist_token", "cls_token_head", "cls_token_tail"}
@torch.jit.ignore()
def load_pretrained(self, checkpoint_path, prefix=""):
_load_weights(self, checkpoint_path, prefix)
# 未调用
def forward_features(self, z, x, inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False):
x = self.patch_embed(x) #x.shape = torch.Size([B, 3, 224, 224]) -> torch.Size([2, 196, 384])
z = self.patch_embed(z)
B, M, _ = x.shape
if self.if_abs_pos_embed: #YES # self.if_abs_pos_embed = true
x = x + self.pos_embed_x # x = x + positon_embemding =torch.Size([B, 196, 384]) + torch.Size([1, 196, 384]) = torch.Size([B, 196, 384])
z = z + self.pos_embed_z
x = torch.cat((z, x), dim=1)
x = self.pos_drop(x) # x.shape = torch.Size([B, 196, 384])
if_flip_img_sequences = False
# NO
# mamba impl
residual = None
hidden_states = x
for layer in self.layers:
hidden_states, residual = layer(
hidden_states, residual, inference_params=inference_params
)
fused_add_norm_fn = rms_norm_fn if isinstance(self.norm_f, RMSNorm) else layer_norm_fn
hidden_states = fused_add_norm_fn(
self.drop_path(hidden_states),
self.norm_f.weight,
self.norm_f.bias,
eps=self.norm_f.eps,
residual=residual,
prenorm=False,
residual_in_fp32=self.residual_in_fp32,
)
return hidden_states
def foward_dynamic_features(self, stacked_template, inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False):
# print('1111111111111111')
B, M, C, H, W = stacked_template.size()
# print('stacked_template.size():', stacked_template.size()) # stacked_template.size(): torch.Size([2, 7, 3, 128, 128]) BatchSize
# 初始化一个空的列表用于存放打乱后的模板
shuffled_templates = []
# 遍历每个 batch
for i in range(B):
# 取出当前 batch 的模板,形状为 (M, C, H, W)
batch_templates = stacked_template[i]
# 将当前 batch 内的模板顺序打乱
indices = torch.randperm(M)
batch_templates = batch_templates[indices]
# 进行 Patch Embedding 操作并展平
patch_embeddings = self.patch_embed(batch_templates) # 形状假设为 (M, N, D)
flattened_embeddings = patch_embeddings.flatten(0, 1) # 形状变为 (M * N, D)
# 将打乱并处理后的模板加入新的列表
shuffled_templates.append(flattened_embeddings)
# 将列表展平并堆叠为一个新的张量,形状为 (B, M * N, D)
shuffled_templates = torch.stack(shuffled_templates, dim=0)
x = self.pos_drop(shuffled_templates)
if_flip_img_sequences = False
# mamba impl
residual = None
hidden_states = x
for layer in self.layers:
hidden_states, residual = layer(
hidden_states, residual, inference_params=inference_params
)
# Set prenorm=False here since we don't need the residual
fused_add_norm_fn = rms_norm_fn if isinstance(self.norm_f, RMSNorm) else layer_norm_fn
hidden_states = fused_add_norm_fn( # hidden_states.shape = torch.Size([2, 320, 384])
self.drop_path(hidden_states),
self.norm_f.weight,
self.norm_f.bias,
eps=self.norm_f.eps,
residual=residual,
prenorm=False,
residual_in_fp32=self.residual_in_fp32,
)
return hidden_states
def forward_dynamic_features_inference(self, template_list, inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False):
'''
input shape:
template_list: python list. item: torch.tensor, (1, 3, 128, 128)
'''
# B = 1
# stacked_templates = template_list.flatten(0,1) #为了测速而作的调整
stacked_templates = torch.cat(template_list, dim=0)
x = self.patch_embed(stacked_templates)
B, N, C = x.shape
x = x.reshape(1, B*N, C)
x = self.pos_drop(x)
if_flip_img_sequences = False
# mamba impl
residual = None
hidden_states = x
for layer in self.layers:
hidden_states, residual = layer(
hidden_states, residual, inference_params=inference_params
)
fused_add_norm_fn = rms_norm_fn
hidden_states = fused_add_norm_fn( # hidden_states.shape = torch.Size([2, 320, 384])
self.drop_path(hidden_states),
self.norm_f.weight,
self.norm_f.bias,
eps=self.norm_f.eps,
residual=residual,
prenorm=False,
residual_in_fp32=self.residual_in_fp32,
)
return hidden_states
def forward_dynamic_features_speed_test(self, template_list, inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False):
'''
input shape:
template_list: python list. item: torch.tensor, (1, 3, 128, 128)
'''
# B = 1
stacked_templates = template_list.flatten(0,1) #为了测速而作的调整
# stacked_templates = torch.cat(template_list, dim=0)
x = self.patch_embed(stacked_templates)
B, N, C = x.shape
x = x.reshape(1, B*N, C)
x = self.pos_drop(x)
if_flip_img_sequences = False
# mamba impl
residual = None
hidden_states = x
for layer in self.layers:
hidden_states, residual = layer(
hidden_states, residual, inference_params=inference_params
)
fused_add_norm_fn = rms_norm_fn
hidden_states = fused_add_norm_fn( # hidden_states.shape = torch.Size([2, 320, 384])
self.drop_path(hidden_states),
self.norm_f.weight,
self.norm_f.bias,
eps=self.norm_f.eps,
residual=residual,
prenorm=False,
residual_in_fp32=self.residual_in_fp32,
)
return hidden_states
def forward_tripple_features(self, dynamic_z, static_z, x, inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False):
# taken from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
# with slight modifications to add the dist_token
# print('pre_x.shape:',x.shape) # torch.Size([2, 3, 256, 256])
x = self.patch_embed(x) #x.shape = torch.Size([B, 3, 224, 224]) -> torch.Size([2, 196, 384])
z = self.patch_embed(static_z)
# print('tri_x.shape:', x.shape) # tri_x.shape: torch.Size([2, 256, 384])
B, M, _ = x.shape
# print('BM_x.shape:', x.shape) # BM_x.shape: torch.Size([2, 256, 384])
x = x + self.pos_embed_x # x = x + positon_embemding =torch.Size([B, 196, 384]) + torch.Size([1, 196, 384]) = torch.Size([B, 196, 384])
z = z + self.pos_embed_z
dynamic_z = dynamic_z + self.pos_embed_dynamic_z
x = torch.cat((z, dynamic_z, x), dim=1)
# x = torch.cat((dynamic_z, z, x), dim=1)
x = self.pos_drop(x) # x.shape = torch.Size([B, 196, 384])
if_flip_img_sequences = False
# mamba impl
residual = None
hidden_states = x
for layer in self.layers:
hidden_states, residual = layer(
hidden_states, residual, inference_params=inference_params
)
fused_add_norm_fn = rms_norm_fn
hidden_states = fused_add_norm_fn( # hidden_states.shape = torch.Size([2, 320, 384])
self.drop_path(hidden_states),
self.norm_f.weight,
self.norm_f.bias,
eps=self.norm_f.eps,
residual=residual,
prenorm=False,
residual_in_fp32=self.residual_in_fp32,
)
return hidden_states
def forward(self, static_z, dynamic_z, x, return_features=False, inference_params=None,
if_random_cls_token_position=False, if_random_token_rank=False,
feat_len_s=None, feat_len_z=None):
dynamic_z = self.foward_dynamic_features(dynamic_z)[:, -feat_len_z:]
x = self.forward_tripple_features(dynamic_z, static_z, x,
inference_params, if_random_cls_token_position=if_random_cls_token_position,
if_random_token_rank=if_random_token_rank)
if return_features:
return x
# x = self.head(x)
if self.final_pool_type == 'max':
x = x.max(dim=1)[0]
return x
def inference(self, dynamic_z, static_z, x, return_features=False, inference_params=None,
if_random_cls_token_position=False, if_random_token_rank=False,
feat_len_s=None, feat_len_z=None):
'''
dynamic_z -> mamba hidden states
static_z -> raw template rgb image
x -> raw search rgb image
'''
dynamic_z = dynamic_z[:, -feat_len_z:]
x = self.forward_tripple_features(dynamic_z, static_z, x,
inference_params, if_random_cls_token_position=if_random_cls_token_position,
if_random_token_rank=if_random_token_rank)
return x
#### 新增 :Resnet 特征提取器
self.resnet = ResNetExtractor(resnet_type ="resnet18")
#### 新增时间卷积层
self.temporal_conv = TemporalConv(input_size=512, hidden_size=embed_dim)
# pretrain parameters
self.num_classes = num_classes
self.d_model = self.num_features = self.embed_dim = embed_dim
self.patch_embed = PatchEmbed(
img_size=img_size, patch_size=patch_size, stride=stride, in_chans=channels, embed_dim=embed_dim)
num_patches = self.patch_embed.num_patches
if if_cls_token:
if use_double_cls_token:
self.cls_token_head = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
self.cls_token_tail = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
self.num_tokens = 2
else:
self.cls_token = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
if if_abs_pos_embed:
self.pos_embed_x = nn.Parameter(torch.zeros(1, 256, self.embed_dim))
self.pos_embed_z = nn.Parameter(torch.zeros(1, 64, self.embed_dim))
self.pos_embed_dynamic_z = nn.Parameter(torch.zeros(1, 64, self.embed_dim))
self.pos_drop = nn.Dropout(p=drop_rate)
if if_rope:
half_head_dim = embed_dim // 2
hw_seq_len = img_size // patch_size
self.rope = VisionRotaryEmbeddingFast(
dim=half_head_dim,
pt_seq_len=pt_hw_seq_len,
ft_seq_len=hw_seq_len
)
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)]
inter_dpr = [0.0] + dpr
self.drop_path = DropPath(drop_path_rate) if drop_path_rate > 0. else nn.Identity()
self.layers = nn.ModuleList(
[
create_block(
embed_dim,
ssm_cfg=ssm_cfg,
norm_epsilon=norm_epsilon,
rms_norm=rms_norm,
residual_in_fp32=residual_in_fp32,
fused_add_norm=fused_add_norm,
layer_idx=i,
if_bimamba=if_bimamba,
bimamba_type=bimamba_type,
drop_path=inter_dpr[i],
if_devide_out=if_devide_out,
init_layer_scale=init_layer_scale,
**factory_kwargs,
)
for i in range(depth)
]
)
# output head
self.norm_f = (nn.LayerNorm if not rms_norm else RMSNorm)(
embed_dim, eps=norm_epsilon, **factory_kwargs
)
self.patch_embed.apply(segm_init_weights)
if if_abs_pos_embed:
trunc_normal_(self.pos_embed_x, std=.02)
trunc_normal_(self.pos_embed_z, std=.02)
if if_cls_token:
if use_double_cls_token:
trunc_normal_(self.cls_token_head, std=.02)
trunc_normal_(self.cls_token_tail, std=.02)
else:
trunc_normal_(self.cls_token, std=.02)
self.apply(
partial(
_init_weights,
n_layer=depth,
**(initializer_cfg if initializer_cfg is not None else {}),
)
)
def forward_features(self, z, x, inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False):
# 使用ResNet提取图像特征
x = self.resnet(x)
x = self.temporal_conv(x)
B, N, C = x.shape
if self.if_abs_pos_embed:
x = x + self.pos_embed_x
z = z + self.pos_embed_z
x = torch.cat((z, x), dim=1)
x = self.pos_drop(x)
# 下面是原有逻辑
residual = None
hidden_states = x
for layer in self.layers:
hidden_states, residual = layer(
hidden_states, residual, inference_params=inference_params
)
fused_add_norm_fn = rms_norm_fn if isinstance(self.norm_f, RMSNorm) else layer_norm_fn
hidden_states = fused_add_norm_fn(
self.drop_path(hidden_states),
self.norm_f.weight,
self.norm_f.bias,
eps=self.norm_f.eps,
residual=residual,
prenorm=False,
residual_in_fp32=self.residual_in_fp32,
)
return hidden_states
def forward(self, static_z, x, return_features=False, inference_params=None,
if_random_cls_token_position=False, if_random_token_rank=False,
feat_len_s=None):
x = self.forward_features(static_z, x, inference_params, if_random_cls_token_position, if_random_token_rank)
if return_features:
return x
return x
if self.conv_type == 0:
self.kernel_size = ['K3']
elif self.conv_type == 1:
self.kernel_size = ['K5', "P2"]
elif self.conv_type == 2:
self.kernel_size = ['K5', "P2", 'K5', "P2"]
modules = []
for layer_idx, ks in enumerate(self.kernel_size):
input_sz = self.input_size if layer_idx == 0 else self.hidden_size
if ks[0] == 'P':
modules.append(nn.MaxPool1d(kernel_size=int(ks[1]), ceil_mode=False))
elif ks[0] == 'K':
modules.append(
nn.Conv1d(input_sz, self.hidden_size, kernel_size=int(ks[1]), stride=1, padding=0)
)
modules.append(nn.BatchNorm1d(self.hidden_size))
modules.append(nn.ReLU(inplace=True))
self.temporal_conv = nn.Sequential(*modules)
def forward(self, x):
x = self.temporal_conv(x.permute(0,2,1))
return x.permute(0,2,1)
class V_encoder(nn.Module):
def init (self, emb_size, feature_size):
super(V_encoder, self).init ()
code Copy code
self.src_emb = nn.Linear(feature_size, emb_size)
modules = []
modules.append(nn.BatchNorm1d(emb_size))
modules.append(nn.ReLU(inplace=True))
self.bn_ac = nn.Sequential(*modules)
for m in self.modules():
if isinstance(m, (nn.Conv1d,nn.Linear)):
nn.init.xavier_uniform_(m.weight, gain=nn.init.calculate_gain('relu'))
elif isinstance(m, nn.BatchNorm1d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
def forward(self, src:torch.Tensor):
src = self.src_emb(src)
src = self.bn_ac(src.permute(0,2,1)).permute(0,2,1)
return src
class SignModel(nn.Module):
def init (self, config, args, embed_dim=1024):
super(SignModel, self).init ()
self.args = args
self.resnet = resnet(name="resnet18")
self.time_mamba = time_mamba()
self.mbart = MBartForConditionalGeneration.from_pretrained(config['model']['visual_encoder'])
self.conv_1d = TemporalConv(input_size=512, hidden_size=1024, conv_type=2)
self.sign_emb = V_encoder(emb_size=embed_dim, feature_size=embed_dim)
self.embed_scale = 1.0
code Copy code
def __str__(self):
model_parameters = filter(lambda p: p.requires_grad, self.parameters())
params = sum([np.prod(p.size()) for p in model_parameters])
return super().__str__() + '\nTrainable parameters: {}'.format(params)
def visual_forward(self, src_input):
attention_mask = src_input['attention_mask']
out_visual = self.resnet(src_input['input_ids'].cuda(), src_input['src_length_batch'])
out_visual = self.time_mamba(out_visual)
frames_feature = self.conv_1d(out_visual)
inputs_embeds = self.sign_emb(frames_feature)
inputs_embeds = self.embed_scale * inputs_embeds
return inputs_embeds, attention_mask
def forward(self, src_input, tgt_input):
inputs_embeds, attention_mask = self.visual_forward(src_input)
out = self.mbart(inputs_embeds = inputs_embeds,
attention_mask = attention_mask.cuda(),
labels = tgt_input['input_ids'].cuda(),
decoder_attention_mask = tgt_input['attention_mask'].cuda(),
return_dict = True,
)
return out['logits']
def generate(self,src_input, max_new_tokens, num_beams, decoder_start_token_id):
inputs_embeds, attention_mask = self.visual_forward(src_input)
out = self.mbart.generate(inputs_embeds = inputs_embeds,
attention_mask = attention_mask.cuda(),max_new_tokens=max_new_tokens,num_beams = num_beams,
decoder_start_token_id=decoder_start_token_id
)
return out
all = [
'vim_tiny_patch16_224', 'vim_small_patch16_224', 'vim_base_patch16_224',
'vim_tiny_patch16_384', 'vim_small_patch16_384', 'vim_base_patch16_384',
]
class PatchEmbed(nn.Module):
""" 2D Image to Patch Embedding
"""
def init (self, img_size=224, patch_size=16, stride=16, in_chans=3, embed_dim=768, norm_layer=None, flatten=True):
super().init ()
img_size = to_2tuple(img_size)
patch_size = to_2tuple(patch_size)
self.img_size = img_size
self.patch_size = patch_size
self.grid_size = ((img_size[0] - patch_size[0]) // stride + 1, (img_size[1] - patch_size[1]) // stride + 1)
self.num_patches = self.grid_size[0] * self.grid_size[1]
self.flatten = flatten
code Copy code
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=stride)
self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
def forward(self, x):
B, C, H, W = x.shape
x = self.proj(x)
if self.flatten:
x = x.flatten(2).transpose(1, 2) # BCHW -> BNC
x = self.norm(x)
return x
class Block(nn.Module):
def init (
self, dim, mixer_cls, norm_cls=nn.LayerNorm, fused_add_norm=False, residual_in_fp32=False,drop_path=0.,
):
"""
Simple block wrapping a mixer class with LayerNorm/RMSNorm and residual connection"
code Copy code
This Block has a slightly different structure compared to a regular
prenorm Transformer block.
The standard block is: LN -> MHA/MLP -> Add.
[Ref: https://arxiv.org/abs/2002.04745]
Here we have: Add -> LN -> Mixer, returning both
the hidden_states (output of the mixer) and the residual.
This is purely for performance reasons, as we can fuse add and LayerNorm.
The residual needs to be provided (except for the very first block).
"""
super().__init__()
self.residual_in_fp32 = residual_in_fp32
self.fused_add_norm = fused_add_norm
self.mixer = mixer_cls(dim)
self.norm = norm_cls(dim)
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
if self.fused_add_norm:
assert RMSNorm is not None, "RMSNorm import fails"
assert isinstance(
self.norm, (nn.LayerNorm, RMSNorm)
), "Only LayerNorm and RMSNorm are supported for fused_add_norm"
def forward(
self, hidden_states: Tensor, residual: Optional[Tensor] = None, inference_params=None
):
r"""Pass the input through the encoder layer.
Args:
hidden_states: the sequence to the encoder layer (required).
residual: hidden_states = Mixer(LN(residual))
"""
fused_add_norm_fn = rms_norm_fn if isinstance(self.norm, RMSNorm) else layer_norm_fn
hidden_states, residual = fused_add_norm_fn(
hidden_states,
self.norm.weight,
self.norm.bias,
residual=residual,
prenorm=True,
residual_in_fp32=self.residual_in_fp32,
eps=self.norm.eps,
)
hidden_states = self.mixer(hidden_states, inference_params=inference_params)
return hidden_states, residual
def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
return self.mixer.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs)
def create_block(
d_model,
ssm_cfg=None,
norm_epsilon=1e-5,
drop_path=0.,
rms_norm=False,
residual_in_fp32=False,
fused_add_norm=False,
layer_idx=None,
device=None,
dtype=None,
if_bimamba=False,
bimamba_type="none",
if_devide_out=False,
init_layer_scale=None,
):
if if_bimamba:
bimamba_type = "v1"
if ssm_cfg is None:
ssm_cfg = {}
factory_kwargs = {"device": device, "dtype": dtype}
mixer_cls = partial(Mamba, layer_idx=layer_idx, bimamba_type=bimamba_type, if_devide_out=if_devide_out, init_layer_scale=init_layer_scale, **ssm_cfg, **factory_kwargs)
norm_cls = partial(
nn.LayerNorm if not rms_norm else RMSNorm, eps=norm_epsilon, **factory_kwargs
)
block = Block(
d_model,
mixer_cls,
norm_cls=norm_cls,
drop_path=drop_path,
fused_add_norm=fused_add_norm,
residual_in_fp32=residual_in_fp32,
)
block.layer_idx = layer_idx
return block
#################### 新增类
class VisionMamba(nn.Module):
def init (self,
img_size =224,
patch_size=16,
stride=16,
depth =24,
embed_dim = 192,
channels = 3,
num_classes = 1000,
ssm_cfg = None,
drop_rate = 0.,
drop_path_rate = 0.1,
norm_epsilon: float = 1e-5,
rms_norm: bool = False,
initializer_cfg = None,
fused_add_norm = False,
residual_in_fp32 = False,
device = None,
dtype = None,
ft_seq_len = None,
pt_hw_seq_len = 14,
if_bidirectional = False,
final_pool_type = 'none',
if_abs_pos_embed = False,
if_rope = False,
if_rope_residual = False,
flip_img_sequences_ratio = -1.,
if_bimamba = False,
bimamba_type = "none",
if_cls_token = False,
if_devide_out = False,
init_layer_scale = None,
use_double_cls_token = False,
use_middle_cls_token = False,
**kwargs):
factory_kwargs = {"device": device, "dtype": dtype}
kwargs.update(factory_kwargs)
super().init ()
self.residual_in_fp32 = residual_in_fp32
self.fused_add_norm = fused_add_norm
self.if_bidirectional = if_bidirectional
self.final_pool_type = final_pool_type
self.if_abs_pos_embed = if_abs_pos_embed
self.if_rope = if_rope
self.if_rope_residual = if_rope_residual
self.flip_img_sequences_ratio = flip_img_sequences_ratio
self.if_cls_token = if_cls_token
self.use_double_cls_token = use_double_cls_token
self.use_middle_cls_token = use_middle_cls_token
self.num_tokens = 1 if if_cls_token else 0
code Copy code
#### 新增 :Resnet 特征提取器
self.resnet = ResNetExtractor(resnet_type ="resnet18")
#### 新增时间卷积层
self.temporal_conv = TemporalConv(input_size=512, hidden_size=embed_dim)
# pretrain parameters
self.num_classes = num_classes
self.d_model = self.num_features = self.embed_dim = embed_dim
self.patch_embed = PatchEmbed(
img_size=img_size, patch_size=patch_size, stride=stride, in_chans=channels, embed_dim=embed_dim)
num_patches = self.patch_embed.num_patches
if if_cls_token:
if use_double_cls_token:
self.cls_token_head = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
self.cls_token_tail = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
self.num_tokens = 2
else:
self.cls_token = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
if if_abs_pos_embed:
self.pos_embed_x = nn.Parameter(torch.zeros(1, 256, self.embed_dim))
self.pos_embed_z = nn.Parameter(torch.zeros(1, 64, self.embed_dim))
self.pos_embed_dynamic_z = nn.Parameter(torch.zeros(1, 64, self.embed_dim))
self.pos_drop = nn.Dropout(p=drop_rate)
if if_rope:
half_head_dim = embed_dim // 2
hw_seq_len = img_size // patch_size
self.rope = VisionRotaryEmbeddingFast(
dim=half_head_dim,
pt_seq_len=pt_hw_seq_len,
ft_seq_len=hw_seq_len
)
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)]
inter_dpr = [0.0] + dpr
self.drop_path = DropPath(drop_path_rate) if drop_path_rate > 0. else nn.Identity()
self.layers = nn.ModuleList(
[
create_block(
embed_dim,
ssm_cfg=ssm_cfg,
norm_epsilon=norm_epsilon,
rms_norm=rms_norm,
residual_in_fp32=residual_in_fp32,
fused_add_norm=fused_add_norm,
layer_idx=i,
if_bimamba=if_bimamba,
bimamba_type=bimamba_type,
drop_path=inter_dpr[i],
if_devide_out=if_devide_out,
init_layer_scale=init_layer_scale,
**factory_kwargs,
)
for i in range(depth)
]
)
# output head
self.norm_f = (nn.LayerNorm if not rms_norm else RMSNorm)(
embed_dim, eps=norm_epsilon, **factory_kwargs
)
self.patch_embed.apply(segm_init_weights)
if if_abs_pos_embed:
trunc_normal_(self.pos_embed_x, std=.02)
trunc_normal_(self.pos_embed_z, std=.02)
if if_cls_token:
if use_double_cls_token:
trunc_normal_(self.cls_token_head, std=.02)
trunc_normal_(self.cls_token_tail, std=.02)
else:
trunc_normal_(self.cls_token, std=.02)
self.apply(
partial(
_init_weights,
n_layer=depth,
**(initializer_cfg if initializer_cfg is not None else {}),
)
)
def forward_features(self, z, x, inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False):
# 使用ResNet提取图像特征
x = self.resnet(x)
x = self.temporal_conv(x)
B, N, C = x.shape
if self.if_abs_pos_embed:
x = x + self.pos_embed_x
z = z + self.pos_embed_z
x = torch.cat((z, x), dim=1)
x = self.pos_drop(x)
# 下面是原有逻辑
residual = None
hidden_states = x
for layer in self.layers:
hidden_states, residual = layer(
hidden_states, residual, inference_params=inference_params
)
fused_add_norm_fn = rms_norm_fn if isinstance(self.norm_f, RMSNorm) else layer_norm_fn
hidden_states = fused_add_norm_fn(
self.drop_path(hidden_states),
self.norm_f.weight,
self.norm_f.bias,
eps=self.norm_f.eps,
residual=residual,
prenorm=False,
residual_in_fp32=self.residual_in_fp32,
)
return hidden_states
def foward_dynamic_features(self, stacked_template, inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False):
# print('1111111111111111')
B, M, C, H, W = stacked_template.size()
# print('stacked_template.size():', stacked_template.size()) # stacked_template.size(): torch.Size([2, 7, 3, 128, 128]) BatchSize
# 初始化一个空的列表用于存放打乱后的模板
shuffled_templates = []
# 遍历每个 batch
for i in range(B):
# 取出当前 batch 的模板,形状为 (M, C, H, W)
batch_templates = stacked_template[i]
# 将当前 batch 内的模板顺序打乱
indices = torch.randperm(M)
batch_templates = batch_templates[indices]
# 进行 Patch Embedding 操作并展平
patch_embeddings = self.patch_embed(batch_templates) # 形状假设为 (M, N, D)
flattened_embeddings = patch_embeddings.flatten(0, 1) # 形状变为 (M * N, D)
# 将打乱并处理后的模板加入新的列表
shuffled_templates.append(flattened_embeddings)
# 将列表展平并堆叠为一个新的张量,形状为 (B, M * N, D)
shuffled_templates = torch.stack(shuffled_templates, dim=0)
x = self.pos_drop(shuffled_templates)
if_flip_img_sequences = False
# mamba impl
residual = None
hidden_states = x
for layer in self.layers:
hidden_states, residual = layer(
hidden_states, residual, inference_params=inference_params
)
# Set prenorm=False here since we don't need the residual
fused_add_norm_fn = rms_norm_fn if isinstance(self.norm_f, RMSNorm) else layer_norm_fn
hidden_states = fused_add_norm_fn( # hidden_states.shape = torch.Size([2, 320, 384])
self.drop_path(hidden_states),
self.norm_f.weight,
self.norm_f.bias,
eps=self.norm_f.eps,
residual=residual,
prenorm=False,
residual_in_fp32=self.residual_in_fp32,
)
return hidden_states
def forward_tripple_features(self, dynamic_z, static_z, x, inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False):
# taken from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
# with slight modifications to add the dist_token
# print('pre_x.shape:',x.shape) # torch.Size([2, 3, 256, 256])
x = self.patch_embed(x) #x.shape = torch.Size([B, 3, 224, 224]) -> torch.Size([2, 196, 384])
z = self.patch_embed(static_z)
# print('tri_x.shape:', x.shape) # tri_x.shape: torch.Size([2, 256, 384])
B, M, _ = x.shape
# print('BM_x.shape:', x.shape) # BM_x.shape: torch.Size([2, 256, 384])
x = x + self.pos_embed_x # x = x + positon_embemding =torch.Size([B, 196, 384]) + torch.Size([1, 196, 384]) = torch.Size([B, 196, 384])
z = z + self.pos_embed_z
dynamic_z = dynamic_z + self.pos_embed_dynamic_z
x = torch.cat((z, dynamic_z, x), dim=1)
# x = torch.cat((dynamic_z, z, x), dim=1)
x = self.pos_drop(x) # x.shape = torch.Size([B, 196, 384])
if_flip_img_sequences = False
# mamba impl
residual = None
hidden_states = x
for layer in self.layers:
hidden_states, residual = layer(
hidden_states, residual, inference_params=inference_params
)
fused_add_norm_fn = rms_norm_fn
hidden_states = fused_add_norm_fn( # hidden_states.shape = torch.Size([2, 320, 384])
self.drop_path(hidden_states),
self.norm_f.weight,
self.norm_f.bias,
eps=self.norm_f.eps,
residual=residual,
prenorm=False,
residual_in_fp32=self.residual_in_fp32,
)
return hidden_states
def forward(self, static_z, dynamic_z, x, return_features=False, inference_params=None,
if_random_cls_token_position=False, if_random_token_rank=False,
feat_len_s=None, feat_len_z=None):
x = self.resnet(x)
dynamic_z = self.foward_dynamic_features(dynamic_z)[:, -feat_len_z:]
x = self.forward_tripple_features(dynamic_z, static_z, x,
inference_params, if_random_cls_token_position=if_random_cls_token_position,
if_random_token_rank=if_random_token_rank)
if return_features:
return x
return x
########## 下文中加载 预训练模型权重
@register_model
def vim_tiny_patch16_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, embed_dim=192, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='mean', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
checkpoint = torch.hub.load_state_dict_from_url(
url="to.do",
map_location="cpu", check_hash=True
)
model.load_state_dict(checkpoint["model"])
return model
@register_model
def vim_tiny_patch16_stride8_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, stride=8, embed_dim=192, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='mean', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
checkpoint = torch.hub.load_state_dict_from_url(
url="to.do",
map_location="cpu", check_hash=True
)
model.load_state_dict(checkpoint["model"])
return model
LIGHT @register_model
def vim_small_patch16_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, embed_dim=384, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='all', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
# checkpoint = torch.hub.load_state_dict_from_url(
# url="to.do",
# map_location="cpu", check_hash=True
# )
# model.load_state_dict(checkpoint["model"])
code Copy code
checkpoint = torch.load(pretrained, map_location="cpu")
missing_keys, unexpected_keys = model.load_state_dict(checkpoint["model"], strict=False)
print('Load pretrained model from: ' + pretrained)
return model
@register_model
def vim_small_patch16_stride8_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, stride=8, embed_dim=384, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='mean', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
checkpoint = torch.hub.load_state_dict_from_url(
url="to.do",
map_location="cpu", check_hash=True
)
model.load_state_dict(checkpoint["model"])
return model中,提取特征的部分是什么?
class Block(nn.Module):
def init (
self, dim, mixer_cls, norm_cls=nn.LayerNorm, fused_add_norm=False, residual_in_fp32=False,drop_path=0.,
):
"""
Simple block wrapping a mixer class with LayerNorm/RMSNorm and residual connection"
code Copy code
This Block has a slightly different structure compared to a regular
prenorm Transformer block.
The standard block is: LN -> MHA/MLP -> Add.
[Ref: https://arxiv.org/abs/2002.04745]
Here we have: Add -> LN -> Mixer, returning both
the hidden_states (output of the mixer) and the residual.
This is purely for performance reasons, as we can fuse add and LayerNorm.
The residual needs to be provided (except for the very first block).
"""
super().__init__()
self.residual_in_fp32 = residual_in_fp32
self.fused_add_norm = fused_add_norm
self.mixer = mixer_cls(dim)
self.norm = norm_cls(dim)
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
if self.fused_add_norm:
assert RMSNorm is not None, "RMSNorm import fails"
assert isinstance(
self.norm, (nn.LayerNorm, RMSNorm)
), "Only LayerNorm and RMSNorm are supported for fused_add_norm"
def forward(
self, hidden_states: Tensor, residual: Optional[Tensor] = None, inference_params=None
):
r"""Pass the input through the encoder layer.
Args:
hidden_states: the sequence to the encoder layer (required).
residual: hidden_states = Mixer(LN(residual))
"""
fused_add_norm_fn = rms_norm_fn if isinstance(self.norm, RMSNorm) else layer_norm_fn
hidden_states, residual = fused_add_norm_fn(
hidden_states,
self.norm.weight,
self.norm.bias,
residual=residual,
prenorm=True,
residual_in_fp32=self.residual_in_fp32,
eps=self.norm.eps,
)
hidden_states = self.mixer(hidden_states, inference_params=inference_params)
return hidden_states, residual
def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
return self.mixer.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs)
def create_block(
d_model,
ssm_cfg=None,
norm_epsilon=1e-5,
drop_path=0.,
rms_norm=False,
residual_in_fp32=False,
fused_add_norm=False,
layer_idx=None,
device=None,
dtype=None,
if_bimamba=False,
bimamba_type="none",
if_devide_out=False,
init_layer_scale=None,
):
if if_bimamba:
bimamba_type = "v1"
if ssm_cfg is None:
ssm_cfg = {}
factory_kwargs = {"device": device, "dtype": dtype}
mixer_cls = partial(Mamba, layer_idx=layer_idx, bimamba_type=bimamba_type, if_devide_out=if_devide_out, init_layer_scale=init_layer_scale, **ssm_cfg, **factory_kwargs)
norm_cls = partial(
nn.LayerNorm if not rms_norm else RMSNorm, eps=norm_epsilon, **factory_kwargs
)
block = Block(
d_model,
mixer_cls,
norm_cls=norm_cls,
drop_path=drop_path,
fused_add_norm=fused_add_norm,
residual_in_fp32=residual_in_fp32,
)
block.layer_idx = layer_idx
return block
def init_weights(
module,
n_layer,
initializer_range=0.02, # Now only used for embedding layer.
rescale_prenorm_residual=True,
n_residuals_per_layer=1, # Change to 2 if we have MLP
):
if isinstance(module, nn.Linear):
if module.bias is not None:
if not getattr(module.bias, "no_reinit", False):
nn.init.zeros (module.bias)
elif isinstance(module, nn.Embedding):
nn.init.normal (module.weight, std=initializer_range)
code Copy code
if rescale_prenorm_residual:
# Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
# > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
# > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
# > -- GPT-2 :: https://openai.com/blog/better-language-models/
#
# Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
for name, p in module.named_parameters():
if name in ["out_proj.weight", "fc2.weight"]:
# Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
# Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
# We need to reinit p since this code could be called multiple times
# Having just p *= scale would repeatedly scale it down
nn.init.kaiming_uniform_(p, a=math.sqrt(5))
with torch.no_grad():
p /= math.sqrt(n_residuals_per_layer * n_layer)
def segm_init_weights(m):
if isinstance(m, nn.Linear):
trunc_normal_(m.weight, std=0.02)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.Conv2d):
# NOTE conv was left to pytorch default in my original init
lecun_normal_(m.weight)
if m.bias is not None:
nn.init.zeros_(m.bias)
elif isinstance(m, (nn.LayerNorm, nn.GroupNorm, nn.BatchNorm2d)):
nn.init.zeros_(m.bias)
nn.init.ones_(m.weight)
class VisionMamba(nn.Module):
def init (self,
img_size=224,
patch_size=16,
stride=16,
depth=24,
embed_dim=192,
channels=3,
num_classes=1000,
ssm_cfg=None,
drop_rate=0.,
drop_path_rate=0.1,
norm_epsilon: float = 1e-5,
rms_norm: bool = False,
initializer_cfg=None,
fused_add_norm=False,
residual_in_fp32=False,
device=None,
dtype=None,
ft_seq_len=None,
pt_hw_seq_len=14,
if_bidirectional=False,
final_pool_type='none',
if_abs_pos_embed=False,
if_rope=False,
if_rope_residual=False,
flip_img_sequences_ratio=-1.,
if_bimamba=False,
bimamba_type="none",
if_cls_token=False,
if_devide_out=False,
init_layer_scale=None,
use_double_cls_token=False,
use_middle_cls_token=False,
**kwargs):
factory_kwargs = {"device": device, "dtype": dtype}
# add factory_kwargs into kwargs
kwargs.update(factory_kwargs)
super().init ()
self.residual_in_fp32 = residual_in_fp32
self.fused_add_norm = fused_add_norm
self.if_bidirectional = if_bidirectional
self.final_pool_type = final_pool_type
self.if_abs_pos_embed = if_abs_pos_embed
self.if_rope = if_rope
self.if_rope_residual = if_rope_residual
self.flip_img_sequences_ratio = flip_img_sequences_ratio
# self.if_cls_token = if_cls_token
self.if_cls_token = False
self.use_double_cls_token = use_double_cls_token
self.use_middle_cls_token = use_middle_cls_token
self.num_tokens = 1 if if_cls_token else 0
code Copy code
# pretrain parameters
self.num_classes = num_classes
self.d_model = self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
self.patch_embed = PatchEmbed(
img_size=img_size, patch_size=patch_size, stride=stride, in_chans=channels, embed_dim=embed_dim)
num_patches = self.patch_embed.num_patches
if if_cls_token:
if use_double_cls_token:
self.cls_token_head = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
self.cls_token_tail = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
self.num_tokens = 2
else:
self.cls_token = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
# self.num_tokens = 1
if if_abs_pos_embed:
# self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + self.num_tokens, self.embed_dim))
self.pos_embed_x = nn.Parameter(torch.zeros(1, 256, self.embed_dim))
self.pos_embed_z = nn.Parameter(torch.zeros(1, 64, self.embed_dim))
self.pos_embed_dynamic_z = nn.Parameter(torch.zeros(1, 64, self.embed_dim))
self.pos_drop = nn.Dropout(p=drop_rate)
if if_rope:
half_head_dim = embed_dim // 2
hw_seq_len = img_size // patch_size
self.rope = VisionRotaryEmbeddingFast(
dim=half_head_dim,
pt_seq_len=pt_hw_seq_len,
ft_seq_len=hw_seq_len
)
# self.head = nn.Linear(self.num_features, num_classes) if num_classes > 0 else nn.Identity()
# TODO: release this comment
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
# import ipdb;ipdb.set_trace()
inter_dpr = [0.0] + dpr
self.drop_path = DropPath(drop_path_rate) if drop_path_rate > 0. else nn.Identity()
# transformer blocks
self.layers = nn.ModuleList(
[
create_block(
embed_dim,
ssm_cfg=ssm_cfg,
norm_epsilon=norm_epsilon,
rms_norm=rms_norm,
residual_in_fp32=residual_in_fp32,
fused_add_norm=fused_add_norm,
layer_idx=i,
if_bimamba=if_bimamba,
bimamba_type=bimamba_type,
drop_path=inter_dpr[i],
if_devide_out=if_devide_out,
init_layer_scale=init_layer_scale,
**factory_kwargs,
)
for i in range(depth)
]
)
# output head
self.norm_f = (nn.LayerNorm if not rms_norm else RMSNorm)(
embed_dim, eps=norm_epsilon, **factory_kwargs
)
# self.pre_logits = nn.Identity()
# original init
self.patch_embed.apply(segm_init_weights)
# self.head.apply(segm_init_weights)
if if_abs_pos_embed:
trunc_normal_(self.pos_embed_x, std=.02)
trunc_normal_(self.pos_embed_z, std=.02)
if if_cls_token:
if use_double_cls_token:
trunc_normal_(self.cls_token_head, std=.02)
trunc_normal_(self.cls_token_tail, std=.02)
else:
trunc_normal_(self.cls_token, std=.02)
# mamba init
self.apply(
partial(
_init_weights,
n_layer=depth,
**(initializer_cfg if initializer_cfg is not None else {}),
)
)
def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
return {
i: layer.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs)
for i, layer in enumerate(self.layers)
}
@torch.jit.ignore
def no_weight_decay(self):
return {"pos_embed", "cls_token", "dist_token", "cls_token_head", "cls_token_tail"}
@torch.jit.ignore()
def load_pretrained(self, checkpoint_path, prefix=""):
_load_weights(self, checkpoint_path, prefix)
# 未调用
def forward_features(self, z, x, inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False):
x = self.patch_embed(x) #x.shape = torch.Size([B, 3, 224, 224]) -> torch.Size([2, 196, 384])
z = self.patch_embed(z)
B, M, _ = x.shape
if self.if_abs_pos_embed: #YES # self.if_abs_pos_embed = true
x = x + self.pos_embed_x # x = x + positon_embemding =torch.Size([B, 196, 384]) + torch.Size([1, 196, 384]) = torch.Size([B, 196, 384])
z = z + self.pos_embed_z
x = torch.cat((z, x), dim=1)
x = self.pos_drop(x) # x.shape = torch.Size([B, 196, 384])
if_flip_img_sequences = False
# NO
# mamba impl
residual = None
hidden_states = x
for layer in self.layers:
hidden_states, residual = layer(
hidden_states, residual, inference_params=inference_params
)
fused_add_norm_fn = rms_norm_fn if isinstance(self.norm_f, RMSNorm) else layer_norm_fn
hidden_states = fused_add_norm_fn(
self.drop_path(hidden_states),
self.norm_f.weight,
self.norm_f.bias,
eps=self.norm_f.eps,
residual=residual,
prenorm=False,
residual_in_fp32=self.residual_in_fp32,
)
return hidden_states
def foward_dynamic_features(self, stacked_template, inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False):
# print('1111111111111111')
B, M, C, H, W = stacked_template.size()
# print('stacked_template.size():', stacked_template.size()) # stacked_template.size(): torch.Size([2, 7, 3, 128, 128]) BatchSize
# 初始化一个空的列表用于存放打乱后的模板
shuffled_templates = []
# 遍历每个 batch
for i in range(B):
# 取出当前 batch 的模板,形状为 (M, C, H, W)
batch_templates = stacked_template[i]
# 将当前 batch 内的模板顺序打乱
indices = torch.randperm(M)
batch_templates = batch_templates[indices]
# 进行 Patch Embedding 操作并展平
patch_embeddings = self.patch_embed(batch_templates) # 形状假设为 (M, N, D)
flattened_embeddings = patch_embeddings.flatten(0, 1) # 形状变为 (M * N, D)
# 将打乱并处理后的模板加入新的列表
shuffled_templates.append(flattened_embeddings)
# 将列表展平并堆叠为一个新的张量,形状为 (B, M * N, D)
shuffled_templates = torch.stack(shuffled_templates, dim=0)
x = self.pos_drop(shuffled_templates)
if_flip_img_sequences = False
# mamba impl
residual = None
hidden_states = x
for layer in self.layers:
hidden_states, residual = layer(
hidden_states, residual, inference_params=inference_params
)
# Set prenorm=False here since we don't need the residual
fused_add_norm_fn = rms_norm_fn if isinstance(self.norm_f, RMSNorm) else layer_norm_fn
hidden_states = fused_add_norm_fn( # hidden_states.shape = torch.Size([2, 320, 384])
self.drop_path(hidden_states),
self.norm_f.weight,
self.norm_f.bias,
eps=self.norm_f.eps,
residual=residual,
prenorm=False,
residual_in_fp32=self.residual_in_fp32,
)
return hidden_states
def forward_dynamic_features_inference(self, template_list, inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False):
'''
input shape:
template_list: python list. item: torch.tensor, (1, 3, 128, 128)
'''
# B = 1
# stacked_templates = template_list.flatten(0,1) #为了测速而作的调整
stacked_templates = torch.cat(template_list, dim=0)
x = self.patch_embed(stacked_templates)
B, N, C = x.shape
x = x.reshape(1, B*N, C)
x = self.pos_drop(x)
if_flip_img_sequences = False
# mamba impl
residual = None
hidden_states = x
for layer in self.layers:
hidden_states, residual = layer(
hidden_states, residual, inference_params=inference_params
)
fused_add_norm_fn = rms_norm_fn
hidden_states = fused_add_norm_fn( # hidden_states.shape = torch.Size([2, 320, 384])
self.drop_path(hidden_states),
self.norm_f.weight,
self.norm_f.bias,
eps=self.norm_f.eps,
residual=residual,
prenorm=False,
residual_in_fp32=self.residual_in_fp32,
)
return hidden_states
def forward_dynamic_features_speed_test(self, template_list, inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False):
'''
input shape:
template_list: python list. item: torch.tensor, (1, 3, 128, 128)
'''
# B = 1
stacked_templates = template_list.flatten(0,1) #为了测速而作的调整
# stacked_templates = torch.cat(template_list, dim=0)
x = self.patch_embed(stacked_templates)
B, N, C = x.shape
x = x.reshape(1, B*N, C)
x = self.pos_drop(x)
if_flip_img_sequences = False
# mamba impl
residual = None
hidden_states = x
for layer in self.layers:
hidden_states, residual = layer(
hidden_states, residual, inference_params=inference_params
)
fused_add_norm_fn = rms_norm_fn
hidden_states = fused_add_norm_fn( # hidden_states.shape = torch.Size([2, 320, 384])
self.drop_path(hidden_states),
self.norm_f.weight,
self.norm_f.bias,
eps=self.norm_f.eps,
residual=residual,
prenorm=False,
residual_in_fp32=self.residual_in_fp32,
)
return hidden_states
def forward_tripple_features(self, dynamic_z, static_z, x, inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False):
# taken from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
# with slight modifications to add the dist_token
# print('pre_x.shape:',x.shape) # torch.Size([2, 3, 256, 256])
x = self.patch_embed(x) #x.shape = torch.Size([B, 3, 224, 224]) -> torch.Size([2, 196, 384])
z = self.patch_embed(static_z)
# print('tri_x.shape:', x.shape) # tri_x.shape: torch.Size([2, 256, 384])
B, M, _ = x.shape
# print('BM_x.shape:', x.shape) # BM_x.shape: torch.Size([2, 256, 384])
x = x + self.pos_embed_x # x = x + positon_embemding =torch.Size([B, 196, 384]) + torch.Size([1, 196, 384]) = torch.Size([B, 196, 384])
z = z + self.pos_embed_z
dynamic_z = dynamic_z + self.pos_embed_dynamic_z
x = torch.cat((z, dynamic_z, x), dim=1)
# x = torch.cat((dynamic_z, z, x), dim=1)
x = self.pos_drop(x) # x.shape = torch.Size([B, 196, 384])
if_flip_img_sequences = False
# mamba impl
residual = None
hidden_states = x
for layer in self.layers:
hidden_states, residual = layer(
hidden_states, residual, inference_params=inference_params
)
fused_add_norm_fn = rms_norm_fn
hidden_states = fused_add_norm_fn( # hidden_states.shape = torch.Size([2, 320, 384])
self.drop_path(hidden_states),
self.norm_f.weight,
self.norm_f.bias,
eps=self.norm_f.eps,
residual=residual,
prenorm=False,
residual_in_fp32=self.residual_in_fp32,
)
return hidden_states
def forward(self, static_z, dynamic_z, x, return_features=False, inference_params=None,
if_random_cls_token_position=False, if_random_token_rank=False,
feat_len_s=None, feat_len_z=None):
dynamic_z = self.foward_dynamic_features(dynamic_z)[:, -feat_len_z:]
x = self.forward_tripple_features(dynamic_z, static_z, x,
inference_params, if_random_cls_token_position=if_random_cls_token_position,
if_random_token_rank=if_random_token_rank)
if return_features:
return x
# x = self.head(x)
if self.final_pool_type == 'max':
x = x.max(dim=1)[0]
return x
def inference(self, dynamic_z, static_z, x, return_features=False, inference_params=None,
if_random_cls_token_position=False, if_random_token_rank=False,
feat_len_s=None, feat_len_z=None):
'''
dynamic_z -> mamba hidden states
static_z -> raw template rgb image
x -> raw search rgb image
'''
dynamic_z = dynamic_z[:, -feat_len_z:]
x = self.forward_tripple_features(dynamic_z, static_z, x,
inference_params, if_random_cls_token_position=if_random_cls_token_position,
if_random_token_rank=if_random_token_rank)
return x
@register_model
def vim_tiny_patch16_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, embed_dim=192, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='mean', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
checkpoint = torch.hub.load_state_dict_from_url(
url="to.do",
map_location="cpu", check_hash=True
)
model.load_state_dict(checkpoint["model"])
return model
@register_model
def vim_tiny_patch16_stride8_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, stride=8, embed_dim=192, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='mean', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
checkpoint = torch.hub.load_state_dict_from_url(
url="to.do",
map_location="cpu", check_hash=True
)
model.load_state_dict(checkpoint["model"])
return model
LIGHT @register_model
def vim_small_patch16_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, embed_dim=384, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='all', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
# checkpoint = torch.hub.load_state_dict_from_url(
# url="to.do",
# map_location="cpu", check_hash=True
# )
# model.load_state_dict(checkpoint["model"])
code Copy code
checkpoint = torch.load(pretrained, map_location="cpu")
missing_keys, unexpected_keys = model.load_state_dict(checkpoint["model"], strict=False)
print('Load pretrained model from: ' + pretrained)
return model
@register_model
def vim_small_patch16_stride8_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, stride=8, embed_dim=384, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='mean', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
checkpoint = torch.hub.load_state_dict_from_url(
url="to.do",
map_location="cpu", check_hash=True
)
model.load_state_dict(checkpoint["model"])
return model,现在参考了import torch
import torch.nn as nn
import numpy as np
import torchvision
from transformers import MBartForConditionalGeneration, MBartPreTrainedModel, MBartModel, MBartConfig
from torch.nn.utils.rnn import pad_sequence
global definition from models_mamba import create_block
import math
from einops import rearrange, repeat
def make_resnet(name='resnet18'):
if name == 'resnet18':
model = torchvision.models.resnet18(pretrained=True)
elif name == 'resnet34':
model = torchvision.models.resnet34(pretrained=True)
elif name == 'resnet50':
model = torchvision.models.resnet50(pretrained=True)
elif name == 'resnet101':
model = torchvision.models.resnet101(pretrained=True)
else:
raise Exception('There are no supported resnet model {}.'.format(_('resnet')))
code Copy code
model.fc = nn.Identity()
return model
class resnet(nn.Module):
def init (self, name="resnet18"):
super(resnet, self).init ()
self.resnet = make_resnet(name=name)
code Copy code
def forward(self, x, lengths):
x = self.resnet(x)
x_batch = []
start = 0
for length in lengths:
end = start + length
x_batch.append(x[start:end])
start = end
x = pad_sequence(x_batch,padding_value=PAD_IDX,batch_first=True)
return x
class time_mamba(nn.Module):
def init (self):
super(time_mamba, self).init ()
code Copy code
self.mamba_block = create_block(d_model=512)
def forward(self, x):
hidden_x, res_x = self.mamba_block(x)
return hidden_x
class TemporalConv(nn.Module):
def init (self, input_size, hidden_size, conv_type=2):
super(TemporalConv, self).init ()
self.input_size = input_size
self.hidden_size = hidden_size
self.conv_type = conv_type
code Copy code
if self.conv_type == 0:
self.kernel_size = ['K3']
elif self.conv_type == 1:
self.kernel_size = ['K5', "P2"]
elif self.conv_type == 2:
self.kernel_size = ['K5', "P2", 'K5', "P2"]
modules = []
for layer_idx, ks in enumerate(self.kernel_size):
input_sz = self.input_size if layer_idx == 0 else self.hidden_size
if ks[0] == 'P':
modules.append(nn.MaxPool1d(kernel_size=int(ks[1]), ceil_mode=False))
elif ks[0] == 'K':
modules.append(
nn.Conv1d(input_sz, self.hidden_size, kernel_size=int(ks[1]), stride=1, padding=0)
)
modules.append(nn.BatchNorm1d(self.hidden_size))
modules.append(nn.ReLU(inplace=True))
self.temporal_conv = nn.Sequential(*modules)
def forward(self, x):
x = self.temporal_conv(x.permute(0,2,1))
return x.permute(0,2,1)
class V_encoder(nn.Module):
def init (self, emb_size, feature_size):
super(V_encoder, self).init ()
code Copy code
self.src_emb = nn.Linear(feature_size, emb_size)
modules = []
modules.append(nn.BatchNorm1d(emb_size))
modules.append(nn.ReLU(inplace=True))
self.bn_ac = nn.Sequential(*modules)
for m in self.modules():
if isinstance(m, (nn.Conv1d,nn.Linear)):
nn.init.xavier_uniform_(m.weight, gain=nn.init.calculate_gain('relu'))
elif isinstance(m, nn.BatchNorm1d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
def forward(self, src:torch.Tensor):
src = self.src_emb(src)
src = self.bn_ac(src.permute(0,2,1)).permute(0,2,1)
return src
class SignModel(nn.Module):
def init (self, config, args, embed_dim=1024):
super(SignModel, self).init ()
self.args = args
self.resnet = resnet(name="resnet18")
self.time_mamba = time_mamba()
self.mbart = MBartForConditionalGeneration.from_pretrained(config['model']['visual_encoder'])
self.conv_1d = TemporalConv(input_size=512, hidden_size=1024, conv_type=2)
self.sign_emb = V_encoder(emb_size=embed_dim, feature_size=embed_dim)
self.embed_scale = 1.0
code Copy code
def __str__(self):
model_parameters = filter(lambda p: p.requires_grad, self.parameters())
params = sum([np.prod(p.size()) for p in model_parameters])
return super().__str__() + '\nTrainable parameters: {}'.format(params)
def visual_forward(self, src_input):
attention_mask = src_input['attention_mask']
out_visual = self.resnet(src_input['input_ids'].cuda(), src_input['src_length_batch'])
out_visual = self.time_mamba(out_visual)
frames_feature = self.conv_1d(out_visual)
inputs_embeds = self.sign_emb(frames_feature)
inputs_embeds = self.embed_scale * inputs_embeds
return inputs_embeds, attention_mask
def forward(self, src_input, tgt_input):
inputs_embeds, attention_mask = self.visual_forward(src_input)
out = self.mbart(inputs_embeds = inputs_embeds,
attention_mask = attention_mask.cuda(),
labels = tgt_input['input_ids'].cuda(),
decoder_attention_mask = tgt_input['attention_mask'].cuda(),
return_dict = True,
)
return out['logits']
def generate(self,src_input, max_new_tokens, num_beams, decoder_start_token_id):
inputs_embeds, attention_mask = self.visual_forward(src_input)
out = self.mbart.generate(inputs_embeds = inputs_embeds,
attention_mask = attention_mask.cuda(),max_new_tokens=max_new_tokens,num_beams = num_beams,
decoder_start_token_id=decoder_start_token_id
)
return out
中提取视觉特征的网络,将原始模型修改为:# Copyright (c) 2015-present, Facebook, Inc.
All rights reserved. import torch
import torch.nn as nn
from functools import partial
from torch import Tensor
from typing import Optional
from timm.models.vision_transformer import VisionTransformer, cfg
from timm.models.registry import register_model
from timm.models.layers import trunc_normal , lecun_normal_
from timm.models.layers import DropPath, to_2tuple
from timm.models.vision_transformer import _load_weights
from collections import namedtuple
from mamba_ssm.modules.mamba_simple import Mamba
from mamba_ssm.utils.generation import GenerationMixin
from mamba_ssm.utils.hf import load_config_hf, load_state_dict_hf
from lib.models.ostrack.rope import *
import random
from lib.models.layers.head import build_box_head
import importlib
import lib.train.admin.settings as ws_settings
from .utils import combine_tokens, recover_tokens
try:
from mamba_ssm.ops.triton.layernorm import RMSNorm, layer_norm_fn, rms_norm_fn
except ImportError:
RMSNorm, layer_norm_fn, rms_norm_fn = None, None, None
################# 添加 Resnet 网络
import torchvision
from torch.nn.utils.rnn import pad_sequence
from einops import rearrange
class ResNetExtractor(nn.Module):
def init (self, resnet_type ="resnet18"):
super(ResNetExtractor, self).init ()
self.resnet = getattr(torchvision.models, resnet_type)(pretrained=True)
self.resnet.fc = nn.Identity()
code Copy code
def forward(self, x):
return self.resnet(x)
class TemporalConv(nn.Module):
def init (self, input_size, hidden_size, conv_type=2):
super(TemporalConv, self).init ()
self.input_size = input_size
self.hidden_size = hidden_size
self.kernel_size = ['K5','P2'] if conv_type == 2 else ['K3']
code Copy code
modules = []
for layer_idx, ks in enumerate(self.kernel_size):
input_sz = self.input_size if layer_idx == 0 else self.hidden_size
if ks[0] == 'P':
modules.append(nn.MaxPool1d(kernel_size=int(ks[1]), ceil_mode=False))
elif ks[0] == 'K':
modules.append(nn.Conv1d(input_sz, self.hidden_size, kernel_size=int(ks[1]), stride=1, padding=0))
modules.append(nn.BatchNorm1d(self.hidden_size))
modules.append(nn.ReLU(inplace=True))
self.temporal_conv = nn.Sequential(*modules)
def forward(self, x):
x = self.temporal_conv(x.permute(0, 2, 1))
return x.permute(0, 2, 1)
all = [
'vim_tiny_patch16_224', 'vim_small_patch16_224', 'vim_base_patch16_224',
'vim_tiny_patch16_384', 'vim_small_patch16_384', 'vim_base_patch16_384',
]
class PatchEmbed(nn.Module):
""" 2D Image to Patch Embedding
"""
def init (self, img_size=224, patch_size=16, stride=16, in_chans=3, embed_dim=768, norm_layer=None, flatten=True):
super().init ()
img_size = to_2tuple(img_size)
patch_size = to_2tuple(patch_size)
self.img_size = img_size
self.patch_size = patch_size
self.grid_size = ((img_size[0] - patch_size[0]) // stride + 1, (img_size[1] - patch_size[1]) // stride + 1)
self.num_patches = self.grid_size[0] * self.grid_size[1]
self.flatten = flatten
code Copy code
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=stride)
self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
def forward(self, x):
B, C, H, W = x.shape
x = self.proj(x)
if self.flatten:
x = x.flatten(2).transpose(1, 2) # BCHW -> BNC
x = self.norm(x)
return x
class Block(nn.Module):
def init (
self, dim, mixer_cls, norm_cls=nn.LayerNorm, fused_add_norm=False, residual_in_fp32=False,drop_path=0.,
):
"""
Simple block wrapping a mixer class with LayerNorm/RMSNorm and residual connection"
code Copy code
This Block has a slightly different structure compared to a regular
prenorm Transformer block.
The standard block is: LN -> MHA/MLP -> Add.
[Ref: https://arxiv.org/abs/2002.04745]
Here we have: Add -> LN -> Mixer, returning both
the hidden_states (output of the mixer) and the residual.
This is purely for performance reasons, as we can fuse add and LayerNorm.
The residual needs to be provided (except for the very first block).
"""
super().__init__()
self.residual_in_fp32 = residual_in_fp32
self.fused_add_norm = fused_add_norm
self.mixer = mixer_cls(dim)
self.norm = norm_cls(dim)
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
if self.fused_add_norm:
assert RMSNorm is not None, "RMSNorm import fails"
assert isinstance(
self.norm, (nn.LayerNorm, RMSNorm)
), "Only LayerNorm and RMSNorm are supported for fused_add_norm"
def forward(
self, hidden_states: Tensor, residual: Optional[Tensor] = None, inference_params=None
):
r"""Pass the input through the encoder layer.
Args:
hidden_states: the sequence to the encoder layer (required).
residual: hidden_states = Mixer(LN(residual))
"""
fused_add_norm_fn = rms_norm_fn if isinstance(self.norm, RMSNorm) else layer_norm_fn
hidden_states, residual = fused_add_norm_fn(
hidden_states,
self.norm.weight,
self.norm.bias,
residual=residual,
prenorm=True,
residual_in_fp32=self.residual_in_fp32,
eps=self.norm.eps,
)
hidden_states = self.mixer(hidden_states, inference_params=inference_params)
return hidden_states, residual
def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
return self.mixer.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs)
def create_block(
d_model,
ssm_cfg=None,
norm_epsilon=1e-5,
drop_path=0.,
rms_norm=False,
residual_in_fp32=False,
fused_add_norm=False,
layer_idx=None,
device=None,
dtype=None,
if_bimamba=False,
bimamba_type="none",
if_devide_out=False,
init_layer_scale=None,
):
if if_bimamba:
bimamba_type = "v1"
if ssm_cfg is None:
ssm_cfg = {}
factory_kwargs = {"device": device, "dtype": dtype}
mixer_cls = partial(Mamba, layer_idx=layer_idx, bimamba_type=bimamba_type, if_devide_out=if_devide_out, init_layer_scale=init_layer_scale, **ssm_cfg, **factory_kwargs)
norm_cls = partial(
nn.LayerNorm if not rms_norm else RMSNorm, eps=norm_epsilon, **factory_kwargs
)
block = Block(
d_model,
mixer_cls,
norm_cls=norm_cls,
drop_path=drop_path,
fused_add_norm=fused_add_norm,
residual_in_fp32=residual_in_fp32,
)
block.layer_idx = layer_idx
return block
#################### 新增类
class VisionMamba(nn.Module):
def init (self,
img_size =224,
patch_size=16,
stride=16,
depth =24,
embed_dim = 192,
channels = 3,
num_classes = 1000,
ssm_cfg = None,
drop_rate = 0.,
drop_path_rate = 0.1,
norm_epsilon: float = 1e-5,
rms_norm: bool = False,
initializer_cfg = None,
fused_add_norm = False,
residual_in_fp32 = False,
device = None,
dtype = None,
ft_seq_len = None,
pt_hw_seq_len = 14,
if_bidirectional = False,
final_pool_type = 'none',
if_abs_pos_embed = False,
if_rope = False,
if_rope_residual = False,
flip_img_sequences_ratio = -1.,
if_bimamba = False,
bimamba_type = "none",
if_cls_token = False,
if_devide_out = False,
init_layer_scale = None,
use_double_cls_token = False,
use_middle_cls_token = False,
**kwargs):
factory_kwargs = {"device": device, "dtype": dtype}
kwargs.update(factory_kwargs)
super().init ()
self.residual_in_fp32 = residual_in_fp32
self.fused_add_norm = fused_add_norm
self.if_bidirectional = if_bidirectional
self.final_pool_type = final_pool_type
self.if_abs_pos_embed = if_abs_pos_embed
self.if_rope = if_rope
self.if_rope_residual = if_rope_residual
self.flip_img_sequences_ratio = flip_img_sequences_ratio
self.if_cls_token = if_cls_token
self.use_double_cls_token = use_double_cls_token
self.use_middle_cls_token = use_middle_cls_token
self.num_tokens = 1 if if_cls_token else 0
code Copy code
#### 新增 :Resnet 特征提取器
self.resnet = ResNetExtractor(resnet_type ="resnet18")
#### 新增时间卷积层
self.temporal_conv = TemporalConv(input_size=512, hidden_size=embed_dim)
# pretrain parameters
self.num_classes = num_classes
self.d_model = self.num_features = self.embed_dim = embed_dim
self.patch_embed = PatchEmbed(
img_size=img_size, patch_size=patch_size, stride=stride, in_chans=channels, embed_dim=embed_dim)
num_patches = self.patch_embed.num_patches
if if_cls_token:
if use_double_cls_token:
self.cls_token_head = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
self.cls_token_tail = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
self.num_tokens = 2
else:
self.cls_token = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
if if_abs_pos_embed:
self.pos_embed_x = nn.Parameter(torch.zeros(1, 256, self.embed_dim))
self.pos_embed_z = nn.Parameter(torch.zeros(1, 64, self.embed_dim))
self.pos_embed_dynamic_z = nn.Parameter(torch.zeros(1, 64, self.embed_dim))
self.pos_drop = nn.Dropout(p=drop_rate)
if if_rope:
half_head_dim = embed_dim // 2
hw_seq_len = img_size // patch_size
self.rope = VisionRotaryEmbeddingFast(
dim=half_head_dim,
pt_seq_len=pt_hw_seq_len,
ft_seq_len=hw_seq_len
)
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)]
inter_dpr = [0.0] + dpr
self.drop_path = DropPath(drop_path_rate) if drop_path_rate > 0. else nn.Identity()
self.layers = nn.ModuleList(
[
create_block(
embed_dim,
ssm_cfg=ssm_cfg,
norm_epsilon=norm_epsilon,
rms_norm=rms_norm,
residual_in_fp32=residual_in_fp32,
fused_add_norm=fused_add_norm,
layer_idx=i,
if_bimamba=if_bimamba,
bimamba_type=bimamba_type,
drop_path=inter_dpr[i],
if_devide_out=if_devide_out,
init_layer_scale=init_layer_scale,
**factory_kwargs,
)
for i in range(depth)
]
)
# output head
self.norm_f = (nn.LayerNorm if not rms_norm else RMSNorm)(
embed_dim, eps=norm_epsilon, **factory_kwargs
)
self.patch_embed.apply(segm_init_weights)
if if_abs_pos_embed:
trunc_normal_(self.pos_embed_x, std=.02)
trunc_normal_(self.pos_embed_z, std=.02)
if if_cls_token:
if use_double_cls_token:
trunc_normal_(self.cls_token_head, std=.02)
trunc_normal_(self.cls_token_tail, std=.02)
else:
trunc_normal_(self.cls_token, std=.02)
self.apply(
partial(
_init_weights,
n_layer=depth,
**(initializer_cfg if initializer_cfg is not None else {}),
)
)
def forward_features(self, z, x, inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False):
# 使用ResNet提取图像特征
x = self.resnet(x)
x = self.temporal_conv(x)
B, N, C = x.shape
if self.if_abs_pos_embed:
x = x + self.pos_embed_x
z = z + self.pos_embed_z
x = torch.cat((z, x), dim=1)
x = self.pos_drop(x)
# 下面是原有逻辑
residual = None
hidden_states = x
for layer in self.layers:
hidden_states, residual = layer(
hidden_states, residual, inference_params=inference_params
)
fused_add_norm_fn = rms_norm_fn if isinstance(self.norm_f, RMSNorm) else layer_norm_fn
hidden_states = fused_add_norm_fn(
self.drop_path(hidden_states),
self.norm_f.weight,
self.norm_f.bias,
eps=self.norm_f.eps,
residual=residual,
prenorm=False,
residual_in_fp32=self.residual_in_fp32,
)
return hidden_states
def foward_dynamic_features(self, stacked_template, inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False):
# print('1111111111111111')
B, M, C, H, W = stacked_template.size()
# print('stacked_template.size():', stacked_template.size()) # stacked_template.size(): torch.Size([2, 7, 3, 128, 128]) BatchSize
# 初始化一个空的列表用于存放打乱后的模板
shuffled_templates = []
# 遍历每个 batch
for i in range(B):
# 取出当前 batch 的模板,形状为 (M, C, H, W)
batch_templates = stacked_template[i]
# 将当前 batch 内的模板顺序打乱
indices = torch.randperm(M)
batch_templates = batch_templates[indices]
# 进行 Patch Embedding 操作并展平
patch_embeddings = self.patch_embed(batch_templates) # 形状假设为 (M, N, D)
flattened_embeddings = patch_embeddings.flatten(0, 1) # 形状变为 (M * N, D)
# 将打乱并处理后的模板加入新的列表
shuffled_templates.append(flattened_embeddings)
# 将列表展平并堆叠为一个新的张量,形状为 (B, M * N, D)
shuffled_templates = torch.stack(shuffled_templates, dim=0)
x = self.pos_drop(shuffled_templates)
if_flip_img_sequences = False
# mamba impl
residual = None
hidden_states = x
for layer in self.layers:
hidden_states, residual = layer(
hidden_states, residual, inference_params=inference_params
)
# Set prenorm=False here since we don't need the residual
fused_add_norm_fn = rms_norm_fn if isinstance(self.norm_f, RMSNorm) else layer_norm_fn
hidden_states = fused_add_norm_fn( # hidden_states.shape = torch.Size([2, 320, 384])
self.drop_path(hidden_states),
self.norm_f.weight,
self.norm_f.bias,
eps=self.norm_f.eps,
residual=residual,
prenorm=False,
residual_in_fp32=self.residual_in_fp32,
)
return hidden_states
def forward_tripple_features(self, dynamic_z, static_z, x, inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False):
# taken from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
# with slight modifications to add the dist_token
# print('pre_x.shape:',x.shape) # torch.Size([2, 3, 256, 256])
x = self.patch_embed(x) #x.shape = torch.Size([B, 3, 224, 224]) -> torch.Size([2, 196, 384])
z = self.patch_embed(static_z)
# print('tri_x.shape:', x.shape) # tri_x.shape: torch.Size([2, 256, 384])
B, M, _ = x.shape
# print('BM_x.shape:', x.shape) # BM_x.shape: torch.Size([2, 256, 384])
x = x + self.pos_embed_x # x = x + positon_embemding =torch.Size([B, 196, 384]) + torch.Size([1, 196, 384]) = torch.Size([B, 196, 384])
z = z + self.pos_embed_z
dynamic_z = dynamic_z + self.pos_embed_dynamic_z
x = torch.cat((z, dynamic_z, x), dim=1)
# x = torch.cat((dynamic_z, z, x), dim=1)
x = self.pos_drop(x) # x.shape = torch.Size([B, 196, 384])
if_flip_img_sequences = False
# mamba impl
residual = None
hidden_states = x
for layer in self.layers:
hidden_states, residual = layer(
hidden_states, residual, inference_params=inference_params
)
fused_add_norm_fn = rms_norm_fn
hidden_states = fused_add_norm_fn( # hidden_states.shape = torch.Size([2, 320, 384])
self.drop_path(hidden_states),
self.norm_f.weight,
self.norm_f.bias,
eps=self.norm_f.eps,
residual=residual,
prenorm=False,
residual_in_fp32=self.residual_in_fp32,
)
return hidden_states
def forward(self, static_z, dynamic_z, x, return_features=False, inference_params=None,
if_random_cls_token_position=False, if_random_token_rank=False,
feat_len_s=None, feat_len_z=None):
#################### 新增 resnet提取特征
x = self.resnet(x)
x = self.temporal_conv(x)
#################################
dynamic_z = self.foward_dynamic_features(dynamic_z)[:, -feat_len_z:]
x = self.forward_tripple_features(dynamic_z, static_z, x,
inference_params, if_random_cls_token_position=if_random_cls_token_position,
if_random_token_rank=if_random_token_rank)
if return_features:
return x
return x
########## 下文中加载 预训练模型权重
@register_model
def vim_tiny_patch16_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, embed_dim=192, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='mean', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
checkpoint = torch.hub.load_state_dict_from_url(
url="to.do",
map_location="cpu", check_hash=True
)
model.load_state_dict(checkpoint["model"])
return model
@register_model
def vim_tiny_patch16_stride8_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, stride=8, embed_dim=192, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='mean', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
checkpoint = torch.hub.load_state_dict_from_url(
url="to.do",
map_location="cpu", check_hash=True
)
model.load_state_dict(checkpoint["model"])
return model
LIGHT @register_model
def vim_small_patch16_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, embed_dim=384, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='all', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
# checkpoint = torch.hub.load_state_dict_from_url(
# url="to.do",
# map_location="cpu", check_hash=True
# )
# model.load_state_dict(checkpoint["model"])
code Copy code
checkpoint = torch.load(pretrained, map_location="cpu")
missing_keys, unexpected_keys = model.load_state_dict(checkpoint["model"], strict=False)
print('Load pretrained model from: ' + pretrained)
return model
@register_model
def vim_small_patch16_stride8_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, stride=8, embed_dim=384, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='mean', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
checkpoint = torch.hub.load_state_dict_from_url(
url="to.do",
map_location="cpu", check_hash=True
)
model.load_state_dict(checkpoint["model"])
return model,检查逻辑是否正确?是否需要修改?给出相应的意见。
all = [
'vim_tiny_patch16_224', 'vim_small_patch16_224', 'vim_base_patch16_224',
'vim_tiny_patch16_384', 'vim_small_patch16_384', 'vim_base_patch16_384',
]
class PatchEmbed(nn.Module):
""" 2D Image to Patch Embedding
"""
def init (self, img_size=224, patch_size=16, stride=16, in_chans=3, embed_dim=768, norm_layer=None, flatten=True):
super().init ()
img_size = to_2tuple(img_size)
patch_size = to_2tuple(patch_size)
self.img_size = img_size
self.patch_size = patch_size
self.grid_size = ((img_size[0] - patch_size[0]) // stride + 1, (img_size[1] - patch_size[1]) // stride + 1)
self.num_patches = self.grid_size[0] * self.grid_size[1]
self.flatten = flatten
code Copy code
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=stride)
self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
def forward(self, x):
B, C, H, W = x.shape
# print('11x.shape:', x.shape) # 11x.shape: torch.Size([2, 3, 128, 128])
# assert H == self.img_size[0] and W == self.img_size[1], \
# f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
x = self.proj(x)
if self.flatten:
x = x.flatten(2).transpose(1, 2) # BCHW -> BNC
x = self.norm(x)
return x
class Block(nn.Module):
def init (
self, dim, mixer_cls, norm_cls=nn.LayerNorm, fused_add_norm=False, residual_in_fp32=False,drop_path=0.,
):
"""
Simple block wrapping a mixer class with LayerNorm/RMSNorm and residual connection"
code Copy code
This Block has a slightly different structure compared to a regular
prenorm Transformer block.
The standard block is: LN -> MHA/MLP -> Add.
[Ref: https://arxiv.org/abs/2002.04745]
Here we have: Add -> LN -> Mixer, returning both
the hidden_states (output of the mixer) and the residual.
This is purely for performance reasons, as we can fuse add and LayerNorm.
The residual needs to be provided (except for the very first block).
"""
super().__init__()
self.residual_in_fp32 = residual_in_fp32
self.fused_add_norm = fused_add_norm
self.mixer = mixer_cls(dim)
self.norm = norm_cls(dim)
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
if self.fused_add_norm:
assert RMSNorm is not None, "RMSNorm import fails"
assert isinstance(
self.norm, (nn.LayerNorm, RMSNorm)
), "Only LayerNorm and RMSNorm are supported for fused_add_norm"
def forward(
self, hidden_states: Tensor, residual: Optional[Tensor] = None, inference_params=None
):
r"""Pass the input through the encoder layer.
Args:
hidden_states: the sequence to the encoder layer (required).
residual: hidden_states = Mixer(LN(residual))
"""
fused_add_norm_fn = rms_norm_fn if isinstance(self.norm, RMSNorm) else layer_norm_fn
hidden_states, residual = fused_add_norm_fn(
hidden_states,
self.norm.weight,
self.norm.bias,
residual=residual,
prenorm=True,
residual_in_fp32=self.residual_in_fp32,
eps=self.norm.eps,
)
hidden_states = self.mixer(hidden_states, inference_params=inference_params)
return hidden_states, residual
def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
return self.mixer.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs)
def create_block(
d_model,
ssm_cfg=None,
norm_epsilon=1e-5,
drop_path=0.,
rms_norm=False,
residual_in_fp32=False,
fused_add_norm=False,
layer_idx=None,
device=None,
dtype=None,
if_bimamba=False,
bimamba_type="none",
if_devide_out=False,
init_layer_scale=None,
):
if if_bimamba:
bimamba_type = "v1"
if ssm_cfg is None:
ssm_cfg = {}
factory_kwargs = {"device": device, "dtype": dtype}
mixer_cls = partial(Mamba, layer_idx=layer_idx, bimamba_type=bimamba_type, if_devide_out=if_devide_out, init_layer_scale=init_layer_scale, **ssm_cfg, **factory_kwargs)
norm_cls = partial(
nn.LayerNorm if not rms_norm else RMSNorm, eps=norm_epsilon, **factory_kwargs
)
block = Block(
d_model,
mixer_cls,
norm_cls=norm_cls,
drop_path=drop_path,
fused_add_norm=fused_add_norm,
residual_in_fp32=residual_in_fp32,
)
block.layer_idx = layer_idx
return block
def init_weights(
module,
n_layer,
initializer_range=0.02, # Now only used for embedding layer.
rescale_prenorm_residual=True,
n_residuals_per_layer=1, # Change to 2 if we have MLP
):
if isinstance(module, nn.Linear):
if module.bias is not None:
if not getattr(module.bias, "no_reinit", False):
nn.init.zeros (module.bias)
elif isinstance(module, nn.Embedding):
nn.init.normal (module.weight, std=initializer_range)
code Copy code
if rescale_prenorm_residual:
# Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
# > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
# > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
# > -- GPT-2 :: https://openai.com/blog/better-language-models/
#
# Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
for name, p in module.named_parameters():
if name in ["out_proj.weight", "fc2.weight"]:
# Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
# Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
# We need to reinit p since this code could be called multiple times
# Having just p *= scale would repeatedly scale it down
nn.init.kaiming_uniform_(p, a=math.sqrt(5))
with torch.no_grad():
p /= math.sqrt(n_residuals_per_layer * n_layer)
def segm_init_weights(m):
if isinstance(m, nn.Linear):
trunc_normal_(m.weight, std=0.02)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.Conv2d):
# NOTE conv was left to pytorch default in my original init
lecun_normal_(m.weight)
if m.bias is not None:
nn.init.zeros_(m.bias)
elif isinstance(m, (nn.LayerNorm, nn.GroupNorm, nn.BatchNorm2d)):
nn.init.zeros_(m.bias)
nn.init.ones_(m.weight)
class VisionMamba(nn.Module):
def init (self,
img_size=224,
patch_size=16,
stride=16,
depth=24,
embed_dim=192,
channels=3,
num_classes=1000,
ssm_cfg=None,
drop_rate=0.,
drop_path_rate=0.1,
norm_epsilon: float = 1e-5,
rms_norm: bool = False,
initializer_cfg=None,
fused_add_norm=False,
residual_in_fp32=False,
device=None,
dtype=None,
ft_seq_len=None,
pt_hw_seq_len=14,
if_bidirectional=False,
final_pool_type='none',
if_abs_pos_embed=False,
if_rope=False,
if_rope_residual=False,
flip_img_sequences_ratio=-1.,
if_bimamba=False,
bimamba_type="none",
if_cls_token=False,
if_devide_out=False,
init_layer_scale=None,
use_double_cls_token=False,
use_middle_cls_token=False,
**kwargs):
factory_kwargs = {"device": device, "dtype": dtype}
# add factory_kwargs into kwargs
kwargs.update(factory_kwargs)
super().init ()
self.residual_in_fp32 = residual_in_fp32
self.fused_add_norm = fused_add_norm
self.if_bidirectional = if_bidirectional
self.final_pool_type = final_pool_type
self.if_abs_pos_embed = if_abs_pos_embed
self.if_rope = if_rope
self.if_rope_residual = if_rope_residual
self.flip_img_sequences_ratio = flip_img_sequences_ratio
# self.if_cls_token = if_cls_token
self.if_cls_token = False
self.use_double_cls_token = use_double_cls_token
self.use_middle_cls_token = use_middle_cls_token
self.num_tokens = 1 if if_cls_token else 0
####################
self.resnet = ResNetExtractor(resnet_type ="resnet18")
self.temporal_conv = TemporalConv(input_size=512, hidden_size=embed_dim)
#######################
# pretrain parameters
self.num_classes = num_classes
self.d_model = self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
code Copy code
self.patch_embed = PatchEmbed(
img_size=img_size, patch_size=patch_size, stride=stride, in_chans=channels, embed_dim=embed_dim)
num_patches = self.patch_embed.num_patches
if if_cls_token:
if use_double_cls_token:
self.cls_token_head = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
self.cls_token_tail = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
self.num_tokens = 2
else:
self.cls_token = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
# self.num_tokens = 1
if if_abs_pos_embed:
# self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + self.num_tokens, self.embed_dim))
self.pos_embed_x = nn.Parameter(torch.zeros(1, 256, self.embed_dim))
self.pos_embed_z = nn.Parameter(torch.zeros(1, 64, self.embed_dim))
self.pos_embed_dynamic_z = nn.Parameter(torch.zeros(1, 64, self.embed_dim))
self.pos_drop = nn.Dropout(p=drop_rate)
if if_rope:
half_head_dim = embed_dim // 2
hw_seq_len = img_size // patch_size
self.rope = VisionRotaryEmbeddingFast(
dim=half_head_dim,
pt_seq_len=pt_hw_seq_len,
ft_seq_len=hw_seq_len
)
# self.head = nn.Linear(self.num_features, num_classes) if num_classes > 0 else nn.Identity()
# TODO: release this comment
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
# import ipdb;ipdb.set_trace()
inter_dpr = [0.0] + dpr
self.drop_path = DropPath(drop_path_rate) if drop_path_rate > 0. else nn.Identity()
# transformer blocks
self.layers = nn.ModuleList(
[
create_block(
embed_dim,
ssm_cfg=ssm_cfg,
norm_epsilon=norm_epsilon,
rms_norm=rms_norm,
residual_in_fp32=residual_in_fp32,
fused_add_norm=fused_add_norm,
layer_idx=i,
if_bimamba=if_bimamba,
bimamba_type=bimamba_type,
drop_path=inter_dpr[i],
if_devide_out=if_devide_out,
init_layer_scale=init_layer_scale,
**factory_kwargs,
)
for i in range(depth)
]
)
# output head
self.norm_f = (nn.LayerNorm if not rms_norm else RMSNorm)(
embed_dim, eps=norm_epsilon, **factory_kwargs
)
# self.pre_logits = nn.Identity()
# original init
self.patch_embed.apply(segm_init_weights)
# self.head.apply(segm_init_weights)
if if_abs_pos_embed:
trunc_normal_(self.pos_embed_x, std=.02)
trunc_normal_(self.pos_embed_z, std=.02)
if if_cls_token:
if use_double_cls_token:
trunc_normal_(self.cls_token_head, std=.02)
trunc_normal_(self.cls_token_tail, std=.02)
else:
trunc_normal_(self.cls_token, std=.02)
# mamba init
self.apply(
partial(
_init_weights,
n_layer=depth,
**(initializer_cfg if initializer_cfg is not None else {}),
)
)
def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
return {
i: layer.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs)
for i, layer in enumerate(self.layers)
}
@torch.jit.ignore
def no_weight_decay(self):
return {"pos_embed", "cls_token", "dist_token", "cls_token_head", "cls_token_tail"}
@torch.jit.ignore()
def load_pretrained(self, checkpoint_path, prefix=""):
_load_weights(self, checkpoint_path, prefix)
# 未调用
def forward_features(self, z, x, inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False):
x = self.patch_embed(x) #x.shape = torch.Size([B, 3, 224, 224]) -> torch.Size([2, 196, 384])
z = self.patch_embed(z)
B, M, _ = x.shape
if self.if_abs_pos_embed: #YES # self.if_abs_pos_embed = true
x = x + self.pos_embed_x # x = x + positon_embemding =torch.Size([B, 196, 384]) + torch.Size([1, 196, 384]) = torch.Size([B, 196, 384])
z = z + self.pos_embed_z
x = torch.cat((z, x), dim=1)
x = self.pos_drop(x) # x.shape = torch.Size([B, 196, 384])
if_flip_img_sequences = False
# NO
# mamba impl
residual = None
hidden_states = x
for layer in self.layers:
hidden_states, residual = layer(
hidden_states, residual, inference_params=inference_params
)
fused_add_norm_fn = rms_norm_fn if isinstance(self.norm_f, RMSNorm) else layer_norm_fn
hidden_states = fused_add_norm_fn(
self.drop_path(hidden_states),
self.norm_f.weight,
self.norm_f.bias,
eps=self.norm_f.eps,
residual=residual,
prenorm=False,
residual_in_fp32=self.residual_in_fp32,
)
return hidden_states
def foward_dynamic_features(self, stacked_template, inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False):
# print('1111111111111111')
B, M, C, H, W = stacked_template.size()
# print('stacked_template.size():', stacked_template.size()) # stacked_template.size(): torch.Size([2, 7, 3, 128, 128]) BatchSize
# 初始化一个空的列表用于存放打乱后的模板
shuffled_templates = []
# 遍历每个 batch
for i in range(B):
# 取出当前 batch 的模板,形状为 (M, C, H, W)
batch_templates = stacked_template[i]
# 将当前 batch 内的模板顺序打乱
indices = torch.randperm(M)
batch_templates = batch_templates[indices]
# 进行 Patch Embedding 操作并展平
patch_embeddings = self.patch_embed(batch_templates) # 形状假设为 (M, N, D)
flattened_embeddings = patch_embeddings.flatten(0, 1) # 形状变为 (M * N, D)
# 将打乱并处理后的模板加入新的列表
shuffled_templates.append(flattened_embeddings)
# 将列表展平并堆叠为一个新的张量,形状为 (B, M * N, D)
shuffled_templates = torch.stack(shuffled_templates, dim=0)
x = self.pos_drop(shuffled_templates)
if_flip_img_sequences = False
# mamba impl
residual = None
hidden_states = x
for layer in self.layers:
hidden_states, residual = layer(
hidden_states, residual, inference_params=inference_params
)
# Set prenorm=False here since we don't need the residual
fused_add_norm_fn = rms_norm_fn if isinstance(self.norm_f, RMSNorm) else layer_norm_fn
hidden_states = fused_add_norm_fn( # hidden_states.shape = torch.Size([2, 320, 384])
self.drop_path(hidden_states),
self.norm_f.weight,
self.norm_f.bias,
eps=self.norm_f.eps,
residual=residual,
prenorm=False,
residual_in_fp32=self.residual_in_fp32,
)
return hidden_states
def forward_dynamic_features_inference(self, template_list, inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False):
'''
input shape:
template_list: python list. item: torch.tensor, (1, 3, 128, 128)
'''
# B = 1
# stacked_templates = template_list.flatten(0,1) #为了测速而作的调整
stacked_templates = torch.cat(template_list, dim=0)
x = self.patch_embed(stacked_templates)
B, N, C = x.shape
x = x.reshape(1, B*N, C)
x = self.pos_drop(x)
if_flip_img_sequences = False
# mamba impl
residual = None
hidden_states = x
for layer in self.layers:
hidden_states, residual = layer(
hidden_states, residual, inference_params=inference_params
)
fused_add_norm_fn = rms_norm_fn
hidden_states = fused_add_norm_fn( # hidden_states.shape = torch.Size([2, 320, 384])
self.drop_path(hidden_states),
self.norm_f.weight,
self.norm_f.bias,
eps=self.norm_f.eps,
residual=residual,
prenorm=False,
residual_in_fp32=self.residual_in_fp32,
)
return hidden_states
def forward_dynamic_features_speed_test(self, template_list, inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False):
'''
input shape:
template_list: python list. item: torch.tensor, (1, 3, 128, 128)
'''
# B = 1
stacked_templates = template_list.flatten(0,1) #为了测速而作的调整
# stacked_templates = torch.cat(template_list, dim=0)
x = self.patch_embed(stacked_templates)
B, N, C = x.shape
x = x.reshape(1, B*N, C)
x = self.pos_drop(x)
if_flip_img_sequences = False
# mamba impl
residual = None
hidden_states = x
for layer in self.layers:
hidden_states, residual = layer(
hidden_states, residual, inference_params=inference_params
)
fused_add_norm_fn = rms_norm_fn
hidden_states = fused_add_norm_fn( # hidden_states.shape = torch.Size([2, 320, 384])
self.drop_path(hidden_states),
self.norm_f.weight,
self.norm_f.bias,
eps=self.norm_f.eps,
residual=residual,
prenorm=False,
residual_in_fp32=self.residual_in_fp32,
)
return hidden_states
def forward_tripple_features(self, dynamic_z, static_z, x, inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False):
# taken from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
# with slight modifications to add the dist_token
# print('pre_x.shape:',x.shape) # torch.Size([2, 3, 256, 256])
x = self.patch_embed(x) #x.shape = torch.Size([B, 3, 224, 224]) -> torch.Size([2, 196, 384])
z = self.patch_embed(static_z)
# print('tri_x.shape:', x.shape) # tri_x.shape: torch.Size([2, 256, 384])
B, M, _ = x.shape
# print('BM_x.shape:', x.shape) # BM_x.shape: torch.Size([2, 256, 384])
x = x + self.pos_embed_x # x = x + positon_embemding =torch.Size([B, 196, 384]) + torch.Size([1, 196, 384]) = torch.Size([B, 196, 384])
z = z + self.pos_embed_z
dynamic_z = dynamic_z + self.pos_embed_dynamic_z
x = torch.cat((z, dynamic_z, x), dim=1)
# x = torch.cat((dynamic_z, z, x), dim=1)
x = self.pos_drop(x) # x.shape = torch.Size([B, 196, 384])
if_flip_img_sequences = False
# mamba impl
residual = None
hidden_states = x
for layer in self.layers:
hidden_states, residual = layer(
hidden_states, residual, inference_params=inference_params
)
fused_add_norm_fn = rms_norm_fn
hidden_states = fused_add_norm_fn( # hidden_states.shape = torch.Size([2, 320, 384])
self.drop_path(hidden_states),
self.norm_f.weight,
self.norm_f.bias,
eps=self.norm_f.eps,
residual=residual,
prenorm=False,
residual_in_fp32=self.residual_in_fp32,
)
return hidden_states
def forward(self, static_z, dynamic_z, x, return_features=False, inference_params=None,
if_random_cls_token_position=False, if_random_token_rank=False,
feat_len_s=None, feat_len_z=None):
x = self.resnet(x)
x = self.temporal_conv(x)
dynamic_z = self.foward_dynamic_features(dynamic_z)[:, -feat_len_z:]
x = self.forward_tripple_features(dynamic_z, static_z, x,
inference_params, if_random_cls_token_position=if_random_cls_token_position,
if_random_token_rank=if_random_token_rank)
if return_features:
return x
# x = self.head(x)
if self.final_pool_type == 'max':
x = x.max(dim=1)[0]
return x
def inference(self, dynamic_z, static_z, x, return_features=False, inference_params=None,
if_random_cls_token_position=False, if_random_token_rank=False,
feat_len_s=None, feat_len_z=None):
'''
dynamic_z -> mamba hidden states
static_z -> raw template rgb image
x -> raw search rgb image
'''
dynamic_z = dynamic_z[:, -feat_len_z:]
x = self.forward_tripple_features(dynamic_z, static_z, x,
inference_params, if_random_cls_token_position=if_random_cls_token_position,
if_random_token_rank=if_random_token_rank)
return x
@register_model
def vim_tiny_patch16_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, embed_dim=192, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='mean', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
checkpoint = torch.hub.load_state_dict_from_url(
url="to.do",
map_location="cpu", check_hash=True
)
model.load_state_dict(checkpoint["model"])
return model
@register_model
def vim_tiny_patch16_stride8_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, stride=8, embed_dim=192, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='mean', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
checkpoint = torch.hub.load_state_dict_from_url(
url="to.do",
map_location="cpu", check_hash=True
)
model.load_state_dict(checkpoint["model"])
return model
LIGHT @register_model
def vim_small_patch16_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, embed_dim=384, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='all', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
# checkpoint = torch.hub.load_state_dict_from_url(
# url="to.do",
# map_location="cpu", check_hash=True
# )
# model.load_state_dict(checkpoint["model"])
code Copy code
checkpoint = torch.load(pretrained, map_location="cpu")
missing_keys, unexpected_keys = model.load_state_dict(checkpoint["model"], strict=False)
print('Load pretrained model from: ' + pretrained)
return model
@register_model
def vim_small_patch16_stride8_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, stride=8, embed_dim=384, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='mean', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
checkpoint = torch.hub.load_state_dict_from_url(
url="to.do",
map_location="cpu", check_hash=True
)
model.load_state_dict(checkpoint["model"])
return model中是否需要集成V_encoder?
class Block(nn.Module):
def init (
self, dim, mixer_cls, norm_cls=nn.LayerNorm, fused_add_norm=False, residual_in_fp32=False,drop_path=0.,
):
"""
Simple block wrapping a mixer class with LayerNorm/RMSNorm and residual connection"
code Copy code
This Block has a slightly different structure compared to a regular
prenorm Transformer block.
The standard block is: LN -> MHA/MLP -> Add.
[Ref: https://arxiv.org/abs/2002.04745]
Here we have: Add -> LN -> Mixer, returning both
the hidden_states (output of the mixer) and the residual.
This is purely for performance reasons, as we can fuse add and LayerNorm.
The residual needs to be provided (except for the very first block).
"""
super().__init__()
self.residual_in_fp32 = residual_in_fp32
self.fused_add_norm = fused_add_norm
self.mixer = mixer_cls(dim)
self.norm = norm_cls(dim)
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
if self.fused_add_norm:
assert RMSNorm is not None, "RMSNorm import fails"
assert isinstance(
self.norm, (nn.LayerNorm, RMSNorm)
), "Only LayerNorm and RMSNorm are supported for fused_add_norm"
def forward(
self, hidden_states: Tensor, residual: Optional[Tensor] = None, inference_params=None
):
r"""Pass the input through the encoder layer.
Args:
hidden_states: the sequence to the encoder layer (required).
residual: hidden_states = Mixer(LN(residual))
"""
if not self.fused_add_norm:
if residual is None:
residual = hidden_states
else:
residual = residual + self.drop_path(hidden_states)
hidden_states = self.norm(residual.to(dtype=self.norm.weight.dtype))
if self.residual_in_fp32:
residual = residual.to(torch.float32)
else:
fused_add_norm_fn = rms_norm_fn if isinstance(self.norm, RMSNorm) else layer_norm_fn
if residual is None:
hidden_states, residual = fused_add_norm_fn(
hidden_states,
self.norm.weight,
self.norm.bias,
residual=residual,
prenorm=True,
residual_in_fp32=self.residual_in_fp32,
eps=self.norm.eps,
)
else:
hidden_states, residual = fused_add_norm_fn(
self.drop_path(hidden_states),
self.norm.weight,
self.norm.bias,
residual=residual,
prenorm=True,
residual_in_fp32=self.residual_in_fp32,
eps=self.norm.eps,
)
hidden_states = self.mixer(hidden_states, inference_params=inference_params)
return hidden_states, residual
def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
return self.mixer.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs)
def create_block(
d_model,
ssm_cfg=None,
norm_epsilon=1e-5,
drop_path=0.,
rms_norm=False,
residual_in_fp32=False,
fused_add_norm=False,
layer_idx=None,
device=None,
dtype=None,
if_bimamba=False,
bimamba_type="none",
if_devide_out=False,
init_layer_scale=None,
):
if if_bimamba:
bimamba_type = "v1"
if ssm_cfg is None:
ssm_cfg = {}
factory_kwargs = {"device": device, "dtype": dtype}
mixer_cls = partial(Mamba, layer_idx=layer_idx, bimamba_type=bimamba_type, if_devide_out=if_devide_out, init_layer_scale=init_layer_scale, **ssm_cfg, **factory_kwargs)
norm_cls = partial(
nn.LayerNorm if not rms_norm else RMSNorm, eps=norm_epsilon, **factory_kwargs
)
block = Block(
d_model,
mixer_cls,
norm_cls=norm_cls,
drop_path=drop_path,
fused_add_norm=fused_add_norm,
residual_in_fp32=residual_in_fp32,
)
block.layer_idx = layer_idx
return block
def init_weights(
module,
n_layer,
initializer_range=0.02, # Now only used for embedding layer.
rescale_prenorm_residual=True,
n_residuals_per_layer=1, # Change to 2 if we have MLP
):
if isinstance(module, nn.Linear):
if module.bias is not None:
if not getattr(module.bias, "no_reinit", False):
nn.init.zeros (module.bias)
elif isinstance(module, nn.Embedding):
nn.init.normal (module.weight, std=initializer_range)
code Copy code
if rescale_prenorm_residual:
# Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
# > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
# > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
# > -- GPT-2 :: https://openai.com/blog/better-language-models/
#
# Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
for name, p in module.named_parameters():
if name in ["out_proj.weight", "fc2.weight"]:
# Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
# Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
# We need to reinit p since this code could be called multiple times
# Having just p *= scale would repeatedly scale it down
nn.init.kaiming_uniform_(p, a=math.sqrt(5))
with torch.no_grad():
p /= math.sqrt(n_residuals_per_layer * n_layer)
def segm_init_weights(m):
if isinstance(m, nn.Linear):
trunc_normal_(m.weight, std=0.02)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.Conv2d):
# NOTE conv was left to pytorch default in my original init
lecun_normal_(m.weight)
if m.bias is not None:
nn.init.zeros_(m.bias)
elif isinstance(m, (nn.LayerNorm, nn.GroupNorm, nn.BatchNorm2d)):
nn.init.zeros_(m.bias)
nn.init.ones_(m.weight)
class VisionMamba(nn.Module):
def init (self,
img_size=224,
patch_size=16,
stride=16,
depth=24,
embed_dim=192,
channels=3,
num_classes=1000,
ssm_cfg=None,
drop_rate=0.,
drop_path_rate=0.1,
norm_epsilon: float = 1e-5,
rms_norm: bool = False,
initializer_cfg=None,
fused_add_norm=False,
residual_in_fp32=False,
device=None,
dtype=None,
ft_seq_len=None,
pt_hw_seq_len=14,
if_bidirectional=False,
final_pool_type='none',
if_abs_pos_embed=False,
if_rope=False,
if_rope_residual=False,
flip_img_sequences_ratio=-1.,
if_bimamba=False,
bimamba_type="none",
if_cls_token=False,
if_devide_out=False,
init_layer_scale=None,
use_double_cls_token=False,
use_middle_cls_token=False,
**kwargs):
factory_kwargs = {"device": device, "dtype": dtype}
# add factory_kwargs into kwargs
kwargs.update(factory_kwargs)
super().init ()
self.residual_in_fp32 = residual_in_fp32
self.fused_add_norm = fused_add_norm
self.if_bidirectional = if_bidirectional
self.final_pool_type = final_pool_type
self.if_abs_pos_embed = if_abs_pos_embed
self.if_rope = if_rope
self.if_rope_residual = if_rope_residual
self.flip_img_sequences_ratio = flip_img_sequences_ratio
self.if_cls_token = if_cls_token
self.use_double_cls_token = use_double_cls_token
self.use_middle_cls_token = use_middle_cls_token
self.num_tokens = 1 if if_cls_token else 0
code Copy code
# pretrain parameters
self.num_classes = num_classes
self.d_model = self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
self.patch_embed = PatchEmbed(
img_size=img_size, patch_size=patch_size, stride=stride, in_chans=channels, embed_dim=embed_dim)
num_patches = self.patch_embed.num_patches
if if_cls_token:
if use_double_cls_token:
self.cls_token_head = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
self.cls_token_tail = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
self.num_tokens = 2
else:
self.cls_token = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
# self.num_tokens = 1
if if_abs_pos_embed:
self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + self.num_tokens, self.embed_dim))
self.pos_drop = nn.Dropout(p=drop_rate)
if if_rope:
half_head_dim = embed_dim // 2
hw_seq_len = img_size // patch_size
self.rope = VisionRotaryEmbeddingFast(
dim=half_head_dim,
pt_seq_len=pt_hw_seq_len,
ft_seq_len=hw_seq_len
)
self.head = nn.Linear(self.num_features, num_classes) if num_classes > 0 else nn.Identity()
# TODO: release this comment
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
# import ipdb;ipdb.set_trace()
inter_dpr = [0.0] + dpr
self.drop_path = DropPath(drop_path_rate) if drop_path_rate > 0. else nn.Identity()
# transformer blocks
self.layers = nn.ModuleList(
[
create_block(
embed_dim,
ssm_cfg=ssm_cfg,
norm_epsilon=norm_epsilon,
rms_norm=rms_norm,
residual_in_fp32=residual_in_fp32,
fused_add_norm=fused_add_norm,
layer_idx=i,
if_bimamba=if_bimamba,
bimamba_type=bimamba_type,
drop_path=inter_dpr[i],
if_devide_out=if_devide_out,
init_layer_scale=init_layer_scale,
**factory_kwargs,
)
for i in range(depth)
]
)
# output head
self.norm_f = (nn.LayerNorm if not rms_norm else RMSNorm)(
embed_dim, eps=norm_epsilon, **factory_kwargs
)
# self.pre_logits = nn.Identity()
# original init
self.patch_embed.apply(segm_init_weights)
self.head.apply(segm_init_weights)
if if_abs_pos_embed:
trunc_normal_(self.pos_embed, std=.02)
if if_cls_token:
if use_double_cls_token:
trunc_normal_(self.cls_token_head, std=.02)
trunc_normal_(self.cls_token_tail, std=.02)
else:
trunc_normal_(self.cls_token, std=.02)
# mamba init
self.apply(
partial(
_init_weights,
n_layer=depth,
**(initializer_cfg if initializer_cfg is not None else {}),
)
)
def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
return {
i: layer.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs)
for i, layer in enumerate(self.layers)
}
@torch.jit.ignore
def no_weight_decay(self):
return {"pos_embed", "cls_token", "dist_token", "cls_token_head", "cls_token_tail"}
@torch.jit.ignore()
def load_pretrained(self, checkpoint_path, prefix=""):
_load_weights(self, checkpoint_path, prefix)
def forward_features(self, x, inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False):
# taken from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
# with slight modifications to add the dist_token
x = self.patch_embed(x)
B, M, _ = x.shape
if self.if_cls_token:
if self.use_double_cls_token:
cls_token_head = self.cls_token_head.expand(B, -1, -1)
cls_token_tail = self.cls_token_tail.expand(B, -1, -1)
token_position = [0, M + 1]
x = torch.cat((cls_token_head, x, cls_token_tail), dim=1)
M = x.shape[1]
else:
if self.use_middle_cls_token:
cls_token = self.cls_token.expand(B, -1, -1)
token_position = M // 2
# add cls token in the middle
x = torch.cat((x[:, :token_position, :], cls_token, x[:, token_position:, :]), dim=1)
elif if_random_cls_token_position:
cls_token = self.cls_token.expand(B, -1, -1)
token_position = random.randint(0, M)
x = torch.cat((x[:, :token_position, :], cls_token, x[:, token_position:, :]), dim=1)
print("token_position: ", token_position)
else:
cls_token = self.cls_token.expand(B, -1, -1) # stole cls_tokens impl from Phil Wang, thanks
token_position = 0
x = torch.cat((cls_token, x), dim=1)
M = x.shape[1]
if self.if_abs_pos_embed:
# if new_grid_size[0] == self.patch_embed.grid_size[0] and new_grid_size[1] == self.patch_embed.grid_size[1]:
# x = x + self.pos_embed
# else:
# pos_embed = interpolate_pos_embed_online(
# self.pos_embed, self.patch_embed.grid_size, new_grid_size,0
# )
x = x + self.pos_embed
x = self.pos_drop(x)
if if_random_token_rank:
# 生成随机 shuffle 索引
shuffle_indices = torch.randperm(M)
if isinstance(token_position, list):
print("original value: ", x[0, token_position[0], 0], x[0, token_position[1], 0])
else:
print("original value: ", x[0, token_position, 0])
print("original token_position: ", token_position)
# 执行 shuffle
x = x[:, shuffle_indices, :]
if isinstance(token_position, list):
# 找到 cls token 在 shuffle 之后的新位置
new_token_position = [torch.where(shuffle_indices == token_position[i])[0].item() for i in range(len(token_position))]
token_position = new_token_position
else:
# 找到 cls token 在 shuffle 之后的新位置
token_position = torch.where(shuffle_indices == token_position)[0].item()
if isinstance(token_position, list):
print("new value: ", x[0, token_position[0], 0], x[0, token_position[1], 0])
else:
print("new value: ", x[0, token_position, 0])
print("new token_position: ", token_position)
if_flip_img_sequences = False
if self.flip_img_sequences_ratio > 0 and (self.flip_img_sequences_ratio - random.random()) > 1e-5:
x = x.flip([1])
if_flip_img_sequences = True
# mamba impl
residual = None
hidden_states = x
if not self.if_bidirectional:
for layer in self.layers:
if if_flip_img_sequences and self.if_rope:
hidden_states = hidden_states.flip([1])
if residual is not None:
residual = residual.flip([1])
# rope about
if self.if_rope:
hidden_states = self.rope(hidden_states)
if residual is not None and self.if_rope_residual:
residual = self.rope(residual)
if if_flip_img_sequences and self.if_rope:
hidden_states = hidden_states.flip([1])
if residual is not None:
residual = residual.flip([1])
hidden_states, residual = layer(
hidden_states, residual, inference_params=inference_params
)
else:
# get two layers in a single for-loop
for i in range(len(self.layers) // 2):
if self.if_rope:
hidden_states = self.rope(hidden_states)
if residual is not None and self.if_rope_residual:
residual = self.rope(residual)
hidden_states_f, residual_f = self.layers[i * 2](
hidden_states, residual, inference_params=inference_params
)
hidden_states_b, residual_b = self.layers[i * 2 + 1](
hidden_states.flip([1]), None if residual == None else residual.flip([1]), inference_params=inference_params
)
hidden_states = hidden_states_f + hidden_states_b.flip([1])
residual = residual_f + residual_b.flip([1])
if not self.fused_add_norm:
if residual is None:
residual = hidden_states
else:
residual = residual + self.drop_path(hidden_states)
hidden_states = self.norm_f(residual.to(dtype=self.norm_f.weight.dtype))
else:
# Set prenorm=False here since we don't need the residual
fused_add_norm_fn = rms_norm_fn if isinstance(self.norm_f, RMSNorm) else layer_norm_fn
hidden_states = fused_add_norm_fn(
self.drop_path(hidden_states),
self.norm_f.weight,
self.norm_f.bias,
eps=self.norm_f.eps,
residual=residual,
prenorm=False,
residual_in_fp32=self.residual_in_fp32,
)
# return only cls token if it exists
if self.if_cls_token:
if self.use_double_cls_token:
return (hidden_states[:, token_position[0], :] + hidden_states[:, token_position[1], :]) / 2
else:
if self.use_middle_cls_token:
return hidden_states[:, token_position, :]
elif if_random_cls_token_position:
return hidden_states[:, token_position, :]
else:
return hidden_states[:, token_position, :]
if self.final_pool_type == 'none':
return hidden_states[:, -1, :]
elif self.final_pool_type == 'mean':
return hidden_states.mean(dim=1)
elif self.final_pool_type == 'max':
return hidden_states
elif self.final_pool_type == 'all':
return hidden_states
else:
raise NotImplementedError
def forward(self, x, return_features=False, inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False):
x = self.forward_features(x, inference_params, if_random_cls_token_position=if_random_cls_token_position, if_random_token_rank=if_random_token_rank)
if return_features:
return x
x = self.head(x)
if self.final_pool_type == 'max':
x = x.max(dim=1)[0]
return x
@register_model
def vim_tiny_patch16_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, embed_dim=192, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='mean', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
checkpoint = torch.hub.load_state_dict_from_url(
url="to.do",
map_location="cpu", check_hash=True
)
model.load_state_dict(checkpoint["model"])
return model
@register_model
def vim_tiny_patch16_stride8_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, stride=8, embed_dim=192, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='mean', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
checkpoint = torch.hub.load_state_dict_from_url(
url="to.do",
map_location="cpu", check_hash=True
)
model.load_state_dict(checkpoint["model"])
return model
@register_model
def vim_small_patch16_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, embed_dim=384, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='mean', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
checkpoint = torch.hub.load_state_dict_from_url(
url="to.do",
map_location="cpu", check_hash=True
)
model.load_state_dict(checkpoint["model"])
return model
@register_model
def vim_small_patch16_stride8_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, stride=8, embed_dim=384, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='mean', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
checkpoint = torch.hub.load_state_dict_from_url(
url="to.do",
map_location="cpu", check_hash=True
)
model.load_state_dict(checkpoint["model"])
return model 和 ② import torch
import torch.nn as nn
import numpy as np
import torchvision
from transformers import MBartForConditionalGeneration, MBartPreTrainedModel, MBartModel, MBartConfig
from torch.nn.utils.rnn import pad_sequence
global definition from models_mamba import create_block
import math
from einops import rearrange, repeat
def make_resnet(name='resnet18'):
if name == 'resnet18':
model = torchvision.models.resnet18(pretrained=True)
elif name == 'resnet34':
model = torchvision.models.resnet34(pretrained=True)
elif name == 'resnet50':
model = torchvision.models.resnet50(pretrained=True)
elif name == 'resnet101':
model = torchvision.models.resnet101(pretrained=True)
else:
raise Exception('There are no supported resnet model {}.'.format(_('resnet')))
code Copy code
model.fc = nn.Identity()
return model
class resnet(nn.Module):
def init (self, name="resnet18"):
super(resnet, self).init ()
self.resnet = make_resnet(name=name)
code Copy code
def forward(self, x, lengths):
x = self.resnet(x)
x_batch = []
start = 0
for length in lengths:
end = start + length
x_batch.append(x[start:end])
start = end
x = pad_sequence(x_batch,padding_value=PAD_IDX,batch_first=True)
return x
class time_mamba(nn.Module):
def init (self):
super(time_mamba, self).init ()
code Copy code
self.mamba_block = create_block(d_model=512)
def forward(self, x):
hidden_x, res_x = self.mamba_block(x)
return hidden_x
class TemporalConv(nn.Module):
def init (self, input_size, hidden_size, conv_type=2):
super(TemporalConv, self).init ()
self.input_size = input_size
self.hidden_size = hidden_size
self.conv_type = conv_type
code Copy code
if self.conv_type == 0:
self.kernel_size = ['K3']
elif self.conv_type == 1:
self.kernel_size = ['K5', "P2"]
elif self.conv_type == 2:
self.kernel_size = ['K5', "P2", 'K5', "P2"]
modules = []
for layer_idx, ks in enumerate(self.kernel_size):
input_sz = self.input_size if layer_idx == 0 else self.hidden_size
if ks[0] == 'P':
modules.append(nn.MaxPool1d(kernel_size=int(ks[1]), ceil_mode=False))
elif ks[0] == 'K':
modules.append(
nn.Conv1d(input_sz, self.hidden_size, kernel_size=int(ks[1]), stride=1, padding=0)
)
modules.append(nn.BatchNorm1d(self.hidden_size))
modules.append(nn.ReLU(inplace=True))
self.temporal_conv = nn.Sequential(*modules)
def forward(self, x):
x = self.temporal_conv(x.permute(0,2,1))
return x.permute(0,2,1)
class V_encoder(nn.Module):
def init (self, emb_size, feature_size):
super(V_encoder, self).init ()
code Copy code
self.src_emb = nn.Linear(feature_size, emb_size)
modules = []
modules.append(nn.BatchNorm1d(emb_size))
modules.append(nn.ReLU(inplace=True))
self.bn_ac = nn.Sequential(*modules)
for m in self.modules():
if isinstance(m, (nn.Conv1d,nn.Linear)):
nn.init.xavier_uniform_(m.weight, gain=nn.init.calculate_gain('relu'))
elif isinstance(m, nn.BatchNorm1d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
def forward(self, src:torch.Tensor):
src = self.src_emb(src)
src = self.bn_ac(src.permute(0,2,1)).permute(0,2,1)
return src
class SignModel(nn.Module):
def init (self, config, args, embed_dim=1024):
super(SignModel, self).init ()
self.args = args
self.resnet = resnet(name="resnet18")
self.time_mamba = time_mamba()
self.mbart = MBartForConditionalGeneration.from_pretrained(config['model']['visual_encoder'])
self.conv_1d = TemporalConv(input_size=512, hidden_size=1024, conv_type=2)
self.sign_emb = V_encoder(emb_size=embed_dim, feature_size=embed_dim)
self.embed_scale = 1.0
code Copy code
def __str__(self):
model_parameters = filter(lambda p: p.requires_grad, self.parameters())
params = sum([np.prod(p.size()) for p in model_parameters])
return super().__str__() + '\nTrainable parameters: {}'.format(params)
def visual_forward(self, src_input):
attention_mask = src_input['attention_mask']
out_visual = self.resnet(src_input['input_ids'].cuda(), src_input['src_length_batch'])
out_visual = self.time_mamba(out_visual)
frames_feature = self.conv_1d(out_visual)
inputs_embeds = self.sign_emb(frames_feature)
inputs_embeds = self.embed_scale * inputs_embeds
return inputs_embeds, attention_mask
def forward(self, src_input, tgt_input):
inputs_embeds, attention_mask = self.visual_forward(src_input)
out = self.mbart(inputs_embeds = inputs_embeds,
attention_mask = attention_mask.cuda(),
labels = tgt_input['input_ids'].cuda(),
decoder_attention_mask = tgt_input['attention_mask'].cuda(),
return_dict = True,
)
return out['logits']
def generate(self,src_input, max_new_tokens, num_beams, decoder_start_token_id):
inputs_embeds, attention_mask = self.visual_forward(src_input)
out = self.mbart.generate(inputs_embeds = inputs_embeds,
attention_mask = attention_mask.cuda(),max_new_tokens=max_new_tokens,num_beams = num_beams,
decoder_start_token_id=decoder_start_token_id
)
return out
class Block(nn.Module):
def init (
self, dim, mixer_cls, norm_cls=nn.LayerNorm, fused_add_norm=False, residual_in_fp32=False,drop_path=0.,
):
"""
Simple block wrapping a mixer class with LayerNorm/RMSNorm and residual connection"
code Copy code
This Block has a slightly different structure compared to a regular
prenorm Transformer block.
The standard block is: LN -> MHA/MLP -> Add.
[Ref: https://arxiv.org/abs/2002.04745]
Here we have: Add -> LN -> Mixer, returning both
the hidden_states (output of the mixer) and the residual.
This is purely for performance reasons, as we can fuse add and LayerNorm.
The residual needs to be provided (except for the very first block).
"""
super().__init__()
self.residual_in_fp32 = residual_in_fp32
self.fused_add_norm = fused_add_norm
self.mixer = mixer_cls(dim)
self.norm = norm_cls(dim)
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
if self.fused_add_norm:
assert RMSNorm is not None, "RMSNorm import fails"
assert isinstance(
self.norm, (nn.LayerNorm, RMSNorm)
), "Only LayerNorm and RMSNorm are supported for fused_add_norm"
def forward(
self, hidden_states: Tensor, residual: Optional[Tensor] = None, inference_params=None
):
r"""Pass the input through the encoder layer.
Args:
hidden_states: the sequence to the encoder layer (required).
residual: hidden_states = Mixer(LN(residual))
"""
if not self.fused_add_norm:
if residual is None:
residual = hidden_states
else:
residual = residual + self.drop_path(hidden_states)
hidden_states = self.norm(residual.to(dtype=self.norm.weight.dtype))
if self.residual_in_fp32:
residual = residual.to(torch.float32)
else:
fused_add_norm_fn = rms_norm_fn if isinstance(self.norm, RMSNorm) else layer_norm_fn
if residual is None:
hidden_states, residual = fused_add_norm_fn(
hidden_states,
self.norm.weight,
self.norm.bias,
residual=residual,
prenorm=True,
residual_in_fp32=self.residual_in_fp32,
eps=self.norm.eps,
)
else:
hidden_states, residual = fused_add_norm_fn(
self.drop_path(hidden_states),
self.norm.weight,
self.norm.bias,
residual=residual,
prenorm=True,
residual_in_fp32=self.residual_in_fp32,
eps=self.norm.eps,
)
hidden_states = self.mixer(hidden_states, inference_params=inference_params)
return hidden_states, residual
def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
return self.mixer.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs)
def create_block(
d_model,
ssm_cfg=None,
norm_epsilon=1e-5,
drop_path=0.,
rms_norm=False,
residual_in_fp32=False,
fused_add_norm=False,
layer_idx=None,
device=None,
dtype=None,
if_bimamba=False,
bimamba_type="none",
if_devide_out=False,
init_layer_scale=None,
):
if if_bimamba:
bimamba_type = "v1"
if ssm_cfg is None:
ssm_cfg = {}
factory_kwargs = {"device": device, "dtype": dtype}
mixer_cls = partial(Mamba, layer_idx=layer_idx, bimamba_type=bimamba_type, if_devide_out=if_devide_out, init_layer_scale=init_layer_scale, **ssm_cfg, **factory_kwargs)
norm_cls = partial(
nn.LayerNorm if not rms_norm else RMSNorm, eps=norm_epsilon, **factory_kwargs
)
block = Block(
d_model,
mixer_cls,
norm_cls=norm_cls,
drop_path=drop_path,
fused_add_norm=fused_add_norm,
residual_in_fp32=residual_in_fp32,
)
block.layer_idx = layer_idx
return block
def init_weights(
module,
n_layer,
initializer_range=0.02, # Now only used for embedding layer.
rescale_prenorm_residual=True,
n_residuals_per_layer=1, # Change to 2 if we have MLP
):
if isinstance(module, nn.Linear):
if module.bias is not None:
if not getattr(module.bias, "no_reinit", False):
nn.init.zeros (module.bias)
elif isinstance(module, nn.Embedding):
nn.init.normal (module.weight, std=initializer_range)
code Copy code
if rescale_prenorm_residual:
# Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
# > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
# > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
# > -- GPT-2 :: https://openai.com/blog/better-language-models/
#
# Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
for name, p in module.named_parameters():
if name in ["out_proj.weight", "fc2.weight"]:
# Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
# Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
# We need to reinit p since this code could be called multiple times
# Having just p *= scale would repeatedly scale it down
nn.init.kaiming_uniform_(p, a=math.sqrt(5))
with torch.no_grad():
p /= math.sqrt(n_residuals_per_layer * n_layer)
def segm_init_weights(m):
if isinstance(m, nn.Linear):
trunc_normal_(m.weight, std=0.02)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.Conv2d):
# NOTE conv was left to pytorch default in my original init
lecun_normal_(m.weight)
if m.bias is not None:
nn.init.zeros_(m.bias)
elif isinstance(m, (nn.LayerNorm, nn.GroupNorm, nn.BatchNorm2d)):
nn.init.zeros_(m.bias)
nn.init.ones_(m.weight)
class VisionMamba(nn.Module):
def init (self,
img_size=224,
patch_size=16,
stride=16,
depth=24,
embed_dim=192,
channels=3,
num_classes=1000,
ssm_cfg=None,
drop_rate=0.,
drop_path_rate=0.1,
norm_epsilon: float = 1e-5,
rms_norm: bool = False,
initializer_cfg=None,
fused_add_norm=False,
residual_in_fp32=False,
device=None,
dtype=None,
ft_seq_len=None,
pt_hw_seq_len=14,
if_bidirectional=False,
final_pool_type='none',
if_abs_pos_embed=False,
if_rope=False,
if_rope_residual=False,
flip_img_sequences_ratio=-1.,
if_bimamba=False,
bimamba_type="none",
if_cls_token=False,
if_devide_out=False,
init_layer_scale=None,
use_double_cls_token=False,
use_middle_cls_token=False,
**kwargs):
factory_kwargs = {"device": device, "dtype": dtype}
# add factory_kwargs into kwargs
kwargs.update(factory_kwargs)
super().init ()
self.residual_in_fp32 = residual_in_fp32
self.fused_add_norm = fused_add_norm
self.if_bidirectional = if_bidirectional
self.final_pool_type = final_pool_type
self.if_abs_pos_embed = if_abs_pos_embed
self.if_rope = if_rope
self.if_rope_residual = if_rope_residual
self.flip_img_sequences_ratio = flip_img_sequences_ratio
self.if_cls_token = if_cls_token
self.use_double_cls_token = use_double_cls_token
self.use_middle_cls_token = use_middle_cls_token
self.num_tokens = 1 if if_cls_token else 0
code Copy code
# pretrain parameters
self.num_classes = num_classes
self.d_model = self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
self.patch_embed = PatchEmbed(
img_size=img_size, patch_size=patch_size, stride=stride, in_chans=channels, embed_dim=embed_dim)
num_patches = self.patch_embed.num_patches
if if_cls_token:
if use_double_cls_token:
self.cls_token_head = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
self.cls_token_tail = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
self.num_tokens = 2
else:
self.cls_token = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
# self.num_tokens = 1
if if_abs_pos_embed:
self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + self.num_tokens, self.embed_dim))
self.pos_drop = nn.Dropout(p=drop_rate)
if if_rope:
half_head_dim = embed_dim // 2
hw_seq_len = img_size // patch_size
self.rope = VisionRotaryEmbeddingFast(
dim=half_head_dim,
pt_seq_len=pt_hw_seq_len,
ft_seq_len=hw_seq_len
)
self.head = nn.Linear(self.num_features, num_classes) if num_classes > 0 else nn.Identity()
# TODO: release this comment
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
# import ipdb;ipdb.set_trace()
inter_dpr = [0.0] + dpr
self.drop_path = DropPath(drop_path_rate) if drop_path_rate > 0. else nn.Identity()
# transformer blocks
self.layers = nn.ModuleList(
[
create_block(
embed_dim,
ssm_cfg=ssm_cfg,
norm_epsilon=norm_epsilon,
rms_norm=rms_norm,
residual_in_fp32=residual_in_fp32,
fused_add_norm=fused_add_norm,
layer_idx=i,
if_bimamba=if_bimamba,
bimamba_type=bimamba_type,
drop_path=inter_dpr[i],
if_devide_out=if_devide_out,
init_layer_scale=init_layer_scale,
**factory_kwargs,
)
for i in range(depth)
]
)
# output head
self.norm_f = (nn.LayerNorm if not rms_norm else RMSNorm)(
embed_dim, eps=norm_epsilon, **factory_kwargs
)
# self.pre_logits = nn.Identity()
# original init
self.patch_embed.apply(segm_init_weights)
self.head.apply(segm_init_weights)
if if_abs_pos_embed:
trunc_normal_(self.pos_embed, std=.02)
if if_cls_token:
if use_double_cls_token:
trunc_normal_(self.cls_token_head, std=.02)
trunc_normal_(self.cls_token_tail, std=.02)
else:
trunc_normal_(self.cls_token, std=.02)
# mamba init
self.apply(
partial(
_init_weights,
n_layer=depth,
**(initializer_cfg if initializer_cfg is not None else {}),
)
)
def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
return {
i: layer.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs)
for i, layer in enumerate(self.layers)
}
@torch.jit.ignore
def no_weight_decay(self):
return {"pos_embed", "cls_token", "dist_token", "cls_token_head", "cls_token_tail"}
@torch.jit.ignore()
def load_pretrained(self, checkpoint_path, prefix=""):
_load_weights(self, checkpoint_path, prefix)
def forward_features(self, x, inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False):
# taken from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
# with slight modifications to add the dist_token
x = self.patch_embed(x)
B, M, _ = x.shape
if self.if_cls_token:
if self.use_double_cls_token:
cls_token_head = self.cls_token_head.expand(B, -1, -1)
cls_token_tail = self.cls_token_tail.expand(B, -1, -1)
token_position = [0, M + 1]
x = torch.cat((cls_token_head, x, cls_token_tail), dim=1)
M = x.shape[1]
else:
if self.use_middle_cls_token:
cls_token = self.cls_token.expand(B, -1, -1)
token_position = M // 2
# add cls token in the middle
x = torch.cat((x[:, :token_position, :], cls_token, x[:, token_position:, :]), dim=1)
elif if_random_cls_token_position:
cls_token = self.cls_token.expand(B, -1, -1)
token_position = random.randint(0, M)
x = torch.cat((x[:, :token_position, :], cls_token, x[:, token_position:, :]), dim=1)
print("token_position: ", token_position)
else:
cls_token = self.cls_token.expand(B, -1, -1) # stole cls_tokens impl from Phil Wang, thanks
token_position = 0
x = torch.cat((cls_token, x), dim=1)
M = x.shape[1]
if self.if_abs_pos_embed:
# if new_grid_size[0] == self.patch_embed.grid_size[0] and new_grid_size[1] == self.patch_embed.grid_size[1]:
# x = x + self.pos_embed
# else:
# pos_embed = interpolate_pos_embed_online(
# self.pos_embed, self.patch_embed.grid_size, new_grid_size,0
# )
x = x + self.pos_embed
x = self.pos_drop(x)
if if_random_token_rank:
# 生成随机 shuffle 索引
shuffle_indices = torch.randperm(M)
if isinstance(token_position, list):
print("original value: ", x[0, token_position[0], 0], x[0, token_position[1], 0])
else:
print("original value: ", x[0, token_position, 0])
print("original token_position: ", token_position)
# 执行 shuffle
x = x[:, shuffle_indices, :]
if isinstance(token_position, list):
# 找到 cls token 在 shuffle 之后的新位置
new_token_position = [torch.where(shuffle_indices == token_position[i])[0].item() for i in range(len(token_position))]
token_position = new_token_position
else:
# 找到 cls token 在 shuffle 之后的新位置
token_position = torch.where(shuffle_indices == token_position)[0].item()
if isinstance(token_position, list):
print("new value: ", x[0, token_position[0], 0], x[0, token_position[1], 0])
else:
print("new value: ", x[0, token_position, 0])
print("new token_position: ", token_position)
if_flip_img_sequences = False
if self.flip_img_sequences_ratio > 0 and (self.flip_img_sequences_ratio - random.random()) > 1e-5:
x = x.flip([1])
if_flip_img_sequences = True
# mamba impl
residual = None
hidden_states = x
if not self.if_bidirectional:
for layer in self.layers:
if if_flip_img_sequences and self.if_rope:
hidden_states = hidden_states.flip([1])
if residual is not None:
residual = residual.flip([1])
# rope about
if self.if_rope:
hidden_states = self.rope(hidden_states)
if residual is not None and self.if_rope_residual:
residual = self.rope(residual)
if if_flip_img_sequences and self.if_rope:
hidden_states = hidden_states.flip([1])
if residual is not None:
residual = residual.flip([1])
hidden_states, residual = layer(
hidden_states, residual, inference_params=inference_params
)
else:
# get two layers in a single for-loop
for i in range(len(self.layers) // 2):
if self.if_rope:
hidden_states = self.rope(hidden_states)
if residual is not None and self.if_rope_residual:
residual = self.rope(residual)
hidden_states_f, residual_f = self.layers[i * 2](
hidden_states, residual, inference_params=inference_params
)
hidden_states_b, residual_b = self.layers[i * 2 + 1](
hidden_states.flip([1]), None if residual == None else residual.flip([1]), inference_params=inference_params
)
hidden_states = hidden_states_f + hidden_states_b.flip([1])
residual = residual_f + residual_b.flip([1])
if not self.fused_add_norm:
if residual is None:
residual = hidden_states
else:
residual = residual + self.drop_path(hidden_states)
hidden_states = self.norm_f(residual.to(dtype=self.norm_f.weight.dtype))
else:
# Set prenorm=False here since we don't need the residual
fused_add_norm_fn = rms_norm_fn if isinstance(self.norm_f, RMSNorm) else layer_norm_fn
hidden_states = fused_add_norm_fn(
self.drop_path(hidden_states),
self.norm_f.weight,
self.norm_f.bias,
eps=self.norm_f.eps,
residual=residual,
prenorm=False,
residual_in_fp32=self.residual_in_fp32,
)
# return only cls token if it exists
if self.if_cls_token:
if self.use_double_cls_token:
return (hidden_states[:, token_position[0], :] + hidden_states[:, token_position[1], :]) / 2
else:
if self.use_middle_cls_token:
return hidden_states[:, token_position, :]
elif if_random_cls_token_position:
return hidden_states[:, token_position, :]
else:
return hidden_states[:, token_position, :]
if self.final_pool_type == 'none':
return hidden_states[:, -1, :]
elif self.final_pool_type == 'mean':
return hidden_states.mean(dim=1)
elif self.final_pool_type == 'max':
return hidden_states
elif self.final_pool_type == 'all':
return hidden_states
else:
raise NotImplementedError
def forward(self, x, return_features=False, inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False):
x = self.forward_features(x, inference_params, if_random_cls_token_position=if_random_cls_token_position, if_random_token_rank=if_random_token_rank)
if return_features:
return x
x = self.head(x)
if self.final_pool_type == 'max':
x = x.max(dim=1)[0]
return x
@register_model
def vim_tiny_patch16_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, embed_dim=192, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='mean', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
checkpoint = torch.hub.load_state_dict_from_url(
url="to.do",
map_location="cpu", check_hash=True
)
model.load_state_dict(checkpoint["model"])
return model
@register_model
def vim_tiny_patch16_stride8_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, stride=8, embed_dim=192, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='mean', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
checkpoint = torch.hub.load_state_dict_from_url(
url="to.do",
map_location="cpu", check_hash=True
)
model.load_state_dict(checkpoint["model"])
return model
@register_model
def vim_small_patch16_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, embed_dim=384, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='mean', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
checkpoint = torch.hub.load_state_dict_from_url(
url="to.do",
map_location="cpu", check_hash=True
)
model.load_state_dict(checkpoint["model"])
return model
@register_model
def vim_small_patch16_stride8_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, stride=8, embed_dim=384, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='mean', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
checkpoint = torch.hub.load_state_dict_from_url(
url="to.do",
map_location="cpu", check_hash=True
)
model.load_state_dict(checkpoint["model"])
return model中定义了
class V_encoder(nn.Module):
def init (self, emb_size, feature_size):
super(V_encoder, self).init ()
code Copy code
self.src_emb = nn.Linear(feature_size, emb_size)
modules = []
modules.append(nn.BatchNorm1d(emb_size))
modules.append(nn.ReLU(inplace=True))
self.bn_ac = nn.Sequential(*modules)
for m in self.modules():
if isinstance(m, (nn.Conv1d,nn.Linear)):
nn.init.xavier_uniform_(m.weight, gain=nn.init.calculate_gain('relu'))
elif isinstance(m, nn.BatchNorm1d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
def forward(self, src:torch.Tensor):
src = self.src_emb(src)
src = self.bn_ac(src.permute(0,2,1)).permute(0,2,1)
return src
all = [
'vim_tiny_patch16_224', 'vim_small_patch16_224', 'vim_base_patch16_224',
'vim_tiny_patch16_384', 'vim_small_patch16_384', 'vim_base_patch16_384',
]
class PatchEmbed(nn.Module):
""" 2D Image to Patch Embedding
"""
def init (self, img_size=224, patch_size=16, stride=16, in_chans=3, embed_dim=768, norm_layer=None, flatten=True):
super().init ()
img_size = to_2tuple(img_size)
patch_size = to_2tuple(patch_size)
self.img_size = img_size
self.patch_size = patch_size
self.grid_size = ((img_size[0] - patch_size[0]) // stride + 1, (img_size[1] - patch_size[1]) // stride + 1)
self.num_patches = self.grid_size[0] * self.grid_size[1]
self.flatten = flatten
code Copy code
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=stride)
self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
def forward(self, x):
B, C, H, W = x.shape
# print('11x.shape:', x.shape) # 11x.shape: torch.Size([2, 3, 128, 128])
# assert H == self.img_size[0] and W == self.img_size[1], \
# f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
x = self.proj(x)
if self.flatten:
x = x.flatten(2).transpose(1, 2) # BCHW -> BNC
x = self.norm(x)
return x
class Block(nn.Module):
def init (
self, dim, mixer_cls, norm_cls=nn.LayerNorm, fused_add_norm=False, residual_in_fp32=False,drop_path=0.,
):
"""
Simple block wrapping a mixer class with LayerNorm/RMSNorm and residual connection"
code Copy code
This Block has a slightly different structure compared to a regular
prenorm Transformer block.
The standard block is: LN -> MHA/MLP -> Add.
[Ref: https://arxiv.org/abs/2002.04745]
Here we have: Add -> LN -> Mixer, returning both
the hidden_states (output of the mixer) and the residual.
This is purely for performance reasons, as we can fuse add and LayerNorm.
The residual needs to be provided (except for the very first block).
"""
super().__init__()
self.residual_in_fp32 = residual_in_fp32
self.fused_add_norm = fused_add_norm
self.mixer = mixer_cls(dim)
self.norm = norm_cls(dim)
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
if self.fused_add_norm:
assert RMSNorm is not None, "RMSNorm import fails"
assert isinstance(
self.norm, (nn.LayerNorm, RMSNorm)
), "Only LayerNorm and RMSNorm are supported for fused_add_norm"
def forward(
self, hidden_states: Tensor, residual: Optional[Tensor] = None, inference_params=None
):
r"""Pass the input through the encoder layer.
Args:
hidden_states: the sequence to the encoder layer (required).
residual: hidden_states = Mixer(LN(residual))
"""
fused_add_norm_fn = rms_norm_fn if isinstance(self.norm, RMSNorm) else layer_norm_fn
hidden_states, residual = fused_add_norm_fn(
hidden_states,
self.norm.weight,
self.norm.bias,
residual=residual,
prenorm=True,
residual_in_fp32=self.residual_in_fp32,
eps=self.norm.eps,
)
hidden_states = self.mixer(hidden_states, inference_params=inference_params)
return hidden_states, residual
def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
return self.mixer.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs)
def create_block(
d_model,
ssm_cfg=None,
norm_epsilon=1e-5,
drop_path=0.,
rms_norm=False,
residual_in_fp32=False,
fused_add_norm=False,
layer_idx=None,
device=None,
dtype=None,
if_bimamba=False,
bimamba_type="none",
if_devide_out=False,
init_layer_scale=None,
):
if if_bimamba:
bimamba_type = "v1"
if ssm_cfg is None:
ssm_cfg = {}
factory_kwargs = {"device": device, "dtype": dtype}
mixer_cls = partial(Mamba, layer_idx=layer_idx, bimamba_type=bimamba_type, if_devide_out=if_devide_out, init_layer_scale=init_layer_scale, **ssm_cfg, **factory_kwargs)
norm_cls = partial(
nn.LayerNorm if not rms_norm else RMSNorm, eps=norm_epsilon, **factory_kwargs
)
block = Block(
d_model,
mixer_cls,
norm_cls=norm_cls,
drop_path=drop_path,
fused_add_norm=fused_add_norm,
residual_in_fp32=residual_in_fp32,
)
block.layer_idx = layer_idx
return block
def init_weights(
module,
n_layer,
initializer_range=0.02, # Now only used for embedding layer.
rescale_prenorm_residual=True,
n_residuals_per_layer=1, # Change to 2 if we have MLP
):
if isinstance(module, nn.Linear):
if module.bias is not None:
if not getattr(module.bias, "no_reinit", False):
nn.init.zeros (module.bias)
elif isinstance(module, nn.Embedding):
nn.init.normal (module.weight, std=initializer_range)
code Copy code
if rescale_prenorm_residual:
# Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
# > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
# > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
# > -- GPT-2 :: https://openai.com/blog/better-language-models/
#
# Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
for name, p in module.named_parameters():
if name in ["out_proj.weight", "fc2.weight"]:
# Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
# Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
# We need to reinit p since this code could be called multiple times
# Having just p *= scale would repeatedly scale it down
nn.init.kaiming_uniform_(p, a=math.sqrt(5))
with torch.no_grad():
p /= math.sqrt(n_residuals_per_layer * n_layer)
def segm_init_weights(m):
if isinstance(m, nn.Linear):
trunc_normal_(m.weight, std=0.02)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.Conv2d):
# NOTE conv was left to pytorch default in my original init
lecun_normal_(m.weight)
if m.bias is not None:
nn.init.zeros_(m.bias)
elif isinstance(m, (nn.LayerNorm, nn.GroupNorm, nn.BatchNorm2d)):
nn.init.zeros_(m.bias)
nn.init.ones_(m.weight)
class VisionMamba(nn.Module):
def init (self,
img_size=224,
patch_size=16,
stride=16,
depth=24,
embed_dim=192,
channels=3,
num_classes=1000,
ssm_cfg=None,
drop_rate=0.,
drop_path_rate=0.1,
norm_epsilon: float = 1e-5,
rms_norm: bool = False,
initializer_cfg=None,
fused_add_norm=False,
residual_in_fp32=False,
device=None,
dtype=None,
ft_seq_len=None,
pt_hw_seq_len=14,
if_bidirectional=False,
final_pool_type='none',
if_abs_pos_embed=False,
if_rope=False,
if_rope_residual=False,
flip_img_sequences_ratio=-1.,
if_bimamba=False,
bimamba_type="none",
if_cls_token=False,
if_devide_out=False,
init_layer_scale=None,
use_double_cls_token=False,
use_middle_cls_token=False,
**kwargs):
factory_kwargs = {"device": device, "dtype": dtype}
# add factory_kwargs into kwargs
kwargs.update(factory_kwargs)
super().init ()
self.residual_in_fp32 = residual_in_fp32
self.fused_add_norm = fused_add_norm
self.if_bidirectional = if_bidirectional
self.final_pool_type = final_pool_type
self.if_abs_pos_embed = if_abs_pos_embed
self.if_rope = if_rope
self.if_rope_residual = if_rope_residual
self.flip_img_sequences_ratio = flip_img_sequences_ratio
# self.if_cls_token = if_cls_token
self.if_cls_token = False
self.use_double_cls_token = use_double_cls_token
self.use_middle_cls_token = use_middle_cls_token
self.num_tokens = 1 if if_cls_token else 0
####################
self.resnet = ResNetExtractor(resnet_type ="resnet18")
self.temporal_conv = TemporalConv(input_size=512, hidden_size=embed_dim)
self.sign_emb = V_encoder(emb_size=embed_dim, feature_size=embed_dim)
code Copy code
#######################
# pretrain parameters
self.num_classes = num_classes
self.d_model = self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
self.patch_embed = PatchEmbed(
img_size=img_size, patch_size=patch_size, stride=stride, in_chans=channels, embed_dim=embed_dim)
num_patches = self.patch_embed.num_patches
if if_cls_token:
if use_double_cls_token:
self.cls_token_head = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
self.cls_token_tail = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
self.num_tokens = 2
else:
self.cls_token = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
# self.num_tokens = 1
if if_abs_pos_embed:
# self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + self.num_tokens, self.embed_dim))
self.pos_embed_x = nn.Parameter(torch.zeros(1, 256, self.embed_dim))
self.pos_embed_z = nn.Parameter(torch.zeros(1, 64, self.embed_dim))
self.pos_embed_dynamic_z = nn.Parameter(torch.zeros(1, 64, self.embed_dim))
self.pos_drop = nn.Dropout(p=drop_rate)
if if_rope:
half_head_dim = embed_dim // 2
hw_seq_len = img_size // patch_size
self.rope = VisionRotaryEmbeddingFast(
dim=half_head_dim,
pt_seq_len=pt_hw_seq_len,
ft_seq_len=hw_seq_len
)
# self.head = nn.Linear(self.num_features, num_classes) if num_classes > 0 else nn.Identity()
# TODO: release this comment
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
# import ipdb;ipdb.set_trace()
inter_dpr = [0.0] + dpr
self.drop_path = DropPath(drop_path_rate) if drop_path_rate > 0. else nn.Identity()
# transformer blocks
self.layers = nn.ModuleList(
[
create_block(
embed_dim,
ssm_cfg=ssm_cfg,
norm_epsilon=norm_epsilon,
rms_norm=rms_norm,
residual_in_fp32=residual_in_fp32,
fused_add_norm=fused_add_norm,
layer_idx=i,
if_bimamba=if_bimamba,
bimamba_type=bimamba_type,
drop_path=inter_dpr[i],
if_devide_out=if_devide_out,
init_layer_scale=init_layer_scale,
**factory_kwargs,
)
for i in range(depth)
]
)
# output head
self.norm_f = (nn.LayerNorm if not rms_norm else RMSNorm)(
embed_dim, eps=norm_epsilon, **factory_kwargs
)
# self.pre_logits = nn.Identity()
# original init
self.patch_embed.apply(segm_init_weights)
# self.head.apply(segm_init_weights)
if if_abs_pos_embed:
trunc_normal_(self.pos_embed_x, std=.02)
trunc_normal_(self.pos_embed_z, std=.02)
if if_cls_token:
if use_double_cls_token:
trunc_normal_(self.cls_token_head, std=.02)
trunc_normal_(self.cls_token_tail, std=.02)
else:
trunc_normal_(self.cls_token, std=.02)
# mamba init
self.apply(
partial(
_init_weights,
n_layer=depth,
**(initializer_cfg if initializer_cfg is not None else {}),
)
)
def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
return {
i: layer.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs)
for i, layer in enumerate(self.layers)
}
@torch.jit.ignore
def no_weight_decay(self):
return {"pos_embed", "cls_token", "dist_token", "cls_token_head", "cls_token_tail"}
@torch.jit.ignore()
def load_pretrained(self, checkpoint_path, prefix=""):
_load_weights(self, checkpoint_path, prefix)
# 未调用
def forward_features(self, z, x, inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False):
x = self.patch_embed(x) #x.shape = torch.Size([B, 3, 224, 224]) -> torch.Size([2, 196, 384])
z = self.patch_embed(z)
B, M, _ = x.shape
if self.if_abs_pos_embed: #YES # self.if_abs_pos_embed = true
x = x + self.pos_embed_x # x = x + positon_embemding =torch.Size([B, 196, 384]) + torch.Size([1, 196, 384]) = torch.Size([B, 196, 384])
z = z + self.pos_embed_z
x = torch.cat((z, x), dim=1)
x = self.pos_drop(x) # x.shape = torch.Size([B, 196, 384])
if_flip_img_sequences = False
# NO
# mamba impl
residual = None
hidden_states = x
for layer in self.layers:
hidden_states, residual = layer(
hidden_states, residual, inference_params=inference_params
)
fused_add_norm_fn = rms_norm_fn if isinstance(self.norm_f, RMSNorm) else layer_norm_fn
hidden_states = fused_add_norm_fn(
self.drop_path(hidden_states),
self.norm_f.weight,
self.norm_f.bias,
eps=self.norm_f.eps,
residual=residual,
prenorm=False,
residual_in_fp32=self.residual_in_fp32,
)
return hidden_states
def foward_dynamic_features(self, stacked_template, inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False):
# print('1111111111111111')
B, M, C, H, W = stacked_template.size()
# print('stacked_template.size():', stacked_template.size()) # stacked_template.size(): torch.Size([2, 7, 3, 128, 128]) BatchSize
# 初始化一个空的列表用于存放打乱后的模板
shuffled_templates = []
# 遍历每个 batch
for i in range(B):
# 取出当前 batch 的模板,形状为 (M, C, H, W)
batch_templates = stacked_template[i]
# 将当前 batch 内的模板顺序打乱
indices = torch.randperm(M)
batch_templates = batch_templates[indices]
# 进行 Patch Embedding 操作并展平
patch_embeddings = self.patch_embed(batch_templates) # 形状假设为 (M, N, D)
flattened_embeddings = patch_embeddings.flatten(0, 1) # 形状变为 (M * N, D)
# 将打乱并处理后的模板加入新的列表
shuffled_templates.append(flattened_embeddings)
# 将列表展平并堆叠为一个新的张量,形状为 (B, M * N, D)
shuffled_templates = torch.stack(shuffled_templates, dim=0)
x = self.pos_drop(shuffled_templates)
if_flip_img_sequences = False
# mamba impl
residual = None
hidden_states = x
for layer in self.layers:
hidden_states, residual = layer(
hidden_states, residual, inference_params=inference_params
)
# Set prenorm=False here since we don't need the residual
fused_add_norm_fn = rms_norm_fn if isinstance(self.norm_f, RMSNorm) else layer_norm_fn
hidden_states = fused_add_norm_fn( # hidden_states.shape = torch.Size([2, 320, 384])
self.drop_path(hidden_states),
self.norm_f.weight,
self.norm_f.bias,
eps=self.norm_f.eps,
residual=residual,
prenorm=False,
residual_in_fp32=self.residual_in_fp32,
)
return hidden_states
def forward_dynamic_features_inference(self, template_list, inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False):
'''
input shape:
template_list: python list. item: torch.tensor, (1, 3, 128, 128)
'''
# B = 1
# stacked_templates = template_list.flatten(0,1) #为了测速而作的调整
stacked_templates = torch.cat(template_list, dim=0)
x = self.patch_embed(stacked_templates)
B, N, C = x.shape
x = x.reshape(1, B*N, C)
x = self.pos_drop(x)
if_flip_img_sequences = False
# mamba impl
residual = None
hidden_states = x
for layer in self.layers:
hidden_states, residual = layer(
hidden_states, residual, inference_params=inference_params
)
fused_add_norm_fn = rms_norm_fn
hidden_states = fused_add_norm_fn( # hidden_states.shape = torch.Size([2, 320, 384])
self.drop_path(hidden_states),
self.norm_f.weight,
self.norm_f.bias,
eps=self.norm_f.eps,
residual=residual,
prenorm=False,
residual_in_fp32=self.residual_in_fp32,
)
return hidden_states
def forward_dynamic_features_speed_test(self, template_list, inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False):
'''
input shape:
template_list: python list. item: torch.tensor, (1, 3, 128, 128)
'''
# B = 1
stacked_templates = template_list.flatten(0,1) #为了测速而作的调整
# stacked_templates = torch.cat(template_list, dim=0)
x = self.patch_embed(stacked_templates)
B, N, C = x.shape
x = x.reshape(1, B*N, C)
x = self.pos_drop(x)
if_flip_img_sequences = False
# mamba impl
residual = None
hidden_states = x
for layer in self.layers:
hidden_states, residual = layer(
hidden_states, residual, inference_params=inference_params
)
fused_add_norm_fn = rms_norm_fn
hidden_states = fused_add_norm_fn( # hidden_states.shape = torch.Size([2, 320, 384])
self.drop_path(hidden_states),
self.norm_f.weight,
self.norm_f.bias,
eps=self.norm_f.eps,
residual=residual,
prenorm=False,
residual_in_fp32=self.residual_in_fp32,
)
return hidden_states
def forward_tripple_features(self, dynamic_z, static_z, x, inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False):
# taken from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
# with slight modifications to add the dist_token
# print('pre_x.shape:',x.shape) # torch.Size([2, 3, 256, 256])
x = self.patch_embed(x) #x.shape = torch.Size([B, 3, 224, 224]) -> torch.Size([2, 196, 384])
z = self.patch_embed(static_z)
# print('tri_x.shape:', x.shape) # tri_x.shape: torch.Size([2, 256, 384])
B, M, _ = x.shape
# print('BM_x.shape:', x.shape) # BM_x.shape: torch.Size([2, 256, 384])
x = x + self.pos_embed_x # x = x + positon_embemding =torch.Size([B, 196, 384]) + torch.Size([1, 196, 384]) = torch.Size([B, 196, 384])
z = z + self.pos_embed_z
dynamic_z = dynamic_z + self.pos_embed_dynamic_z
x = torch.cat((z, dynamic_z, x), dim=1)
# x = torch.cat((dynamic_z, z, x), dim=1)
x = self.pos_drop(x) # x.shape = torch.Size([B, 196, 384])
if_flip_img_sequences = False
# mamba impl
residual = None
hidden_states = x
for layer in self.layers:
hidden_states, residual = layer(
hidden_states, residual, inference_params=inference_params
)
fused_add_norm_fn = rms_norm_fn
hidden_states = fused_add_norm_fn( # hidden_states.shape = torch.Size([2, 320, 384])
self.drop_path(hidden_states),
self.norm_f.weight,
self.norm_f.bias,
eps=self.norm_f.eps,
residual=residual,
prenorm=False,
residual_in_fp32=self.residual_in_fp32,
)
return hidden_states
def forward(self, static_z, dynamic_z, x, return_features=False, inference_params=None,
if_random_cls_token_position=False, if_random_token_rank=False,
feat_len_s=None, feat_len_z=None):
x = self.resnet(x)
# x = self.temporal_conv(x)
# x = self.sign_emb(x)
#################### 以下是原始逻辑 ###################
dynamic_z = self.foward_dynamic_features(dynamic_z)[:, -feat_len_z:]
x = self.forward_tripple_features(dynamic_z, static_z, x,
inference_params, if_random_cls_token_position=if_random_cls_token_position,
if_random_token_rank=if_random_token_rank)
# x = self.temporal_conv(x) # 1
# x = self.sign_emb(x) # 2 原文中, 1 和 2 已经规划到了 Sign Language Decoder中了
#################################
if return_features:
return x
if self.final_pool_type == 'max':
x = x.max(dim=1)[0]
# x = self.temporal_conv(x)
# x = self.sign_emb(x)
return x
def inference(self, dynamic_z, static_z, x, return_features=False, inference_params=None,
if_random_cls_token_position=False, if_random_token_rank=False,
feat_len_s=None, feat_len_z=None):
'''
dynamic_z -> mamba hidden states
static_z -> raw template rgb image
x -> raw search rgb image
'''
dynamic_z = dynamic_z[:, -feat_len_z:]
x = self.forward_tripple_features(dynamic_z, static_z, x,
inference_params, if_random_cls_token_position=if_random_cls_token_position,
if_random_token_rank=if_random_token_rank)
return x
@register_model
def vim_tiny_patch16_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, embed_dim=192, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='mean', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
checkpoint = torch.hub.load_state_dict_from_url(
url="to.do",
map_location="cpu", check_hash=True
)
model.load_state_dict(checkpoint["model"])
return model
@register_model
def vim_tiny_patch16_stride8_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, stride=8, embed_dim=192, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='mean', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
checkpoint = torch.hub.load_state_dict_from_url(
url="to.do",
map_location="cpu", check_hash=True
)
model.load_state_dict(checkpoint["model"])
return model
LIGHT @register_model
def vim_small_patch16_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, embed_dim=384, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='all', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
# checkpoint = torch.hub.load_state_dict_from_url(
# url="to.do",
# map_location="cpu", check_hash=True
# )
# model.load_state_dict(checkpoint["model"])
code Copy code
checkpoint = torch.load(pretrained, map_location="cpu")
missing_keys, unexpected_keys = model.load_state_dict(checkpoint["model"], strict=False)
print('Load pretrained model from: ' + pretrained)
return model
@register_model
def vim_small_patch16_stride8_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, stride=8, embed_dim=384, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='mean', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
checkpoint = torch.hub.load_state_dict_from_url(
url="to.do",
map_location="cpu", check_hash=True
)
model.load_state_dict(checkpoint["model"])
return model,分析特征提取网络。
class V_encoder(nn.Module):
def init (self, emb_size, feature_size):
super(V_encoder, self).init ()
code Copy code
self.src_emb = nn.Linear(feature_size, emb_size)
modules = []
modules.append(nn.BatchNorm1d(emb_size))
modules.append(nn.ReLU(inplace=True))
self.bn_ac = nn.Sequential(*modules)
for m in self.modules():
if isinstance(m, (nn.Conv1d,nn.Linear)):
nn.init.xavier_uniform_(m.weight, gain=nn.init.calculate_gain('relu'))
elif isinstance(m, nn.BatchNorm1d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
def forward(self, src:torch.Tensor):
src = self.src_emb(src)
src = self.bn_ac(src.permute(0,2,1)).permute(0,2,1)
return src
all = [
'vim_tiny_patch16_224', 'vim_small_patch16_224', 'vim_base_patch16_224',
'vim_tiny_patch16_384', 'vim_small_patch16_384', 'vim_base_patch16_384',
]
class PatchEmbed(nn.Module):
""" 2D Image to Patch Embedding
"""
def init (self, img_size=224, patch_size=16, stride=16, in_chans=3, embed_dim=768, norm_layer=None, flatten=True):
super().init ()
img_size = to_2tuple(img_size)
patch_size = to_2tuple(patch_size)
self.img_size = img_size
self.patch_size = patch_size
self.grid_size = ((img_size[0] - patch_size[0]) // stride + 1, (img_size[1] - patch_size[1]) // stride + 1)
self.num_patches = self.grid_size[0] * self.grid_size[1]
self.flatten = flatten
code Copy code
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=stride)
self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
def forward(self, x):
B, C, H, W = x.shape
# print('11x.shape:', x.shape) # 11x.shape: torch.Size([2, 3, 128, 128])
# assert H == self.img_size[0] and W == self.img_size[1], \
# f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
x = self.proj(x)
if self.flatten:
x = x.flatten(2).transpose(1, 2) # BCHW -> BNC
x = self.norm(x)
return x
class Block(nn.Module):
def init (
self, dim, mixer_cls, norm_cls=nn.LayerNorm, fused_add_norm=False, residual_in_fp32=False,drop_path=0.,
):
"""
Simple block wrapping a mixer class with LayerNorm/RMSNorm and residual connection"
code Copy code
This Block has a slightly different structure compared to a regular
prenorm Transformer block.
The standard block is: LN -> MHA/MLP -> Add.
[Ref: https://arxiv.org/abs/2002.04745]
Here we have: Add -> LN -> Mixer, returning both
the hidden_states (output of the mixer) and the residual.
This is purely for performance reasons, as we can fuse add and LayerNorm.
The residual needs to be provided (except for the very first block).
"""
super().__init__()
self.residual_in_fp32 = residual_in_fp32
self.fused_add_norm = fused_add_norm
self.mixer = mixer_cls(dim)
self.norm = norm_cls(dim)
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
if self.fused_add_norm:
assert RMSNorm is not None, "RMSNorm import fails"
assert isinstance(
self.norm, (nn.LayerNorm, RMSNorm)
), "Only LayerNorm and RMSNorm are supported for fused_add_norm"
def forward(
self, hidden_states: Tensor, residual: Optional[Tensor] = None, inference_params=None
):
r"""Pass the input through the encoder layer.
Args:
hidden_states: the sequence to the encoder layer (required).
residual: hidden_states = Mixer(LN(residual))
"""
fused_add_norm_fn = rms_norm_fn if isinstance(self.norm, RMSNorm) else layer_norm_fn
hidden_states, residual = fused_add_norm_fn(
hidden_states,
self.norm.weight,
self.norm.bias,
residual=residual,
prenorm=True,
residual_in_fp32=self.residual_in_fp32,
eps=self.norm.eps,
)
hidden_states = self.mixer(hidden_states, inference_params=inference_params)
return hidden_states, residual
def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
return self.mixer.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs)
def create_block(
d_model,
ssm_cfg=None,
norm_epsilon=1e-5,
drop_path=0.,
rms_norm=False,
residual_in_fp32=False,
fused_add_norm=False,
layer_idx=None,
device=None,
dtype=None,
if_bimamba=False,
bimamba_type="none",
if_devide_out=False,
init_layer_scale=None,
):
if if_bimamba:
bimamba_type = "v1"
if ssm_cfg is None:
ssm_cfg = {}
factory_kwargs = {"device": device, "dtype": dtype}
mixer_cls = partial(Mamba, layer_idx=layer_idx, bimamba_type=bimamba_type, if_devide_out=if_devide_out, init_layer_scale=init_layer_scale, **ssm_cfg, **factory_kwargs)
norm_cls = partial(
nn.LayerNorm if not rms_norm else RMSNorm, eps=norm_epsilon, **factory_kwargs
)
block = Block(
d_model,
mixer_cls,
norm_cls=norm_cls,
drop_path=drop_path,
fused_add_norm=fused_add_norm,
residual_in_fp32=residual_in_fp32,
)
block.layer_idx = layer_idx
return block
def init_weights(
module,
n_layer,
initializer_range=0.02, # Now only used for embedding layer.
rescale_prenorm_residual=True,
n_residuals_per_layer=1, # Change to 2 if we have MLP
):
if isinstance(module, nn.Linear):
if module.bias is not None:
if not getattr(module.bias, "no_reinit", False):
nn.init.zeros (module.bias)
elif isinstance(module, nn.Embedding):
nn.init.normal (module.weight, std=initializer_range)
code Copy code
if rescale_prenorm_residual:
# Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
# > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
# > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
# > -- GPT-2 :: https://openai.com/blog/better-language-models/
#
# Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
for name, p in module.named_parameters():
if name in ["out_proj.weight", "fc2.weight"]:
# Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
# Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
# We need to reinit p since this code could be called multiple times
# Having just p *= scale would repeatedly scale it down
nn.init.kaiming_uniform_(p, a=math.sqrt(5))
with torch.no_grad():
p /= math.sqrt(n_residuals_per_layer * n_layer)
def segm_init_weights(m):
if isinstance(m, nn.Linear):
trunc_normal_(m.weight, std=0.02)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.Conv2d):
# NOTE conv was left to pytorch default in my original init
lecun_normal_(m.weight)
if m.bias is not None:
nn.init.zeros_(m.bias)
elif isinstance(m, (nn.LayerNorm, nn.GroupNorm, nn.BatchNorm2d)):
nn.init.zeros_(m.bias)
nn.init.ones_(m.weight)
class VisionMamba(nn.Module):
def init (self,
img_size=224,
patch_size=16,
stride=16,
depth=24,
embed_dim=192,
channels=3,
num_classes=1000,
ssm_cfg=None,
drop_rate=0.,
drop_path_rate=0.1,
norm_epsilon: float = 1e-5,
rms_norm: bool = False,
initializer_cfg=None,
fused_add_norm=False,
residual_in_fp32=False,
device=None,
dtype=None,
ft_seq_len=None,
pt_hw_seq_len=14,
if_bidirectional=False,
final_pool_type='none',
if_abs_pos_embed=False,
if_rope=False,
if_rope_residual=False,
flip_img_sequences_ratio=-1.,
if_bimamba=False,
bimamba_type="none",
if_cls_token=False,
if_devide_out=False,
init_layer_scale=None,
use_double_cls_token=False,
use_middle_cls_token=False,
**kwargs):
factory_kwargs = {"device": device, "dtype": dtype}
# add factory_kwargs into kwargs
kwargs.update(factory_kwargs)
super().init ()
self.residual_in_fp32 = residual_in_fp32
self.fused_add_norm = fused_add_norm
self.if_bidirectional = if_bidirectional
self.final_pool_type = final_pool_type
self.if_abs_pos_embed = if_abs_pos_embed
self.if_rope = if_rope
self.if_rope_residual = if_rope_residual
self.flip_img_sequences_ratio = flip_img_sequences_ratio
# self.if_cls_token = if_cls_token
self.if_cls_token = False
self.use_double_cls_token = use_double_cls_token
self.use_middle_cls_token = use_middle_cls_token
self.num_tokens = 1 if if_cls_token else 0
####################
self.resnet = ResNetExtractor(resnet_type ="resnet18")
self.temporal_conv = TemporalConv(input_size=512, hidden_size=embed_dim)
self.sign_emb = V_encoder(emb_size=embed_dim, feature_size=embed_dim)
code Copy code
#######################
# pretrain parameters
self.num_classes = num_classes
self.d_model = self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
self.patch_embed = PatchEmbed(
img_size=img_size, patch_size=patch_size, stride=stride, in_chans=channels, embed_dim=embed_dim)
num_patches = self.patch_embed.num_patches
if if_cls_token:
if use_double_cls_token:
self.cls_token_head = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
self.cls_token_tail = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
self.num_tokens = 2
else:
self.cls_token = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
# self.num_tokens = 1
if if_abs_pos_embed:
# self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + self.num_tokens, self.embed_dim))
self.pos_embed_x = nn.Parameter(torch.zeros(1, 256, self.embed_dim))
self.pos_embed_z = nn.Parameter(torch.zeros(1, 64, self.embed_dim))
self.pos_embed_dynamic_z = nn.Parameter(torch.zeros(1, 64, self.embed_dim))
self.pos_drop = nn.Dropout(p=drop_rate)
if if_rope:
half_head_dim = embed_dim // 2
hw_seq_len = img_size // patch_size
self.rope = VisionRotaryEmbeddingFast(
dim=half_head_dim,
pt_seq_len=pt_hw_seq_len,
ft_seq_len=hw_seq_len
)
# self.head = nn.Linear(self.num_features, num_classes) if num_classes > 0 else nn.Identity()
# TODO: release this comment
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
# import ipdb;ipdb.set_trace()
inter_dpr = [0.0] + dpr
self.drop_path = DropPath(drop_path_rate) if drop_path_rate > 0. else nn.Identity()
# transformer blocks
self.layers = nn.ModuleList(
[
create_block(
embed_dim,
ssm_cfg=ssm_cfg,
norm_epsilon=norm_epsilon,
rms_norm=rms_norm,
residual_in_fp32=residual_in_fp32,
fused_add_norm=fused_add_norm,
layer_idx=i,
if_bimamba=if_bimamba,
bimamba_type=bimamba_type,
drop_path=inter_dpr[i],
if_devide_out=if_devide_out,
init_layer_scale=init_layer_scale,
**factory_kwargs,
)
for i in range(depth)
]
)
# output head
self.norm_f = (nn.LayerNorm if not rms_norm else RMSNorm)(
embed_dim, eps=norm_epsilon, **factory_kwargs
)
# self.pre_logits = nn.Identity()
# original init
self.patch_embed.apply(segm_init_weights)
# self.head.apply(segm_init_weights)
if if_abs_pos_embed:
trunc_normal_(self.pos_embed_x, std=.02)
trunc_normal_(self.pos_embed_z, std=.02)
if if_cls_token:
if use_double_cls_token:
trunc_normal_(self.cls_token_head, std=.02)
trunc_normal_(self.cls_token_tail, std=.02)
else:
trunc_normal_(self.cls_token, std=.02)
# mamba init
self.apply(
partial(
_init_weights,
n_layer=depth,
**(initializer_cfg if initializer_cfg is not None else {}),
)
)
def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
return {
i: layer.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs)
for i, layer in enumerate(self.layers)
}
@torch.jit.ignore
def no_weight_decay(self):
return {"pos_embed", "cls_token", "dist_token", "cls_token_head", "cls_token_tail"}
@torch.jit.ignore()
def load_pretrained(self, checkpoint_path, prefix=""):
_load_weights(self, checkpoint_path, prefix)
# 未调用
def forward_features(self, z, x, inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False):
x = self.patch_embed(x) #x.shape = torch.Size([B, 3, 224, 224]) -> torch.Size([2, 196, 384])
z = self.patch_embed(z)
B, M, _ = x.shape
if self.if_abs_pos_embed: #YES # self.if_abs_pos_embed = true
x = x + self.pos_embed_x # x = x + positon_embemding =torch.Size([B, 196, 384]) + torch.Size([1, 196, 384]) = torch.Size([B, 196, 384])
z = z + self.pos_embed_z
x = torch.cat((z, x), dim=1)
x = self.pos_drop(x) # x.shape = torch.Size([B, 196, 384])
if_flip_img_sequences = False
# NO
# mamba impl
residual = None
hidden_states = x
for layer in self.layers:
hidden_states, residual = layer(
hidden_states, residual, inference_params=inference_params
)
fused_add_norm_fn = rms_norm_fn if isinstance(self.norm_f, RMSNorm) else layer_norm_fn
hidden_states = fused_add_norm_fn(
self.drop_path(hidden_states),
self.norm_f.weight,
self.norm_f.bias,
eps=self.norm_f.eps,
residual=residual,
prenorm=False,
residual_in_fp32=self.residual_in_fp32,
)
return hidden_states
def foward_dynamic_features(self, stacked_template, inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False):
B, M, C, H, W = stacked_template.size()
# 初始化一个空的列表用于存放打乱后的模板
shuffled_templates = []
# 遍历每个 batch
for i in range(B):
# 取出当前 batch 的模板,形状为 (M, C, H, W)
batch_templates = stacked_template[i]
# 将当前 batch 内的模板顺序打乱
indices = torch.randperm(M)
batch_templates = batch_templates[indices]
# 进行 Patch Embedding 操作并展平
patch_embeddings = self.patch_embed(batch_templates) # 形状假设为 (M, N, D)
flattened_embeddings = patch_embeddings.flatten(0, 1) # 形状变为 (M * N, D)
# 将打乱并处理后的模板加入新的列表
shuffled_templates.append(flattened_embeddings)
# 将列表展平并堆叠为一个新的张量,形状为 (B, M * N, D)
shuffled_templates = torch.stack(shuffled_templates, dim=0)
x = self.pos_drop(shuffled_templates)
if_flip_img_sequences = False
# mamba impl
residual = None
hidden_states = x
for layer in self.layers:
hidden_states, residual = layer(
hidden_states, residual, inference_params=inference_params
)
# Set prenorm=False here since we don't need the residual
fused_add_norm_fn = rms_norm_fn if isinstance(self.norm_f, RMSNorm) else layer_norm_fn
hidden_states = fused_add_norm_fn( # hidden_states.shape = torch.Size([2, 320, 384])
self.drop_path(hidden_states),
self.norm_f.weight,
self.norm_f.bias,
eps=self.norm_f.eps,
residual=residual,
prenorm=False,
residual_in_fp32=self.residual_in_fp32,
)
return hidden_states
def forward_dynamic_features_inference(self, template_list, inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False):
'''
input shape:
template_list: python list. item: torch.tensor, (1, 3, 128, 128)
'''
# B = 1
# stacked_templates = template_list.flatten(0,1) #为了测速而作的调整
stacked_templates = torch.cat(template_list, dim=0)
x = self.patch_embed(stacked_templates)
B, N, C = x.shape
x = x.reshape(1, B*N, C)
x = self.pos_drop(x)
if_flip_img_sequences = False
# mamba impl
residual = None
hidden_states = x
for layer in self.layers:
hidden_states, residual = layer(
hidden_states, residual, inference_params=inference_params
)
fused_add_norm_fn = rms_norm_fn
hidden_states = fused_add_norm_fn( # hidden_states.shape = torch.Size([2, 320, 384])
self.drop_path(hidden_states),
self.norm_f.weight,
self.norm_f.bias,
eps=self.norm_f.eps,
residual=residual,
prenorm=False,
residual_in_fp32=self.residual_in_fp32,
)
return hidden_states
def forward_dynamic_features_speed_test(self, template_list, inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False):
'''
input shape:
template_list: python list. item: torch.tensor, (1, 3, 128, 128)
'''
# B = 1
stacked_templates = template_list.flatten(0,1) #为了测速而作的调整
# stacked_templates = torch.cat(template_list, dim=0)
x = self.patch_embed(stacked_templates)
B, N, C = x.shape
x = x.reshape(1, B*N, C)
x = self.pos_drop(x)
if_flip_img_sequences = False
# mamba impl
residual = None
hidden_states = x
for layer in self.layers:
hidden_states, residual = layer(
hidden_states, residual, inference_params=inference_params
)
fused_add_norm_fn = rms_norm_fn
hidden_states = fused_add_norm_fn( # hidden_states.shape = torch.Size([2, 320, 384])
self.drop_path(hidden_states),
self.norm_f.weight,
self.norm_f.bias,
eps=self.norm_f.eps,
residual=residual,
prenorm=False,
residual_in_fp32=self.residual_in_fp32,
)
return hidden_states
def forward_tripple_features(self, dynamic_z, static_z, x, inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False):
# taken from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
# with slight modifications to add the dist_token
# print('pre_x.shape:',x.shape) # torch.Size([2, 3, 256, 256])
x = self.patch_embed(x) #x.shape = torch.Size([B, 3, 224, 224]) -> torch.Size([2, 196, 384])
z = self.patch_embed(static_z)
# print('tri_x.shape:', x.shape) # tri_x.shape: torch.Size([2, 256, 384])
B, M, _ = x.shape
# print('BM_x.shape:', x.shape) # BM_x.shape: torch.Size([2, 256, 384])
x = x + self.pos_embed_x # x = x + positon_embemding =torch.Size([B, 196, 384]) + torch.Size([1, 196, 384]) = torch.Size([B, 196, 384])
z = z + self.pos_embed_z
dynamic_z = dynamic_z + self.pos_embed_dynamic_z
x = torch.cat((z, dynamic_z, x), dim=1)
# x = torch.cat((dynamic_z, z, x), dim=1)
x = self.pos_drop(x) # x.shape = torch.Size([B, 196, 384])
if_flip_img_sequences = False
# mamba impl
residual = None
hidden_states = x
for layer in self.layers:
hidden_states, residual = layer(
hidden_states, residual, inference_params=inference_params
)
fused_add_norm_fn = rms_norm_fn
hidden_states = fused_add_norm_fn( # hidden_states.shape = torch.Size([2, 320, 384])
self.drop_path(hidden_states),
self.norm_f.weight,
self.norm_f.bias,
eps=self.norm_f.eps,
residual=residual,
prenorm=False,
residual_in_fp32=self.residual_in_fp32,
)
return hidden_states
def forward(self, static_z, dynamic_z, x, return_features=False, inference_params=None,
if_random_cls_token_position=False, if_random_token_rank=False,
feat_len_s=None, feat_len_z=None):
x = self.resnet(x)
# print('222222222222222222')
# x = self.temporal_conv(x)
# x = self.sign_emb(x)
#################### 以下是原始逻辑 ###################
dynamic_z = self.foward_dynamic_features(dynamic_z)[:, -feat_len_z:]
x = self.forward_tripple_features(dynamic_z, static_z, x,
inference_params, if_random_cls_token_position=if_random_cls_token_position,
if_random_token_rank=if_random_token_rank)
# x = self.temporal_conv(x) # 1
# x = self.sign_emb(x) # 2 原文中, 1 和 2 已经规划到了 Sign Language Decoder中了
#################################
if return_features:
return x
if self.final_pool_type == 'max':
x = x.max(dim=1)[0]
# x = self.temporal_conv(x)
# x = self.sign_emb(x)
return x
def inference(self, dynamic_z, static_z, x, return_features=False, inference_params=None,
if_random_cls_token_position=False, if_random_token_rank=False,
feat_len_s=None, feat_len_z=None):
'''
dynamic_z -> mamba hidden states
static_z -> raw template rgb image
x -> raw search rgb image
'''
dynamic_z = dynamic_z[:, -feat_len_z:]
x = self.forward_tripple_features(dynamic_z, static_z, x,
inference_params, if_random_cls_token_position=if_random_cls_token_position,
if_random_token_rank=if_random_token_rank)
return x
@register_model
def vim_tiny_patch16_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, embed_dim=192, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='mean', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
checkpoint = torch.hub.load_state_dict_from_url(
url="to.do",
map_location="cpu", check_hash=True
)
model.load_state_dict(checkpoint["model"])
return model
@register_model
def vim_tiny_patch16_stride8_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, stride=8, embed_dim=192, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='mean', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
checkpoint = torch.hub.load_state_dict_from_url(
url="to.do",
map_location="cpu", check_hash=True
)
model.load_state_dict(checkpoint["model"])
return model
LIGHT @register_model
def vim_small_patch16_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, embed_dim=384, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='all', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
# checkpoint = torch.hub.load_state_dict_from_url(
# url="to.do",
# map_location="cpu", check_hash=True
# )
# model.load_state_dict(checkpoint["model"])
code Copy code
checkpoint = torch.load(pretrained, map_location="cpu")
missing_keys, unexpected_keys = model.load_state_dict(checkpoint["model"], strict=False)
print('Load pretrained model from: ' + pretrained)
return model
@register_model
def vim_small_patch16_stride8_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2(pretrained=False, **kwargs):
model = VisionMamba(
patch_size=16, stride=8, embed_dim=384, depth=24, rms_norm=True, residual_in_fp32=True, fused_add_norm=True, final_pool_type='mean', if_abs_pos_embed=True, if_rope=False, if_rope_residual=False, bimamba_type="v2", if_cls_token=True, if_devide_out=True, use_middle_cls_token=True, **kwargs)
model.default_cfg = _cfg()
if pretrained:
checkpoint = torch.hub.load_state_dict_from_url(
url="to.do",
map_location="cpu", check_hash=True
)
model.load_state_dict(checkpoint["model"])
return model中的ResNetExtractor,集成进class VisionMamba中。
if self.conv_type == 0:
self.kernel_size = ['K3']
elif self.conv_type == 1:
self.kernel_size = ['K5', "P2"]
elif self.conv_type == 2:
self.kernel_size = ['K5', "P2", 'K5', "P2"]
modules = []
for layer_idx, ks in enumerate(self.kernel_size):
input_sz = self.input_size if layer_idx == 0 else self.hidden_size
if ks[0] == 'P':
modules.append(nn.MaxPool1d(kernel_size=int(ks[1]), ceil_mode=False))
elif ks[0] == 'K':
modules.append(
nn.Conv1d(input_sz, self.hidden_size, kernel_size=int(ks[1]), stride=1, padding=0)
)
modules.append(nn.BatchNorm1d(self.hidden_size))
modules.append(nn.ReLU(inplace=True))
self.temporal_conv = nn.Sequential(*modules)
def forward(self, x):
x = self.temporal_conv(x.permute(0,2,1))
return x.permute(0,2,1)
class V_encoder(nn.Module):
def init (self, emb_size, feature_size):
super(V_encoder, self).init ()
code Copy code
self.src_emb = nn.Linear(feature_size, emb_size)
modules = []
modules.append(nn.BatchNorm1d(emb_size))
modules.append(nn.ReLU(inplace=True))
self.bn_ac = nn.Sequential(*modules)
for m in self.modules():
if isinstance(m, (nn.Conv1d,nn.Linear)):
nn.init.xavier_uniform_(m.weight, gain=nn.init.calculate_gain('relu'))
elif isinstance(m, nn.BatchNorm1d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
def forward(self, src:torch.Tensor):
src = self.src_emb(src)
src = self.bn_ac(src.permute(0,2,1)).permute(0,2,1)
return src
class SignModel(nn.Module):
def init (self, config, args, embed_dim=1024):
super(SignModel, self).init ()
self.args = args
self.resnet = resnet(name="resnet18")
self.time_mamba = time_mamba()
self.mbart = MBartForConditionalGeneration.from_pretrained(config['model']['visual_encoder'])
self.conv_1d = TemporalConv(input_size=512, hidden_size=1024, conv_type=2)
self.sign_emb = V_encoder(emb_size=embed_dim, feature_size=embed_dim)
self.embed_scale = 1.0
code Copy code
def __str__(self):
model_parameters = filter(lambda p: p.requires_grad, self.parameters())
params = sum([np.prod(p.size()) for p in model_parameters])
return super().__str__() + '\nTrainable parameters: {}'.format(params)
def visual_forward(self, src_input):
attention_mask = src_input['attention_mask']
out_visual = self.resnet(src_input['input_ids'].cuda(), src_input['src_length_batch'])
out_visual = self.time_mamba(out_visual)
frames_feature = self.conv_1d(out_visual)
inputs_embeds = self.sign_emb(frames_feature)
inputs_embeds = self.embed_scale * inputs_embeds
return inputs_embeds, attention_mask
def forward(self, src_input, tgt_input):
inputs_embeds, attention_mask = self.visual_forward(src_input)
out = self.mbart(inputs_embeds = inputs_embeds,
attention_mask = attention_mask.cuda(),
labels = tgt_input['input_ids'].cuda(),
decoder_attention_mask = tgt_input['attention_mask'].cuda(),
return_dict = True,
)
return out['logits']
def generate(self,src_input, max_new_tokens, num_beams, decoder_start_token_id):
inputs_embeds, attention_mask = self.visual_forward(src_input)
out = self.mbart.generate(inputs_embeds = inputs_embeds,
attention_mask = attention_mask.cuda(),max_new_tokens=max_new_tokens,num_beams = num_beams,
decoder_start_token_id=decoder_start_token_id
)
return out
中的调用的resnet做了什么处理?其中,from ctypes import util
from cv2 import IMREAD_GRAYSCALE
import torch
import utils as utils
import torch.utils.data.dataset as Dataset
from torch.nn.utils.rnn import pad_sequence
import math
from torchvision import transforms
from PIL import Image
import cv2
import os
import random
import numpy as np
import lmdb
import io
import time
from vidaug import augmentors as va
from augmentation import *
from loguru import logger
from hpman.m import _
global definition class Normaliztion(object):
"""
same as mxnet, normalize into [-1, 1]
image = (image - 127.5)/128
"""
code Copy code
def __call__(self, Image):
if isinstance(Image, PIL.Image.Image):
Image = np.asarray(Image, dtype=np.uint8)
new_video_x = (Image - 127.5) / 128
return new_video_x
class SomeOf(object):
"""
Selects one augmentation from a list.
Args:
transforms (list of "Augmentor" objects): The list of augmentations to compose.
"""
code Copy code
def __init__(self, transforms1, transforms2):
self.transforms1 = transforms1
self.transforms2 = transforms2
def __call__(self, clip):
select = random.choice([0, 1, 2])
if select == 0:
return clip
elif select == 1:
if random.random() > 0.5:
return self.transforms1(clip)
else:
return self.transforms2(clip)
else:
clip = self.transforms1(clip)
clip = self.transforms2(clip)
return clip
class S2T_Dataset(Dataset.Dataset):
def init (self,path,tokenizer,config,args,phase, training_refurbish=False):
self.config = config
self.args = args
self.training_refurbish = training_refurbish
code Copy code
self.raw_data = utils.load_dataset_file(path)
self.tokenizer = tokenizer
self.img_path = config['data']['img_path']
self.phase = phase
self.max_length = config['data']['max_length']
self.list = [key for key,value in self.raw_data.items()]
sometimes = lambda aug: va.Sometimes(0.5, aug) # Used to apply augmentor with 50% probability
self.seq = va.Sequential([
sometimes(va.RandomRotate(30)),
sometimes(va.RandomTranslate(x=10, y=10)),
])
self.seq_color = va.Sequential([
sometimes(Brightness(min=0.1, max=1.5)),
sometimes(Color(min=0.1, max=1.5)),
])
def __len__(self):
return len(self.raw_data)
def __getitem__(self, index):
key = self.list[index]
sample = self.raw_data[key]
tgt_sample = sample['text']
length = sample['length']
name_sample = sample['name']
img_sample = self.load_imgs([self.img_path + x for x in sample['imgs_path']])
return name_sample,img_sample,tgt_sample
def load_imgs(self, paths):
data_transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
])
if len(paths) > self.max_length:
tmp = sorted(random.sample(range(len(paths)), k=self.max_length))
new_paths = []
for i in tmp:
new_paths.append(paths[i])
paths = new_paths
imgs = torch.zeros(len(paths),3, self.args.input_size,self.args.input_size)
crop_rect, resize = utils.data_augmentation(resize=(self.args.resize, self.args.resize), crop_size=self.args.input_size, is_train=(self.phase=='train'))
batch_image = []
for i,img_path in enumerate(paths):
img = cv2.imread(img_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = Image.fromarray(img)
batch_image.append(img)
if self.phase == 'train':
batch_image = self.seq(batch_image)
for i, img in enumerate(batch_image):
img = img.resize(resize)
img = data_transform(img).unsqueeze(0)
imgs[i,:,:,:] = img[:,:,crop_rect[1]:crop_rect[3],crop_rect[0]:crop_rect[2]]
return imgs
def collate_fn(self,batch):
tgt_batch,img_tmp,src_length_batch,name_batch = [],[],[],[]
for name_sample, img_sample, tgt_sample in batch:
name_batch.append(name_sample)
img_tmp.append(img_sample)
tgt_batch.append(tgt_sample)
max_len = max([len(vid) for vid in img_tmp])
video_length = torch.LongTensor([np.ceil(len(vid) / 4.0) * 4 + 16 for vid in img_tmp])
left_pad = 8
right_pad = int(np.ceil(max_len / 4.0)) * 4 - max_len + 8
max_len = max_len + left_pad + right_pad
padded_video = [torch.cat(
(
vid[0][None].expand(left_pad, -1, -1, -1),
vid,
vid[-1][None].expand(max_len - len(vid) - left_pad, -1, -1, -1),
)
, dim=0)
for vid in img_tmp]
img_tmp = [padded_video[i][0:video_length[i],:,:,:] for i in range(len(padded_video))]
for i in range(len(img_tmp)):
src_length_batch.append(len(img_tmp[i]))
src_length_batch = torch.tensor(src_length_batch)
img_batch = torch.cat(img_tmp,0)
new_src_lengths = (((src_length_batch-5+1) / 2)-5+1)/2
new_src_lengths = new_src_lengths.long()
mask_gen = []
for i in new_src_lengths:
tmp = torch.ones([i]) + 7
mask_gen.append(tmp)
mask_gen = pad_sequence(mask_gen, padding_value=PAD_IDX,batch_first=True)
img_padding_mask = (mask_gen != PAD_IDX).long()
with self.tokenizer.as_target_tokenizer():
tgt_input = self.tokenizer(tgt_batch, return_tensors="pt",padding = True, truncation=True)
src_input = {}
src_input['input_ids'] = img_batch
src_input['attention_mask'] = img_padding_mask
src_input['name_batch'] = name_batch
src_input['src_length_batch'] = src_length_batch
src_input['new_src_length_batch'] = new_src_lengths
if self.training_refurbish:
masked_tgt = utils.NoiseInjecting(tgt_batch, self.args.noise_rate, noise_type=self.args.noise_type, random_shuffle=self.args.random_shuffle, is_train=(self.phase=='train'))
with self.tokenizer.as_target_tokenizer():
masked_tgt_input = self.tokenizer(masked_tgt, return_tensors="pt", padding = True, truncation=True)
return src_input, tgt_input, masked_tgt_input
return src_input, tgt_input
def __str__(self):
return f'#total {self.phase} set: {len(self.list)}.'