The quality of features directly impacts tracking performance. To further enrich feature information, we have introduced a new backbone network to learn the global features of targets. Vision Transformers are adept at capturing long-range dependencies in images and effectively representing the contextual information of images, which is why they are often used as backbone networks. However, their self-attention mechanism results in a computational complexity of (O(n^2)), which is particularly pronounced when handling long sequences. The recently developed Mamba is a new type of state space model designed to address the quadratic complexity issues caused by attention mechanisms, enabling more efficient processing of long sequences. Drawing on the successful experience of Vision Transformers in the field of computer vision, XX and colleagues have designed an efficient and versatile vision backbone network based on the state space model (SMM), known as Vision Mamba (ViM), and have successfully integrated the Mamba approach into image processing tasks.
Similar to Vision Transformer (ViT), Vision Mamba (ViM) processes images as sequences of patches. However, unlike ViT, ViM does not compute multi-head self-attention between these patches. Instead, it performs forward and backward scans on the patches and then merges the results. By scanning image patches in different directions, Mamba enhances its understanding of the image's contextual information. Inspired by ViM, we have stacked multiple Vision Mamba blocks to serve as a global feature extractor, effectively capturing the global context of both RGB and Event modality data.
As illustrated in Figure 2, single-modality template tokens and search tokens are processed through a multi-scale convolutional network to obtain local features. These local feature encodings are then fed into a series of stacked Vision Mamba blocks to extract intra-modality features. Figure 3 provides a detailed view of the Vision Mamba block architecture.
User
在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.mamba_fetrack.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
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=stride)
self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
def forward(self, x):
B, C, H, W = x.shape
x = self.proj(x)
if self.flatten:
x = x.flatten(2).transpose(1, 2) # BCHW -> BNC
x = self.norm(x)
return x
class Block(nn.Module):
def init(
self, dim, mixer_cls, norm_cls=nn.LayerNorm, fused_add_norm=False, residual_in_fp32=False,drop_path=0., integrate_glu=False
):
"""
Simple block wrapping a mixer class with LayerNorm/RMSNorm and residual connection"
Assistant
To integrate the ResGLUAdapter in both the first and second layers, you can modify how create_block is called within the VisionMamba class. Specifically, change the integrate_glu parameter for both the first and second blocks in the self.layers module list. Here is how you can do it:
python
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,
# Modify the condition to integrate ResGLUAdapter in the first and second blocks
integrate_glu=(i == 0 or i == 1),
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)
]
)
This line integrate_glu=(i == 0 or i == 1) ensures that the ResGLUAdapter is integrated into both the first and second layers. The rest of the architecture remains unchanged.
User
这样的修改,是在单层集成还是集成了两层?
Assistant
The modification integrate_glu=(i == 0 or i == 1) integrates the ResGLUAdapter into the first two layers of the network. Here's how it works:
The condition i == 0 or i == 1 checks if the current layer index i is either 0 or 1.
For i == 0 (the first layer) and i == 1 (the second layer), integrate_glu will evaluate to True, thus integrating the ResGLUAdapter into these layers.
For other layers (i.e., i >= 2), integrate_glu will evaluate to False, and the ResGLUAdapter will not be integrated.
Thus, this change will result in ResGLUAdapter being integrated into two layers of the network, specifically the first and second layers.
User
中文回答
Assistant
这样的修改是在网络的前两层中集成了 ResGLUAdapter。具体来说:
条件 i == 0 or i == 1 会检查当前层的索引 i 是否是 0 或 1。
当 i == 0(第一层)或 i == 1(第二层)时,integrate_glu 的值为 True,因此会在这两层中集成 ResGLUAdapter。
对于其他层(即 i >= 2),integrate_glu 的值为 False,因此在这些层不会集成 ResGLUAdapter。
I used \begin{aligned}...\end{aligned} within the equation environment to align related equations, making them more readable.
\mathrm{...} is used for operators and functions to maintain consistency in formatting.
Subscript notations such as \text{fore} and \text{back} are used to clarify the meaning without altering the mathematical representation.
Dataset releases
Not yet included in a published release.
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"
# 引入门控机制
model_args = ModelArgs()
# self.glu_adapter = GLUAdapter(model_args)
# 如果需要集成 ResGLUAdapter,则初始化
if integrate_glu:
model_args = ModelArgs()
self.glu_adapter = ResGLUAdapter(model_args)
else:
self.glu_adapter = None
# self.glu_adapter = ResGLUAdapter(model_args)
def forward(
self, hidden_states: Tensor, residual: Optional[Tensor] = None, inference_params=None
):
r"""Pass the input through the encoder layer.
Args:
hidden_states: the sequence to the encoder layer (required).
residual: hidden_states = Mixer(LN(residual))
"""
if not self.fused_add_norm:
if residual is None:
residual = hidden_states
else:
residual = residual + self.drop_path(hidden_states)
hidden_states = self.norm(residual.to(dtype=self.norm.weight.dtype))
if self.residual_in_fp32:
residual = residual.to(torch.float32)
else:
fused_add_norm_fn = rms_norm_fn if isinstance(self.norm, RMSNorm) else layer_norm_fn
if residual is None:
hidden_states, residual = fused_add_norm_fn(
hidden_states,
self.norm.weight,
self.norm.bias,
residual=residual,
prenorm=True,
residual_in_fp32=self.residual_in_fp32,
eps=self.norm.eps,
)
else:
hidden_states, residual = fused_add_norm_fn(
self.drop_path(hidden_states),
self.norm.weight,
self.norm.bias,
residual=residual,
prenorm=True,
residual_in_fp32=self.residual_in_fp32,
eps=self.norm.eps,
)
hidden_states = self.mixer(hidden_states, inference_params=inference_params)
# 增加门控机制, 消除冗余和不相关的特征,保留最具表现力的输出
if self.glu_adapter is not None:
hidden_states = self.glu_adapter(hidden_states)
# hidden_states = self.glu_adapter(hidden_states)
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 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
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)