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
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
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()
The resnet in your code is set up as a custom PyTorch module that uses a pre-trained ResNet model from the torchvision.models module. Below is a breakdown of how it is configured:
Function make_resnet: This helper function creates a ResNet model based on the specified architecture ('resnet18', 'resnet34', 'resnet50', or 'resnet101') using the torchvision.models library. The model is loaded with pre-trained weights (set by pretrained=True). The final fully connected layer of the model (model.fc) is replaced with an identity layer, effectively removing it. This turns the ResNet into a feature extractor that outputs features instead of classification logits.
python
def make_resnet(name='resnet18'):
if name == 'resnet18':
model = torchvision.models.resnet18(pretrained=True)
elif name == 'resnet34':
model = torchvision.models.resnet34(pretrained=True)
elif name == 'resnet50':
model = torchvision.models.resnet50(pretrained=True)
elif name == 'resnet101':
model = torchvision.models.resnet101(pretrained=True)
else:
raise Exception('There are no supported resnet model {}.'.format(_('resnet')))
model.fc = nn.Identity() # Remove the final classification layer
return model
Class resnet: This custom module encapsulates the ResNet model created by make_resnet. Upon initialization, it creates the specified ResNet model and stores it in self.resnet. The forward method of this class processes input images through the ResNet model:
It expects x, a batch of images, and lengths, which could possibly represent varying sequence lengths if the implementation is dealing with video data or batches of variable-sized inputs.
The images (x) are passed through self.resnet to extract features.
The results are reassembled into a batch with padding to account for varying lengths, using the pad_sequence function.
def make_resnet(name='resnet18'):
if name == 'resnet18':
model = torchvision.models.resnet18(pretrained=True)
elif name == 'resnet34':
model = torchvision.models.resnet34(pretrained=True)
elif name == 'resnet50':
model = torchvision.models.resnet50(pretrained=True)
elif name == 'resnet101':
model = torchvision.models.resnet101(pretrained=True)
else:
raise Exception('There are no supported resnet model {}.'.format(_('resnet')))
model.fc = nn.Identity() # 移除最终的分类层
return model
class resnet(nn.Module):
def __init__(self, name="resnet18"):
super(resnet, self).__init__()
self.resnet = make_resnet(name=name)
def forward(self, x, lengths):
x = self.resnet(x) # 使用 ResNet 提取特征
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
这些组件一起定义了 ResNet 如何在你的神经网络管道中被用作一个特征提取器。网络通过 ResNet 处理每个输入批次,提取特征,填充序列,并创建一个统一的张量,以便后续由其他模型组件(如时间卷积层或 time MAMBA 模块)进一步处理。
User
在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
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
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()
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
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.,
attention_reduction=4, spatial_kernel_size=7 # 添加用于控制 SpatialAttentionModule 的 kernel size 的参数
):
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()
# 实例化 ChannelAttentionModule 和 SpatialAttentionModule
self.channel_attention = ChannelAttentionModule(in_channels=dim, reduction=attention_reduction)
self.spatial_attention = SpatialAttentionModule(kernel_size=spatial_kernel_size)
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
):
# 1. 应用 Channel Attention
hidden_states = rearrange(hidden_states, 'b n d -> b d n 1')
hidden_states = self.channel_attention(hidden_states)
# 2. 应用 Spatial Attention
hidden_states = self.spatial_attention(hidden_states)
# 还原维度排序
hidden_states = rearrange(hidden_states, 'b d n 1 -> b n d')
# 3. Normalization 和 Drop Path
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,
)
# 4. Mamba mixer (core logic)
hidden_states = self.mixer(hidden_states, inference_params=inference_params)
return hidden_states, residual
User
这样设置的: hidden_states0 = rearrange(hidden_states, 'b n d -> b d n 1')
hidden_states1 = self.channel_attention(hidden_states0)
hidden_states2 = self.spatial_attention(hidden_states1)
hidden_states2 = rearrange(hidden_states2, 'b d n 1 -> b n d')
hidden_states = hidden_states2 + hidden_states,相比较上文中的设置有何不同
class resnet(nn.Module):
def __init__(self, name="resnet18"):
super(resnet, self).__init__()
self.resnet = make_resnet(name=name)
def forward(self, x, lengths):
x = self.resnet(x) # Extract features using ResNet
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) # Pad to ensure uniform length
return x
These components together define how the ResNet is set up to be used as a feature extractor for images in the broader context of your neural network pipeline. The network processes each input batch through the ResNet, extracts features, and pads the sequences to create a uniform tensor for further processing by other components of the model, like the temporal convolution layers or the time MAMBA module.
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
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 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)