Explore / Programming 那么① # Copyright (c) 2015-present, Facebook, Inc. All rights reserved. import torch… Save Share Download ▾ ReportJump to turn (7) 1 那么① # Copyright (c) 2015-present, Facebook, Inc. All rights reserved. import tor 2 那么import torch import torch.nn as nn import numpy as np import torchvision from 3 难道没有使用mamba? 4 所以重新分析SignModel 中用于提取视觉特征的网络。 5 那么当前模型中的网络设计是:# Copyright (c) 2015-present, Facebook, Inc. All rights reserved. 6 那么基于# Copyright (c) 2015-present, Facebook, Inc. All rights reserved. import tor 7 不是的,我们是希望将resnet集成进# Copyright (c) 2015-present, Facebook, Inc. All rights reser Copy first prompt
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 7 (14 messages)
Language en
Conversation date Sep 8, 2024
Added to archive Nov 16, 2026
ID 01m7h41tq1qw98xhdpe4zketntSource & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: 19c4470c2e25a7bd6abe018b62489c1f
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 和 ② """
Basic ostrack model.
"""
import math
import os
from typing import List
import torch
from torch import nn
from torch.nn.modules.transformer import _get_clones
from lib.models.layers.head import build_box_head
from lib.models.ostrack.vit import vit_base_patch16_224
from lib.models.ostrack.vit_ce import vit_large_patch16_224_ce, vit_base_patch16_224_ce
from lib.utils.box_ops import box_xyxy_to_cxcywh
from lib.models.ostrack.models_mamba import create_block
from timm.models import create_model
import torch.nn.functional as F
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from lib.models.memnet import MemNet
class OSTrack(nn.Module):
""" This is the base class for ostrack """
def build_ostrack(cfg, training=True):
code Copy code
backbone = create_model(
model_name='vim_small_patch16_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2',
pretrained='/data2/local_userdata/heyuting/MambaEVT/MambaEVT-main/lib/models/pretrained_models/vim_s_midclstok_80p5acc.pth',
num_classes=1000,
drop_rate=0.0,
drop_path_rate=0.1,
drop_block_rate=None,
img_size=224
)
hidden_dim = 384
box_head = build_box_head(cfg, hidden_dim)
# mem_cell = MemNet(cfg, is_train=True)
# model = OSTr
model = OSTrack(
backbone,
box_head,
aux_loss=False,
head_type=cfg.MODEL.HEAD.TYPE,
)
if 'OSTrack' in cfg.MODEL.PRETRAIN_FILE and training:
checkpoint = torch.load(cfg.MODEL.PRETRAIN_FILE, map_location="cpu")
missing_keys, unexpected_keys = model.load_state_dict(checkpoint["net"], strict=False)
print('Load pretrained model from: ' + cfg.MODEL.PRETRAIN_FILE, flush=True)
return model中,视觉特征提取网络是什么?
Show full message · 799 lines Assistant2024-09-08 14:12 UTC Copy response
在 OSTrack 模型中,视觉特征提取网络使用的是 VisionMamba 类的模型实例。这个类是基于 Vision Transformer(ViT)的变体,结合了 Facebook 提出的 Mamba 函数式混合块(Mamba Mixer Blocks)用于特征提取。在 build_ostrack 函数中,创建了一个具体的 VisionMamba 模型实例,函数调用了 create_model,其使用的模型名称为 vim_small_patch16_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2。
总体上,这个视觉特征提取器基于 Vision Transformer 的架构进行修改,并集成了 Bi-Mamba 模块和其他一些特性(如绝对位置嵌入和条件位置编码)。这些修改旨在改进特征提取的效果,并提升 Mamba 模块在视觉任务中的应用能力。
那么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-08 14:12 UTC Copy response
在 SignModel 类中,视觉特征提取网络使用的是 ResNet 模型。具体来说,SignModel 类初始化时创建了一个 resnet 类的实例,其中调用了 make_resnet 函数。这一函数根据传入的名称参数(如 'resnet18')创建对应的 ResNet 结构(例如 resnet18, resnet34 等)。make_resnet 函数还从 torchvision 库中载入预训练的 ResNet 模型,并将最后的 fc 层替换为 nn.Identity(),即一个占位符,不做任何操作。这使网络的输出为最后一个卷积层的特征。
在 SignModel 中,下面这行代码与视觉特征提取相关:
python Copy code
self.resnet = resnet(name="resnet18")
这行代码实例化了一个 resnet 类,默认使用 resnet18 作为基础模型。特征提取通过调用这个实例的 forward 方法实现,该方法返回提取的视觉特征。
Assistant2024-09-08 14:13 UTC Copy response
在 SignModel 中确实使用了 Mamba 相关的功能,这是通过 time_mamba 模块实现的。time_mamba 类封装了 Mamba 的功能,它使用了 create_block 函数来创建一个 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
在 SignModel 的 visual_forward 方法中,经过 ResNet 处理的输出 out_visual 进一步通过了 time_mamba 模块:
python Copy code
out_visual = self.resnet(src_input['input_ids'].cuda(), src_input['src_length_batch'])
out_visual = self.time_mamba(out_visual)
这意味着虽然 ResNet 负责初步的视觉特征提取,但 Mamba 块被用于对这些特征进行进一步的处理或增强。因此,SignModel 中确实结合了 ResNet 和 Mamba 的功能来对视觉特征进行处理。
所以重新分析SignModel 中用于提取视觉特征的网络。
Assistant2024-09-08 14:16 UTC Copy response
在 SignModel 类中,提取视觉特征的过程结合了多个模块。以下是对其如何构成视觉特征提取网络的分析:
ResNet Backbone :
首先,SignModel 中使用了 resnet 来提取初步的视觉特征:
python Copy code
self.resnet = resnet(name="resnet18")
resnet 类内部通过 make_resnet 函数载入了一个预训练的 ResNet 模型,默认使用 resnet18。
这个 ResNet 模型用于从输入数据(假设是图像帧)中提取初步的视觉特征。
Mamba Block :
从 ResNet 提取特征后,数据经过 time_mamba 模块:
python Copy code
out_visual = self.resnet(src_input['input_ids'].cuda(), src_input['src_length_batch'])
out_visual = self.time_mamba(out_visual)
time_mamba 类使用一个 Mamba 块,通过 create_block 函数初始化,在 forward 方法中对来自 ResNet 的特征进行进一步处理。
Mamba 块是一种特征变换机制,可以对特征进行非线性变换以改善表示能力。
Temporal Convolution :
进一步的,经过 Mamba 块的特征输入 TemporalConv 模块:
python Copy code
frames_feature = self.conv_1d(out_visual)
这个模块为一维的卷积神经网络,旨在捕获特征随时间的变化,这是因为手语等序列数据在时间维度上可能存在相关性。
Feature Embedding :
最后,卷积的输出通过 V_encoder 进行线性变换和批归一化:
python Copy code
inputs_embeds = self.sign_emb(frames_feature)
这是为了将特征嵌入到固定大小的表示中,以便用于后续的模型处理。
综合来看,SignModel 中用于提取和处理视觉特征的网络部分包括一个 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
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 · 648 lines Assistant2024-09-08 14:17 UTC Copy response
当前模型中用于提取视觉特征的组件是 VisionMamba 类,它构建在 Vision Transformer(ViT)的架构之上,并结合了 Mamba 模块。这是一种基于 Transformer 的方法,用于从图像中提取强表达能力的特征。
主要结构包括:
Patch Embedding :
PatchEmbed 类用于将输入图像拆分成固定大小的块(patches),每个块通过一个卷积层投影到一个高维空间中。这是 Vision Transformer 方法的一部分,通过将图像分割和特征向量化来准备输入数据。
Mamba Block :
使用 Mamba 模块的自定义混合器类(Mamba)增强特征提取,具体经过 create_block 函数创建。Mamba 是一种复杂的激活机制,集成了多模块融合,可以提高特征表达能力。
Position Embedding :
位置嵌入被用于在特征中编码位置信息,使得模型能够捕获输入中元素的相对位置关系。这里实现了绝对位置编码(if_abs_pos_embed)和旋转位置编码(if_rope)。
Drop Path Regularization :
DropPath 是一种正则化技术,会随机删除某些路径,以提高模型的泛化能力。
Sequential Layers :
模型使用了一系列 Block 模块,其中包含 Mixer 和正则项,用于依次处理由 Patch Embedding 得到的特征。这些模块的重复堆叠使得特征提取更为有效。
这个结构的目的是使用 ViT 和 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
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 · 648 lines Assistant2024-09-08 14:19 UTC Copy response
要在 SignModel 中替换视觉特征提取网络,可以将旧的特征提取网络替换为新的基于 VisionMamba 的网络。以下是一个如何在 SignModel 类中进行替换的示例:
python Copy code
import torch
import torch.nn as nn
import numpy as np
from transformers import MBartForConditionalGeneration
# 假设 `VisionMamba` 已被正确导入
from path_to_visionmamba import VisionMamba # 根据实际路径导入
class SignModel(nn.Module):
def __init__(self, config, args, embed_dim=1024):
super(SignModel, self).__init__()
self.args = args
# 使用 VisionMamba 替换 ResNet
self.vision_mamba = VisionMamba(
img_size=224, 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,
use_middle_cls_token=True
)
self.mbart = MBartForConditionalGeneration.from_pretrained(config['model']['visual_encoder'])
self.conv_1d = TemporalConv(input_size=384, hidden_size=1024, conv_type=2)
self.sign_emb = V_encoder(emb_size=embed_dim, feature_size=embed_dim)
self.embed_scale = 1.0
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']
# 替换 ResNet 的特征提取部分
out_visual = self.vision_mamba.forward(src_input['input_ids'].cuda(), None, None, return_features=True)
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集成进# 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 · 648 lines Assistant2024-09-08 14:24 UTC Copy response
要将 CNN(如 ResNet)与 Mamba 和 Vision Transformer 相结合,可以设计一个混合特征提取器,该提取器先用 CNN 提取局部特征,然后用 Mamba Transformer 对特征进行全局上下文理解。以下是实现这种设计的一种方法:
Copy first response
Not yet included in a published release.
# 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
# def __init__(self, visionmamba, memory, box_head, aux_loss=False, head_type="CORNER"):
def __init__(self, visionmamba, box_head, aux_loss=False, head_type="CORNER"):
""" Initializes the model.
Parameters:
transformer: torch module of the transformer architecture.
aux_loss: True if auxiliary decoding losses (loss at each decoder layer) are to be used.
"""
super().__init__()
self.backbone = visionmamba
self.box_head = box_head
# self.memory = memory
# self.mem_cell = mem_cell
self.aux_loss = aux_loss
self.head_type = head_type
if head_type == "CORNER" or head_type == "CENTER":
self.feat_sz_s = int(box_head.feat_sz)
self.feat_sz_z = int(box_head.feat_sz/2)
self.feat_len_s = int(box_head.feat_sz ** 2)
self.feat_len_z = int(self.feat_sz_z ** 2)
if self.aux_loss:
self.box_head = _get_clones(self.box_head, 6)
def forward(self,
static_template: torch.Tensor,
dynamic_templates: torch.Tensor,
# template: torch.Tensor, # [bs, 3, 256, 256]
search: torch.Tensor, # [bs, 3, 128, 128]
ce_template_mask=None,
ce_keep_rate=None,
return_last_attn=False,
):
# print('static_template shape:', static_template.shape) # static_template shape: torch.Size([2, 3, 128, 128])
# print('22222222222222222222222dynamic_templates shape:', dynamic_templates.shape) # dynamic_templates shape: torch.Size([2, 7, 3, 128, 128])
# print('search shape:', search.shape) # search shape: torch.Size([2, 3, 256, 256])
dynamic_feature = self.backbone.foward_dynamic_features(dynamic_templates)[:, -self.feat_len_z:]
x = self.backbone.forward_tripple_features(static_z=static_template,
dynamic_z =dynamic_feature,
x=search,
inference_params=None,
if_random_cls_token_position=False,
if_random_token_rank=False)
# Forward head
feat_last = x # x.shape = torch.Size([2, 320, 384])
# if isinstance(x, list):
# feat_last = x[-1]
out = self.forward_head(feat_last, None)
# out.update(aux_dict)
out['backbone_feat'] = x
# dynamic_features = out['top60patches']
return out
def inference(self, dynamic_template: torch.Tensor, static_template: torch.Tensor, search: torch.Tensor):
# self.dynamic_template = dynamic_template[:, -self.feat_len_z:]
# self.static_template = static_template
x = self.backbone.inference(dynamic_template, static_template, search,feat_len_s=self.feat_len_s,
feat_len_z=self.feat_len_z,)
# Forward head
feat_last = x # x.shape = torch.Size([2, 320, 384])
out = self.forward_head(feat_last, None)
out['backbone_feat'] = x
return out
def forward_head(self, feature, gt_score_map=None):
"""
cat_feature: output embeddings of the backbone, it can be (HW1+HW2, B, C) or (HW2, B, C)
"""
search_feature = feature[:, -self.feat_len_s:] # search_feature.shape = torch.Size([2, 256, 384])
opt = (search_feature.unsqueeze(-1)).permute((0, 3, 2, 1)).contiguous() # opt.shape = torch.Size([2, 1, 384, 256])
bs, Nq, C, HW = opt.size()
opt_feat = opt.view(-1, C, self.feat_sz_s, self.feat_sz_s) # opt_feat.shape = torch.Size([2, 384, 16, 16])
score_map_ctr, bbox, size_map, offset_map = self.box_head(opt_feat, gt_score_map)
# 为了提速而省去一切if操作
outputs_coord = bbox
outputs_coord_new = outputs_coord.view(bs, Nq, 4)
out = {'pred_boxes': outputs_coord_new,
'score_map': score_map_ctr,
'size_map': size_map,
'offset_map': offset_map,
# 'top60patches': selected_patches,
}
return out
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))
"""
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,它采用什么提取视觉特征?
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,重写SignModel中的视觉特征提取网络。
关键点:
将 VisionMamba 所需的所有超参数传递给其构造函数,包括 img_size、patch_size、embed_dim 等。
确保 forward 方法调用 VisionMamba 时传递适当的输入,并获取特征表示。
修改相关模块(如 TemporalConv 和 V_encoder)处理新的输入大小和特征维度。
使用 VisionMamba 替换后模型的特征提取部分将更具现代化、表达更丰富的特征,这是因为它更加依赖于 Transformer 的设计。
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中,使得模型可以结合CNN和mamba的优势。
import torch
import torch.nn as nn
from functools import partial
from torch import Tensor
from typing import Optional
from torchvision import models
from mamba_ssm.modules.mamba_simple import Mamba
from timm.models.vision_transformer import _cfg
from timm.models.layers import DropPath, to_2tuple
from timm.models.layers import trunc_normal_, lecun_normal_
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
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)
x = self.norm(x)
return x
class HybridVisionTransformer(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=1e-5, rms_norm=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):
super().__init__()
factory_kwargs = {"device": device, "dtype": dtype}
kwargs.update(factory_kwargs)
# CNN Backbone for local feature extraction
self.cnn_backbone = models.resnet50(pretrained=True)
self.cnn_backbone.fc = nn.Identity() # Remove the final classification layer
self.mamba_transformer = VisionMamba(
img_size=img_size, patch_size=patch_size, stride=stride, depth=depth,
embed_dim=embed_dim, channels=channels, num_classes=num_classes,
ssm_cfg=ssm_cfg, drop_rate=drop_rate, drop_path_rate=drop_path_rate,
norm_epsilon=norm_epsilon, rms_norm=rms_norm, initializer_cfg=initializer_cfg,
fused_add_norm=fused_add_norm, residual_in_fp32=residual_in_fp32,
device=device, dtype=dtype, ft_seq_len=ft_seq_len, pt_hw_seq_len=pt_hw_seq_len,
if_bidirectional=if_bidirectional, final_pool_type=final_pool_type,
if_abs_pos_embed=if_abs_pos_embed, if_rope=if_rope,
if_rope_residual=if_rope_residual, flip_img_sequences_ratio=flip_img_sequences_ratio,
if_bimamba=if_bimamba, bimamba_type=bimamba_type, if_cls_token=if_cls_token,
if_devide_out=if_devide_out, init_layer_scale=init_layer_scale,
use_double_cls_token=use_double_cls_token, use_middle_cls_token=use_middle_cls_token,
**kwargs
)
def forward(self, x):
# Extract local features using CNN
x = self.cnn_backbone(x)
# Transform CNN output for Transformer input
x = x.unsqueeze(-1).unsqueeze(-1) # Reshape to match Conv2d dimensions if needed
x = self.mamba_transformer.patch_embed(x)
# Apply Mamba Transformer for global context
x = self.mamba_transformer(x)
return x
# Instantiate Hybrid Model
model = HybridVisionTransformer(
img_size=224, 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,
use_middle_cls_token=True
)
关键点:
CNN Backbone :
使用一个预训练的 ResNet50 提取局部特征。替换CNN的最后一层以获得特征表示。
转换为Transformer输入 :
CNN 特征被简单调整为适合 PatchEmbed 输入的形状。
Mamba Transformer :
将经过 CNN 提取的特征输入到 Mamba Transformer 中,以获得全局的上下文理解。
这种混合特征提取器结合了CNN的局部特征提取优势和Transformer对全局信息建模的能力。