分析:① 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 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
#################################################################
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
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=stride)
self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
def forward(self, x):
B, C, H, W = x.shape
x = self.proj(x)
if self.flatten:
x = x.flatten(2).transpose(1, 2) # BCHW -> BNC
x = self.norm(x)
return x
class Block(nn.Module):
def init(
self, dim, mixer_cls, norm_cls=nn.LayerNorm, fused_add_norm=False, residual_in_fp32=False,drop_path=0.,
):
"""
Simple block wrapping a mixer class with LayerNorm/RMSNorm and residual connection"
This Block has a slightly different structure compared to a regular
prenorm Transformer block.
The standard block is: LN -> MHA/MLP -> Add.
[Ref: https://arxiv.org/abs/2002.04745]
Here we have: Add -> LN -> Mixer, returning both
the hidden_states (output of the mixer) and the residual.
This is purely for performance reasons, as we can fuse add and LayerNorm.
The residual needs to be provided (except for the very first block).
"""
super().__init__()
self.residual_in_fp32 = residual_in_fp32
self.fused_add_norm = fused_add_norm
self.mixer = mixer_cls(dim)
self.norm = norm_cls(dim)
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
if self.fused_add_norm:
assert RMSNorm is not None, "RMSNorm import fails"
assert isinstance(
self.norm, (nn.LayerNorm, RMSNorm)
), "Only LayerNorm and RMSNorm are supported for fused_add_norm"
def forward(
self, hidden_states: Tensor, residual: Optional[Tensor] = None, inference_params=None
):
r"""Pass the input through the encoder layer.
Args:
hidden_states: the sequence to the encoder layer (required).
residual: hidden_states = Mixer(LN(residual))
"""
if not self.fused_add_norm:
if residual is None:
residual = hidden_states
else:
residual = residual + self.drop_path(hidden_states)
hidden_states = self.norm(residual.to(dtype=self.norm.weight.dtype))
if self.residual_in_fp32:
residual = residual.to(torch.float32)
else:
fused_add_norm_fn = rms_norm_fn if isinstance(self.norm, RMSNorm) else layer_norm_fn
if residual is None:
hidden_states, residual = fused_add_norm_fn(
hidden_states,
self.norm.weight,
self.norm.bias,
residual=residual,
prenorm=True,
residual_in_fp32=self.residual_in_fp32,
eps=self.norm.eps,
)
else:
hidden_states, residual = fused_add_norm_fn(
self.drop_path(hidden_states),
self.norm.weight,
self.norm.bias,
residual=residual,
prenorm=True,
residual_in_fp32=self.residual_in_fp32,
eps=self.norm.eps,
)
hidden_states = self.mixer(hidden_states, inference_params=inference_params)
return hidden_states, residual
def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs):
return self.mixer.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs)
def 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)
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)
和 ② """
Basic mamda_fetrack 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.utils.box_ops import box_xyxy_to_cxcywh
from lib.models.mamba_fetrack.models_mamba import create_block
from timm.models import create_model
import torch.nn.functional as F
from lib.models.mamba_fetrack.mamba_cross import CrossMamba
from thop import profile
新增
from .CSMamba import TokenSwapMamba
class Mamba_FEtrack(nn.Module):
""" This is the base class for mamda_fetrack """
def build_mamba_fetrack(cfg, training=True):
current_dir = os.path.dirname(os.path.abspath(file)) # This is your Project Root
pretrained_path = os.path.join(current_dir, 'pretrained_models')
# pretrained_path = os.path.join(current_dir, '../../../pretrained_models')
if cfg.MODEL.PRETRAIN_FILE and ('Mamba_FETrack' not in cfg.MODEL.PRETRAIN_FILE) and training:
pretrained = os.path.join(pretrained_path, cfg.MODEL.PRETRAIN_FILE)
else:
pretrained = ''
backbone = create_model( model_name= cfg.MODEL.BACKBONE.TYPE, pretrained= pretrained, num_classes=1000,
drop_rate=0.0, drop_path_rate=cfg.TRAIN.DROP_PATH_RATE, drop_block_rate=None, img_size=256
)
hidden_dim = 384
cross_mamba = CrossMamba(hidden_dim)
box_head = build_box_head(cfg, hidden_dim*2)
model = Mamba_FEtrack(
backbone,
cross_mamba,
box_head,
aux_loss=False,
head_type=cfg.MODEL.HEAD.TYPE,
)
if 'Mamba_FETrack' 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)
return model
③ import torch
import torch.nn as nn
from mamba_ssm.modules.mamba_simple import Mamba
from einops import rearrange
import numbers
The provided code snippets are part of a deep learning model setup, including a vision transformer-like architecture customized for a tracking task. Here's an overview of the workflow and the specific role of the TokenSwapMamba module:
Overall Workflow
Model Setup:
VisionMamba: This is a vision transformer adapted for a specific task. It includes customized embedding generation and transformer block processing with potential inclusion of rotary positional embeddings (ROPE) and various normalization choices (e.g., LayerNorm, RMSNorm).
Patch Embedding: The image is first split into patches and then embedded into a feature space using a convolutional layer (PatchEmbed).
Block Processing: Each block processes the input sequences through a custom Block which consists of normalization and Mamba-based mixer layers. There are options to use bidirectional processing or include CLS tokens.
Pooling and Output: The final features are pooled and passed to the head for prediction. The forward_features method describes how features are extracted and pooled.
Mamba_FETrack:
Designed to incorporate features from both a template image and a search image for tasks like object tracking.
Processes images through VisionMamba and a swap mechanism using TokenSwapMamba which processes both the main and auxiliary modality (say RGB and event-based vision inputs).
Attends to features across the two modalities with a cross-mamba module CrossMamba.
TokenSwapMamba Module:
Purpose: Enhances feature interaction between two sets of feature maps (e.g., from RGB and event-based modalities).
Process:
Normalization: Normalizes inputs separately using LayerNorm.
Token Swapping: Splits each feature map in half and swaps the halves to create
mixed modality feature maps.
Encoding: Passes the swapped features through Mamba encoders to further process the mixed information.
By preprocessing the inputs with token swapping, the module introduces cross-modality interactions at a lower level before further processing with complex attention mechanisms or mixer layers. This strategy may help the model capture richer representations by explicitly mixing specialized features from different modalities.
TokenSwapMamba in Detail
TokenSwapMamba aims to leverage the complementary information present in different feature representations through a simple, yet effective mechanism:
Input Split and Swap:
It takes two inputs, x1 and x2, each representing features from different sources or modalities.
These features are assumed to be segmented in the channel dimension (i.e., each tensor has a shape of [B, N, C], where C is typically divided between two feature representations).
The first half of x1 channels is swapped with the first half of x2 channels, creating cross-modality feature maps x1_swap and x2_swap.
Encoding and Return:
The swapped feature maps undergo further transformation through individual Mamba encoders, encoder1 and encoder2.
The transformation aims to learn and enhance the interaction between the swapped feature maps.
The integration of TokenSwapMamba in such a network could substantially improve the network's ability to handle input from multimodal sources, potentially increasing robustness and performance for tasks like tracking where the contextual blending of different data modalities is crucial.