####################################### 等同于 vit_ce #############################
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
#################################################################
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',
]
def forward(self, x):
B, C, H, W = x.shape
# assert H == self.img_size[0] and W == self.img_size[1], \
# f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
x = self.proj(x) # 将图像切分为小方块,尺寸就是patch_size
# 切块之后,维度: batch_size, embedding_dim, grid_size, grid_size
# 原始 (B,C,H,W)--> (B,N,grid_size,grid_size)
if self.flatten: # 将小方块拉平,构成序列
# 展平操作:batch_size, embedding_dim, num_patches
x = x.flatten(2).transpose(1, 2) # BCHW -> BNC
x = self.norm(x)
return x
定义mamba的encoder模块
class Block(nn.Module):
def init(
self, dim, mixer_cls, norm_cls=nn.LayerNorm, fused_add_norm=False, residual_in_fp32=False,drop_path=0.,
):
"""
Simple block wrapping a mixer class with LayerNorm/RMSNorm and residual connection"
code
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)
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)
The provided script appears to be part of a machine learning project involving vision transformers, specifically models akin to the Vision Transformer (ViT) architecture. It seems to be implementing variations of a model referred to as "VisionMamba" using torch (PyTorch) and based on, or inspired by, the Mamba architecture. Here's a breakdown of the key components and what they imply:
Key Features:
Vision Transformer Basics:
The script derives from the Vision Transformer (ViT) model, utilizing image patching, which breaks an image into smaller patches that are then processed similarly to tokens in a Transformer model.
Patch Embedding:
The PatchEmbed class transforms the input image into patches using a convolutional layer (nn.Conv2d). This results in a flat sequence that resembles tokenized inputs for a transformer.
Vision Mamba Model:
The core class VisionMamba implements a vision transformer-like model. It supports variations in patch sizes, stride, layer depth, and includes functionalities such as residual connections, LayerNorm, RMSNorm, and potentially other normalizations.
The model encompasses functionalities for applying absolute positional embeddings, and an option for "Rope" (presumably some form of rotation positional encoding), enhancing the model's ability to capture spatial dependencies.
Transformer Blocks:
Block and create_block define how each transformer layer handles attentions and residuals. The use of Mamba implies a specific type of mixer/method for information flow within these blocks.
Parameters and Configuration:
The model configurations, such as embed_dim, depth, use of rms_norm, or fused_add_norm, guide how network layers are constructed and initialized.
segm_init_weights and _init_weights ensure proper initialization of weights in the network layers to stabilize training.
Customizable Functions:
The forward_features method allows customization of the model's forward pass, especially in how CLS tokens are handled, whether using middle insertion, random positions, etc.
基于上文代码,"""
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
class Mamba_FEtrack(nn.Module):
""" This is the base class for mamda_fetrack """
import torch
import torch.nn as nn
from torchvision.models import resnet18
from timm.models import create_model
class HybridModel(nn.Module):
def __init__(self, visionmamba_cfg, pretrained_resnet=True):
super(HybridModel, self).__init__()
# Load ResNet18 and remove the final classification layer
self.resnet = resnet18(pretrained=pretrained_resnet)
self.resnet = nn.Sequential(*list(self.resnet.children())[:-2]) # Remove avgpool and fc layer
# Load VisionMamba or similar model
self.visionmamba = create_model(**visionmamba_cfg)
# Potential adapter to match dimensions
# For example, you might need a linear layer to transform the ResNet features to embedding dimension
self.adapt_layer = nn.Linear(512, self.visionmamba.embed_dim)
def forward(self, x):
# Extract local features using ResNet
x = self.resnet(x)
# [B, C, H, W] -> [B, H*W, C], flatten the feature map
B, C, H, W = x.shape
x = x.view(B, C, H * W).permute(0, 2, 1)
# Adapt the features to the input dimension of VisionMamba
x = self.adapt_layer(x)
# Extract global features using VisionMamba
x = self.visionmamba(x)
return x
# Example configuration for timm Vision Transformer
visionmamba_cfg = {
'model_name': 'vit_base_patch16_224',
'pretrained': True,
'num_classes': 1000
}
model = HybridModel(visionmamba_cfg)
####################################### 等同于 vit_ce #############################
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
#################################################################
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',
]
import torch
import torch.nn as nn
from torchvision.models import resnet18
from timm.models.registry import register_model
class HybridResNetVisionMamba(nn.Module):
def __init__(self, visionmamba_cfg, resnet_layers=18, pretrained_resnet=True):
super(HybridResNetVisionMamba, self).__init__()
# 1. Load ResNet and remove the final fully connected layer.
if resnet_layers == 18:
self.resnet = resnet18(pretrained=pretrained_resnet)
else:
raise NotImplementedError("Only ResNet18 is supported in this example.")
# Remove the average pool and the final fully connected layer
self.resnet = nn.Sequential(*list(self.resnet.children())[:-2]) # B, 512, H/32, W/32
# 2. Load VisionMamba or a similar Vision Transformer model.
self.visionmamba = VisionMamba(**visionmamba_cfg)
# 3. Potential adapter to match dimensions (e.g., ResNet output C=512 to VisionMamba embed_dim)
self.adapter = nn.Linear(512, self.visionmamba.embed_dim)
def forward(self, x):
# 4. Extract local features using ResNet
x = self.resnet(x) # [B, 512, H', W']
# Flatten the feature map and adapt to VisionMamba's input dimensions
B, C, H, W = x.shape
x = x.view(B, C, H * W).permute(0, 2, 1) # (B, H*W, C)
x = self.adapter(x) # (B, H*W, embed_dim)
# 5. Extract global features using VisionMamba
x = self.visionmamba.forward_features(x, x)
return x
# Configuration for VisionMamba
visionmamba_cfg = {
'img_size': 224,
'patch_size': 16,
'stride': 16,
'depth': 24,
'embed_dim': 192,
'rms_norm': True,
'fused_add_norm': True,
'final_pool_type': 'mean',
'if_abs_pos_embed': True,
}
# Instantiate the hybrid model
model = HybridResNetVisionMamba(visionmamba_cfg)
# Example registration
@register_model
def hybrid_resnet_visionmamba(pretrained=False, **kwargs):
model = HybridResNetVisionMamba(kwargs)
if pretrained:
# Load pretrained weights if available.
pass
return model
User
在# Copyright (c) 2015-present, Facebook, Inc.
All rights reserved.
####################################### 等同于 vit_ce #############################
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
#################################################################
try:
from mamba_ssm.ops.triton.layernorm import RMSNorm, layer_norm_fn, rms_norm_fn
except ImportError:
RMSNorm, layer_norm_fn, rms_norm_fn = None, None, None
################ 增加 Resnet网络导入 ########################
from torchvision.models import resnet18
from timm.models.registry import register_model
####################
all = [
'vim_tiny_patch16_224', 'vim_small_patch16_224', 'vim_base_patch16_224',
'vim_tiny_patch16_384', 'vim_small_patch16_384', 'vim_base_patch16_384',
]
根据上文中集成了resnet之后的特征提取网络,那么在"""
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
class Mamba_FEtrack(nn.Module):
""" This is the base class for mamda_fetrack """
按照上述代码修改,报错:resnet_x.shape: torch.Size([4, 512])
resnet_z.shape: torch.Size([4, 512])
Training crashed at epoch 1
Traceback for the error!
Traceback (most recent call last):
File "/data2/local_userdata/heyuting/Mamba/FETrack/Mamba_FETrack/lib/train/../../lib/train/trainers/base_trainer.py", line 85, in train
self.train_epoch()
File "/data2/local_userdata/heyuting/Mamba/FETrack/Mamba_FETrack/lib/train/../../lib/train/trainers/ltr_trainer.py", line 133, in train_epoch
self.cycle_dataset(loader)
File "/data2/local_userdata/heyuting/Mamba/FETrack/Mamba_FETrack/lib/train/../../lib/train/trainers/ltr_trainer.py", line 86, in cycle_dataset
loss, stats = self.actor(data)
File "/data2/local_userdata/heyuting/Mamba/FETrack/Mamba_FETrack/lib/train/../../lib/train/actors/mamba_fetrack.py", line 31, in call
out_dict = self.forward_pass(data)
File "/data2/local_userdata/heyuting/Mamba/FETrack/Mamba_FETrack/lib/train/../../lib/train/actors/mamba_fetrack.py", line 74, in forward_pass
out_dict = self.net(template=template_list,
File "/home/heyuting/anaconda3/envs/mamba/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1518, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/home/heyuting/anaconda3/envs/mamba/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1527, in _call_impl
return forward_call(*args, **kwargs)
File "/data2/local_userdata/heyuting/Mamba/FETrack/Mamba_FETrack/lib/train/../../lib/models/mamba_fetrack/mamba_fetrack.py", line 54, in forward
rgb_feature = self.backbone.forward_features( z=template, x=search, #[B, 320, 384]
File "/data2/local_userdata/heyuting/Mamba/FETrack/Mamba_FETrack/lib/train/../../lib/models/mamba_fetrack/models_mamba.py", line 409, in forward_features
B,C,H,W = x.shape
ValueError: not enough values to unpack (expected 4, got 2)
Restarting training from last epoch ...
Finished training!
Assistant
错误信息指出在从增强后的 VisionMambaResNet 获取特征时发生了问题,具体是因为在forward_features函数中尝试解包 x 和 z 的形状时,得到的张量只有两个维度而不是期望的四个维度。这表明在 resnet 特征提取之后,特征图已经被降维到一个稠密的向量,而不是四维的特征图。
现在报错:No matching checkpoint file found
resnet_x.shape: torch.Size([4, 512, 8, 8])
resnet_z.shape: torch.Size([4, 512, 4, 4])
Training crashed at epoch 1
Traceback for the error!
Traceback (most recent call last):
File "/data2/local_userdata/heyuting/Mamba/FETrack/Mamba_FETrack/lib/train/../../lib/train/trainers/base_trainer.py", line 85, in train
self.train_epoch()
File "/data2/local_userdata/heyuting/Mamba/FETrack/Mamba_FETrack/lib/train/../../lib/train/trainers/ltr_trainer.py", line 133, in train_epoch
self.cycle_dataset(loader)
File "/data2/local_userdata/heyuting/Mamba/FETrack/Mamba_FETrack/lib/train/../../lib/train/trainers/ltr_trainer.py", line 86, in cycle_dataset
loss, stats = self.actor(data)
File "/data2/local_userdata/heyuting/Mamba/FETrack/Mamba_FETrack/lib/train/../../lib/train/actors/mamba_fetrack.py", line 31, in call
out_dict = self.forward_pass(data)
File "/data2/local_userdata/heyuting/Mamba/FETrack/Mamba_FETrack/lib/train/../../lib/train/actors/mamba_fetrack.py", line 74, in forward_pass
out_dict = self.net(template=template_list,
File "/home/heyuting/anaconda3/envs/mamba/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1518, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/home/heyuting/anaconda3/envs/mamba/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1527, in _call_impl
return forward_call(args, **kwargs)
File "/data2/local_userdata/heyuting/Mamba/FETrack/Mamba_FETrack/lib/train/../../lib/models/mamba_fetrack/mamba_fetrack.py", line 54, in forward
rgb_feature = self.backbone.forward_features( z=template, x=search, #[B, 320, 384]
File "/data2/local_userdata/heyuting/Mamba/FETrack/Mamba_FETrack/lib/train/../../lib/models/mamba_fetrack/models_mamba.py", line 411, in forward_features
x = x.view(B,C,HW).premute(0,2,1)
AttributeError: 'Tensor' object has no attribute 'premute'
Restarting training from last epoch ...
Finished training!
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 = ''
####################################### 等同于 vit_ce #############################
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
ResNet 18 import
from torchvision.models import resnet18
###########
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
#################################################################
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',
]
报错:sampler_mode causal
Traceback (most recent call last):
File "/data2/local_userdata/heyuting/Mamba/FETrack/Mamba_FETrack/lib/train/run_training.py", line 110, in
main()
File "/data2/local_userdata/heyuting/Mamba/FETrack/Mamba_FETrack/lib/train/run_training.py", line 101, in main
run_training(args.script, args.config, cudnn_benchmark=args.cudnn_benchmark,
File "/data2/local_userdata/heyuting/Mamba/FETrack/Mamba_FETrack/lib/train/run_training.py", line 75, in run_training
expr_func(settings)
File "/data2/local_userdata/heyuting/Mamba/FETrack/Mamba_FETrack/lib/train/../../lib/train/train_script.py", line 56, in run
net = build_mamba_fetrack(cfg)
File "/data2/local_userdata/heyuting/Mamba/FETrack/Mamba_FETrack/lib/train/../../lib/models/mamba_fetrack/mamba_fetrack.py", line 124, in build_mamba_fetrack
backbone = create_model( model_name= cfg.MODEL.BACKBONE.TYPE, pretrained= pretrained, num_classes=1000,
File "/home/heyuting/anaconda3/envs/mamba/lib/python3.10/site-packages/timm/models/factory.py", line 81, in create_model
model = create_fn(pretrained=pretrained, **kwargs)
File "/data2/local_userdata/heyuting/Mamba/FETrack/Mamba_FETrack/lib/train/../../lib/models/mamba_fetrack/models_mamba.py", line 639, in vim_small_patch16_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2
missing_keys, unexpected_keys = model.load_state_dict(checkpoint["model"], strict=False)
File "/home/heyuting/anaconda3/envs/mamba/lib/python3.10/site-packages/torch/nn/modules/module.py", line 2152, in load_state_dict
raise RuntimeError('Error(s) in loading state_dict for {}:\n\t{}'.format(
RuntimeError: Error(s) in loading state_dict for VisionMamba:
size mismatch for patch_embed.proj.weight: copying a param with shape torch.Size([384, 3, 16, 16]) from checkpoint, the shape in current model is torch.Size([384, 512, 16, 16]).
# 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: # 使用该模式,cls_tokens拼接在头和尾
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:
# pos_embed是加在(cls_tokens和num_patches)总体上的。
# self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + self.num_tokens, self.embed_dim))
# 此处与mamba不同,划分了x和z的位置编码
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_drop = nn.Dropout(p=drop_rate) # 随机失活,增强鲁棒性
# 是否对position_embedding进行增强
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
)
# 此处将head去掉了。
# self.head = nn.Linear(self.num_features, num_classes) if num_classes > 0 else nn.Identity()
# settings = ws_settings.Settings()
# config_module = importlib.import_module("lib.config.%s.config" % settings.script_name)
# cfg = config_module.cfg
# self.head = build_box_head(cfg, embed_dim)
# TODO: release this comment
# drop path rate ,随机失活
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)
# 此处与mamba不同,问题在于没有执行head相关操作
# self.head.apply(segm_init_weights)
# 在pos_embed中也进行了模板和搜索的划分
if if_abs_pos_embed:
# trunc_normal_:保证权重范围落在正态分布之间,加快收敛速度
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):
# taken from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
# with slight modifications to add the dist_token
# 1)将输入 X 切成小方块
# 将输入 Z 切成小方块
# print('x.shape:',x.shape) # x.shape: torch.Size([4, 3, 256, 256])
# print('z.shape:',z.shape) # x.shape: torch.Size([4, 3, 256, 256])
x = self.patch_embed(x) #x.shape = torch.Size([B, 3, 256, 256]) -> torch.Size([2, 256, 384])
z = self.patch_embed(z) #z.shape = torch.Size([B, 3, 128, 128]) -> torch.Size([2, 64, 384])
# 输出切块之后的大小, M表示切块之后的大小,B表示batch_size
B, M, _ = x.shape
if self.if_cls_token: # False
if self.use_double_cls_token:
cls_token_head = self.cls_token_head.expand(B, -1, -1)
cls_token_tail = self.cls_token_tail.expand(B, -1, -1)
token_position = [0, M + 1]
x = torch.cat((cls_token_head, x, cls_token_tail), dim=1)
M = x.shape[1]
else:
if self.use_middle_cls_token:
cls_token = self.cls_token.expand(B, -1, -1)
token_position = M // 2 # 中间位置
# add cls token in the middle
x = torch.cat((x[:, :token_position, :], cls_token, x[:, token_position:, :]), dim=1)
elif if_random_cls_token_position: # (随机位置)
cls_token = self.cls_token.expand(B, -1, -1)
token_position = random.randint(0, M)
x = torch.cat((x[:, :token_position, :], cls_token, x[:, token_position:, :]), dim=1)
print("token_position: ", token_position)
else:
cls_token = self.cls_token.expand(B, -1, -1) # stole cls_tokens impl from Phil Wang, thanks
token_position = 0 # 头插
x = torch.cat((cls_token, x), dim=1)
M = x.shape[1] # 对M进行更新
# 此处由于划分了模板和搜索,pos_embed也需要单独执行
# 上文中将patches和CLS_Tokens拼接上,然后现在将pos_embed拼接
if self.if_abs_pos_embed: # True
x = x + self.pos_embed_x # x = x + positon_embemding =torch.Size([B, 256, 384]) + torch.Size([1, 256, 384]) = torch.Size([B, 256, 384])
z = z + self.pos_embed_z # z = z + positon_embemding =torch.Size([B, 64, 384]) + torch.Size([1, 64, 384]) = torch.Size([B, 64, 384])
# 这里是将patches和pos_embed拼接上之后再进行模板特征和搜索特征的拼接
x = torch.cat((z, x), dim=1) # torch.Size([B, 320, 384])
x = self.pos_drop(x) # x.shape = torch.Size([B, 320, 384])
# 如果采用的随机序列生成索引
# 就需要采用shuffle_indices来重新生成索引
if if_random_token_rank: #False
# 生成随机 shuffle 索引
shuffle_indices = torch.randperm(M) # 生成随机数
# 随机的情况需要打印出来看看
if isinstance(token_position, list):
print("original value: ", x[0, token_position[0], 0], x[0, token_position[1], 0])
else:
print("original value: ", x[0, token_position, 0])
print("original token_position: ", token_position)
# 执行 shuffle 打乱顺序
x = x[:, shuffle_indices, :]
if isinstance(token_position, list):
# 找到 cls token 在 shuffle 之后的新位置
new_token_position = [torch.where(shuffle_indices == token_position[i])[0].item() for i in range(len(token_position))]
token_position = new_token_position
else:
# 找到 cls token 在 shuffle 之后的新位置
token_position = torch.where(shuffle_indices == token_position)[0].item()
if isinstance(token_position, list):
print("new value: ", x[0, token_position[0], 0], x[0, token_position[1], 0])
else:
print("new value: ", x[0, token_position, 0])
print("new token_position: ", token_position)
# 反转操作
if_flip_img_sequences = False
if self.flip_img_sequences_ratio > 0 and (self.flip_img_sequences_ratio - random.random()) > 1e-5: # False
x = x.flip([1])
if_flip_img_sequences = True
# mamba impl
residual = None
hidden_states = x
# 非双向操作
if not self.if_bidirectional: # True
for layer in self.layers:
if if_flip_img_sequences and self.if_rope: # False
hidden_states = hidden_states.flip([1])
if residual is not None:
residual = residual.flip([1])
# rope about
if self.if_rope: # False
hidden_states = self.rope(hidden_states)
if residual is not None and self.if_rope_residual:
residual = self.rope(residual)
if if_flip_img_sequences and self.if_rope: # False
hidden_states = hidden_states.flip([1])
if residual is not None:
residual = residual.flip([1])
hidden_states, residual = layer(
hidden_states, residual, inference_params=inference_params
)
# 双向传播 (一个forward,一个backward)
else: # False
# get two layers in a single for-loop
for i in range(len(self.layers) // 2):
if self.if_rope:
hidden_states = self.rope(hidden_states)
if residual is not None and self.if_rope_residual:
residual = self.rope(residual)
# 前向传播结果 hidden_states_f;前向传播的残差 residual_f
# Forward_SSM (前向传播计算的是偶数 i * 2 层)
hidden_states_f, residual_f = self.layers[i * 2](
hidden_states, residual, inference_params=inference_params
)
# 后向传播(所以后向传播时,应该计算奇数 即 i * 2 + 1)
hidden_states_b, residual_b = self.layers[i * 2 + 1](
hidden_states.flip([1]), None if residual == None else residual.flip([1]), inference_params=inference_params
)
# 因为有一个前向和一个后向,所以需要将两者相加
# 训练时,后向传播采取了翻转,所以现在相加时应该将其翻转回来
hidden_states = hidden_states_f + hidden_states_b.flip([1])
residual = residual_f + residual_b.flip([1])
if not self.fused_add_norm: #False
if residual is None:
residual = hidden_states
else:
residual = residual + self.drop_path(hidden_states)
hidden_states = self.norm_f(residual.to(dtype=self.norm_f.weight.dtype))
else: #True
# 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([B, 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 only cls token if it exists
if self.if_cls_token: #False
if self.use_double_cls_token:
return (hidden_states[:, token_position[0], :] + hidden_states[:, token_position[1], :]) / 2
else:
if self.use_middle_cls_token:
return hidden_states[:, token_position, :]
elif if_random_cls_token_position:
return hidden_states[:, token_position, :]
else:
return hidden_states[:, token_position, :]
# 最后池化操作
# 进入MLP时,VisionMamba的输出是hidden_states.shape = torch.Size([2, 320, 384]) → Batch_size, num_patches, embedding_dim
# MLP接受2个维度,所以需要采用池化的方法对Vmamba的输出进行处理
# hidden_states[:, -1, :] = torch.Size([2, 384])
if self.final_pool_type == 'none':
return hidden_states[:, -1, :]
elif self.final_pool_type == 'mean': #True
return hidden_states.mean(dim=1) #hidden_states.shape = torch.Size([2, 384])
elif self.final_pool_type == 'max':
return hidden_states
elif self.final_pool_type == 'all':
return hidden_states
else:
raise NotImplementedError
# 整个前向传播过程
def forward(self, x, return_features=False, inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False):
x = self.forward_features(x, inference_params, if_random_cls_token_position=if_random_cls_token_position, if_random_token_rank=if_random_token_rank)
print('x.shape:',x.shape)
if return_features:
return x #此处返回mamba_encoder的特征
x = self.head(x)
if self.final_pool_type == 'max':
x = x.max(dim=1)[0]
return x
Functions like vim_small_patch16_224_bimambav2_final_pool_mean_abs_pos_embed_with_midclstok_div2 register different configurations of the model with specific architectural changes like patch sizes, using library functions like register_model.
Compatibility with Pretrained Models:
Includes mechanisms to load pretrained weights, enhancing training speed and model performance through transfer learning.
This script provides a flexible foundation for experimenting with different configurations of Vision Transformers, potentially in vision-related tasks such as image classification, detection, or segmentation. The references to mamba, bimamba, and methods for forward and backward processing hint towards optimizations or custom adaptations for specific tasks or performance improvements.
def __init__(self, visionmamba, cross_mamba, 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.cross_mamba= cross_mamba
self.box_head = box_head
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_len_s = int(box_head.feat_sz ** 2)
if self.aux_loss:
self.box_head = _get_clones(self.box_head, 6)
def forward(self, template: torch.Tensor,
search: torch.Tensor,
event_template: torch.Tensor,
event_search: torch.Tensor,
ce_template_mask=None,
ce_keep_rate=None,
return_last_attn=False,
):
# print('tempalte.shape: ', template.shape) # tempalte.shape: torch.Size([4, 3, 128, 128])
# print('search.shape: ', search.shape) # search.shape: torch.Size([4, 3, 256, 256])
rgb_feature = self.backbone.forward_features( z=template, x=search, #[B, 320, 384]
inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False)
# print('rgb_features.shape: ', rgb_feature.shape) # (batch_size, 320, 384)
event_feature = self.backbone.forward_features(z=event_template, x=event_search, #[B, 320, 384]
inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False)
# print('event_features.shape: ', event_feature.shape) # (batch_size, 320, 384)
residual_event_f = 0
residual_rgb_f = 0
event_f = self.cross_mamba(event_feature,residual_event_f,rgb_feature) + event_feature # 并未改变维度 torch.Size([4, 320, 384])
rgb_f = self.cross_mamba(rgb_feature,residual_rgb_f,event_feature) + rgb_feature
# print(self.feat_len_s) # 256
event_searh = event_f[:, -self.feat_len_s:]
rgb_search = rgb_f[:, -self.feat_len_s:]
# print('event_search.shape: ', event_searh.shape) # event_search.shape: torch.Size([4, 256, 384])
# print('rgb_search.shape: ', rgb_search.shape) # rgb_search.shape: torch.Size([4, 256, 384])
x = torch.cat((event_searh,rgb_search),dim=-1) # x.shape: torch.Size([4, 256, 768])
# print('x.shape: ', x.shape)
# Forward head
feat_last = x
if isinstance(x, list):
feat_last = x[-1]
out = self.forward_head(feat_last, None)
out['backbone_feat'] = x
return out
def forward_head(self, cat_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 = cat_feature
opt = (search_feature.unsqueeze(-1)).permute((0, 3, 2, 1)).contiguous() # opt.shape = torch.Size([B, 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([B, 384, 16, 16])
if self.head_type == "CORNER":
# run the corner head
pred_box, score_map = self.box_head(opt_feat, True)
outputs_coord = box_xyxy_to_cxcywh(pred_box)
outputs_coord_new = outputs_coord.view(bs, Nq, 4)
out = {'pred_boxes': outputs_coord_new,
'score_map': score_map,
}
return out
elif self.head_type == "CENTER":
# run the center head
score_map_ctr, bbox, size_map, offset_map = self.box_head(opt_feat, gt_score_map)
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}
return out
else:
raise NotImplementedError
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 = ''
code
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
if self.if_cls_token: # False
if self.use_double_cls_token:
cls_token_head = self.cls_token_head.expand(B, -1, -1)
cls_token_tail = self.cls_token_tail.expand(B, -1, -1)
token_position = [0, M + 1]
x = torch.cat((cls_token_head, x, cls_token_tail), dim=1)
M = x.shape[1]
else:
if self.use_middle_cls_token:
cls_token = self.cls_token.expand(B, -1, -1)
token_position = M // 2 # 中间位置
# add cls token in the middle
x = torch.cat((x[:, :token_position, :], cls_token, x[:, token_position:, :]), dim=1)
elif if_random_cls_token_position: # (随机位置)
cls_token = self.cls_token.expand(B, -1, -1)
token_position = random.randint(0, M)
x = torch.cat((x[:, :token_position, :], cls_token, x[:, token_position:, :]), dim=1)
print("token_position: ", token_position)
else:
cls_token = self.cls_token.expand(B, -1, -1) # stole cls_tokens impl from Phil Wang, thanks
token_position = 0 # 头插
x = torch.cat((cls_token, x), dim=1)
M = x.shape[1] # 对M进行更新
# 此处由于划分了模板和搜索,pos_embed也需要单独执行
# 上文中将patches和CLS_Tokens拼接上,然后现在将pos_embed拼接
if self.if_abs_pos_embed: # True
x = x + self.pos_embed_x # x = x + positon_embemding =torch.Size([B, 256, 384]) + torch.Size([1, 256, 384]) = torch.Size([B, 256, 384])
z = z + self.pos_embed_z # z = z + positon_embemding =torch.Size([B, 64, 384]) + torch.Size([1, 64, 384]) = torch.Size([B, 64, 384])
# 这里是将patches和pos_embed拼接上之后再进行模板特征和搜索特征的拼接
x = torch.cat((z, x), dim=1) # torch.Size([B, 320, 384])
x = self.pos_drop(x) # x.shape = torch.Size([B, 320, 384])
# 如果采用的随机序列生成索引
# 就需要采用shuffle_indices来重新生成索引
if if_random_token_rank: #False
# 生成随机 shuffle 索引
shuffle_indices = torch.randperm(M) # 生成随机数
# 随机的情况需要打印出来看看
if isinstance(token_position, list):
print("original value: ", x[0, token_position[0], 0], x[0, token_position[1], 0])
else:
print("original value: ", x[0, token_position, 0])
print("original token_position: ", token_position)
# 执行 shuffle 打乱顺序
x = x[:, shuffle_indices, :]
if isinstance(token_position, list):
# 找到 cls token 在 shuffle 之后的新位置
new_token_position = [torch.where(shuffle_indices == token_position[i])[0].item() for i in range(len(token_position))]
token_position = new_token_position
else:
# 找到 cls token 在 shuffle 之后的新位置
token_position = torch.where(shuffle_indices == token_position)[0].item()
if isinstance(token_position, list):
print("new value: ", x[0, token_position[0], 0], x[0, token_position[1], 0])
else:
print("new value: ", x[0, token_position, 0])
print("new token_position: ", token_position)
# 反转操作
if_flip_img_sequences = False
if self.flip_img_sequences_ratio > 0 and (self.flip_img_sequences_ratio - random.random()) > 1e-5: # False
x = x.flip([1])
if_flip_img_sequences = True
# mamba impl
residual = None
hidden_states = x
# 非双向操作
if not self.if_bidirectional: # True
for layer in self.layers:
if if_flip_img_sequences and self.if_rope: # False
hidden_states = hidden_states.flip([1])
if residual is not None:
residual = residual.flip([1])
# rope about
if self.if_rope: # False
hidden_states = self.rope(hidden_states)
if residual is not None and self.if_rope_residual:
residual = self.rope(residual)
if if_flip_img_sequences and self.if_rope: # False
hidden_states = hidden_states.flip([1])
if residual is not None:
residual = residual.flip([1])
hidden_states, residual = layer(
hidden_states, residual, inference_params=inference_params
)
# 双向传播 (一个forward,一个backward)
else: # False
# get two layers in a single for-loop
for i in range(len(self.layers) // 2):
if self.if_rope:
hidden_states = self.rope(hidden_states)
if residual is not None and self.if_rope_residual:
residual = self.rope(residual)
# 前向传播结果 hidden_states_f;前向传播的残差 residual_f
# Forward_SSM (前向传播计算的是偶数 i * 2 层)
hidden_states_f, residual_f = self.layers[i * 2](
hidden_states, residual, inference_params=inference_params
)
# 后向传播(所以后向传播时,应该计算奇数 即 i * 2 + 1)
hidden_states_b, residual_b = self.layers[i * 2 + 1](
hidden_states.flip([1]), None if residual == None else residual.flip([1]), inference_params=inference_params
)
# 因为有一个前向和一个后向,所以需要将两者相加
# 训练时,后向传播采取了翻转,所以现在相加时应该将其翻转回来
hidden_states = hidden_states_f + hidden_states_b.flip([1])
residual = residual_f + residual_b.flip([1])
if not self.fused_add_norm: #False
if residual is None:
residual = hidden_states
else:
residual = residual + self.drop_path(hidden_states)
hidden_states = self.norm_f(residual.to(dtype=self.norm_f.weight.dtype))
else: #True
# 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([B, 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 only cls token if it exists
if self.if_cls_token: #False
if self.use_double_cls_token:
return (hidden_states[:, token_position[0], :] + hidden_states[:, token_position[1], :]) / 2
else:
if self.use_middle_cls_token:
return hidden_states[:, token_position, :]
elif if_random_cls_token_position:
return hidden_states[:, token_position, :]
else:
return hidden_states[:, token_position, :]
# 最后池化操作
# 进入MLP时,VisionMamba的输出是hidden_states.shape = torch.Size([2, 320, 384]) → Batch_size, num_patches, embedding_dim
# MLP接受2个维度,所以需要采用池化的方法对Vmamba的输出进行处理
# hidden_states[:, -1, :] = torch.Size([2, 384])
if self.final_pool_type == 'none':
return hidden_states[:, -1, :]
elif self.final_pool_type == 'mean': #True
return hidden_states.mean(dim=1) #hidden_states.shape = torch.Size([2, 384])
elif self.final_pool_type == 'max':
return hidden_states
elif self.final_pool_type == 'all':
return hidden_states
else:
raise NotImplementedError部分
定义mamba的encoder模块
class Block(nn.Module):
def init(
self, dim, mixer_cls, norm_cls=nn.LayerNorm, fused_add_norm=False, residual_in_fp32=False,drop_path=0.,
):
"""
Simple block wrapping a mixer class with LayerNorm/RMSNorm and residual connection"
code
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)
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)
def forward(self, x):
B, C, H, W = x.shape
# assert H == self.img_size[0] and W == self.img_size[1], \
# f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
x = self.proj(x) # 将图像切分为小方块,尺寸就是patch_size
# 切块之后,维度: batch_size, embedding_dim, grid_size, grid_size
# 原始 (B,C,H,W)--> (B,N,grid_size,grid_size)
if self.flatten: # 将小方块拉平,构成序列
# 展平操作:batch_size, embedding_dim, num_patches
x = x.flatten(2).transpose(1, 2) # BCHW -> BNC
x = self.norm(x)
return x
定义mamba的encoder模块
class Block(nn.Module):
def init(
self, dim, mixer_cls, norm_cls=nn.LayerNorm, fused_add_norm=False, residual_in_fp32=False,drop_path=0.,
):
"""
Simple block wrapping a mixer class with LayerNorm/RMSNorm and residual connection"
code
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)
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)
def __init__(self, visionmamba, cross_mamba, 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.cross_mamba= cross_mamba
self.box_head = box_head
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_len_s = int(box_head.feat_sz ** 2)
if self.aux_loss:
self.box_head = _get_clones(self.box_head, 6)
def forward(self, template: torch.Tensor,
search: torch.Tensor,
event_template: torch.Tensor,
event_search: torch.Tensor,
ce_template_mask=None,
ce_keep_rate=None,
return_last_attn=False,
):
# print('tempalte.shape: ', template.shape) # tempalte.shape: torch.Size([4, 3, 128, 128])
# print('search.shape: ', search.shape) # search.shape: torch.Size([4, 3, 256, 256])
rgb_feature = self.backbone.forward_features( z=template, x=search, #[B, 320, 384]
inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False)
# print('rgb_features.shape: ', rgb_feature.shape) # (batch_size, 320, 384)
event_feature = self.backbone.forward_features(z=event_template, x=event_search, #[B, 320, 384]
inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False)
# print('event_features.shape: ', event_feature.shape) # (batch_size, 320, 384)
residual_event_f = 0
residual_rgb_f = 0
event_f = self.cross_mamba(event_feature,residual_event_f,rgb_feature) + event_feature # 并未改变维度 torch.Size([4, 320, 384])
rgb_f = self.cross_mamba(rgb_feature,residual_rgb_f,event_feature) + rgb_feature
# print(self.feat_len_s) # 256
event_searh = event_f[:, -self.feat_len_s:]
rgb_search = rgb_f[:, -self.feat_len_s:]
# print('event_search.shape: ', event_searh.shape) # event_search.shape: torch.Size([4, 256, 384])
# print('rgb_search.shape: ', rgb_search.shape) # rgb_search.shape: torch.Size([4, 256, 384])
x = torch.cat((event_searh,rgb_search),dim=-1) # x.shape: torch.Size([4, 256, 768])
# print('x.shape: ', x.shape)
# Forward head
feat_last = x
if isinstance(x, list):
feat_last = x[-1]
out = self.forward_head(feat_last, None)
out['backbone_feat'] = x
return out
def forward_head(self, cat_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 = cat_feature
opt = (search_feature.unsqueeze(-1)).permute((0, 3, 2, 1)).contiguous() # opt.shape = torch.Size([B, 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([B, 384, 16, 16])
if self.head_type == "CORNER":
# run the corner head
pred_box, score_map = self.box_head(opt_feat, True)
outputs_coord = box_xyxy_to_cxcywh(pred_box)
outputs_coord_new = outputs_coord.view(bs, Nq, 4)
out = {'pred_boxes': outputs_coord_new,
'score_map': score_map,
}
return out
elif self.head_type == "CENTER":
# run the center head
score_map_ctr, bbox, size_map, offset_map = self.box_head(opt_feat, gt_score_map)
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}
return out
else:
raise NotImplementedError
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 = ''
code
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
中,是否需要修改?
class Mamba_FEtrack(nn.Module):
""" This is the base class for mamda_fetrack """
def __init__(self, vision_backbone, cross_mamba, box_head, aux_loss=False, head_type="CORNER"):
""" Initializes the model.
Parameters:
vision_backbone: vision backbone such as VisionMambaResNet integrated.
cross_mamba: cross-attention network or method.
box_head: head architecture for bounding box prediction.
aux_loss: True if auxiliary decoding losses (loss at each decoder layer) are to be used.
"""
super().__init__()
self.backbone = vision_backbone
self.cross_mamba = cross_mamba
self.box_head = box_head
self.aux_loss = aux_loss
self.head_type = head_type
if head_type in ["CORNER", "CENTER"]:
self.feat_sz_s = int(box_head.feat_sz)
self.feat_len_s = int(box_head.feat_sz ** 2)
if self.aux_loss:
self.box_head = _get_clones(self.box_head, 6)
def forward(self, template: torch.Tensor, search: torch.Tensor,
event_template: Optional[torch.Tensor] = None, # Ensure it can handle None inputs
event_search: Optional[torch.Tensor] = None,
ce_template_mask=None, ce_keep_rate=None, return_last_attn=False):
rgb_feature = self.backbone.forward_features(z=template, x=search)
# If your task requires both event and rgb processing
if event_template is not None and event_search is not None:
event_feature = self.backbone.forward_features(z=event_template, x=event_search)
else:
event_feature = rgb_feature # Or adjust as per requirements or set event_feature to None
event_f = self.cross_mamba(event_feature, 0, rgb_feature) + event_feature
rgb_f = self.cross_mamba(rgb_feature, 0, event_feature) + rgb_feature
event_search_feats = event_f[:, -self.feat_len_s:]
rgb_search_feats = rgb_f[:, -self.feat_len_s:]
x = torch.cat((event_search_feats, rgb_search_feats), dim=-1)
out = self.forward_head(x, None)
out['backbone_feat'] = x
return out
def build_mamba_fetrack(cfg, training=True):
current_dir = os.path.dirname(os.path.abspath(__file__))
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(
vision_backbone=backbone, # Ensure it uses the updated VisionMambaResNet
cross_mamba=cross_mamba,
box_head=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
class VisionMambaResNet(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__()
# 1. Add ResNet as a feature extractor
self.resnet = resnet18(pretrained=True)
self.resnet = nn.Sequential(*list(self.resnet.children())[:-2]) # Remove the adaptive avgpool and fc layer
# Remaining parts unchanged...
def forward_features(self, z, x, inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False):
# Use ResNet as a feature extractor
x = self.resnet(x) # This should give [B, 512, H', W']
z = self.resnet(z) # This should also give [B, 512, H', W']
# Reshape to ensure compatibility, if needed
print('resnet_x.shape:', x.shape)
print('resnet_z.shape:', z.shape)
# Flatten and prepare for Vision Transformer
B, C, H, W = x.shape
x = x.view(B, C, H * W).permute(0, 2, 1)
z = z.view(B, C, H * W).permute(0, 2, 1)
x = self.patch_embed(x)
z = self.patch_embed(z)
B, M, _ = x.shape
# Remaining parts unchanged...
总结:
确保 ResNet 的输出仍保持四维特征图:通过删除 AdaptiveAvgPool2d 和 fc 层,在定义 resnet 子模块时。
确保 forward_features 方法中 resnet 后的传统处理被正确执行。
如果问题 persist,考虑 ResNet 特征是否需要传递到后续网络的调整。
def forward(self, x):
B, C, H, W = x.shape
# assert H == self.img_size[0] and W == self.img_size[1], \
# f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
x = self.proj(x) # 将图像切分为小方块,尺寸就是patch_size
# 切块之后,维度: batch_size, embedding_dim, grid_size, grid_size
# 原始 (B,C,H,W)--> (B,N,grid_size,grid_size)
if self.flatten: # 将小方块拉平,构成序列
# 展平操作:batch_size, embedding_dim, num_patches
x = x.flatten(2).transpose(1, 2) # BCHW -> BNC
x = self.norm(x)
return x
定义mamba的encoder模块
class Block(nn.Module):
def init(
self, dim, mixer_cls, norm_cls=nn.LayerNorm, fused_add_norm=False, residual_in_fp32=False,drop_path=0.,
):
"""
Simple block wrapping a mixer class with LayerNorm/RMSNorm and residual connection"
code
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)
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)