####################################### 等同于 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
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
# 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))
"""
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:
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 Enhancement_texture_LDC class appears to be a specialized convolutional module designed to enhance texture details in feature maps. Here's a detailed analysis of the components and functionality:
Components Analysis
Convolutional Layer (self.conv):
This is a standard 2D convolutional layer. The parameters such as kernel_size, stride, padding, and dilation define the behaviour of the convolution operation.
The layer is initialized for enhancing the input features, which are likely to be image feature maps.
Center Mask (self.center_mask):
This is a fixed 3x3 mask with a single '1' at the center, effectively focusing on the central pixel of the convolutional kernel. This mask aids in computing the difference effect by weighting the center pixel.
Base Mask (self.base_mask):
Initialized to be a tensor of ones with the same size as the convolutional weights. This mask is not trainable and serves as a starting point for the masking mechanism.
Learnable Mask (self.learnable_mask):
A trainable parameter with dimensions [output_channels, input_channels].
This mask is intended to introduce a trainable aspect to the texture enhancement, allowing the network to learn how much emphasis to give to each filter pair.
Learnable Theta (self.learnable_theta):
A single scalar parameter that scales the effect of the learnable mask. It is initialized to 0.5 and is trainable, meaning the model can adapt its value during training.
Forward Method Analysis
Mask Calculation:
The mask is computed by adjusting the base mask using both the learnable mask and learnable_theta.
The learnable mask is multiplied by learnable_theta and the center mask, then subtracted from the base mask to form a new mask.
Additionally, the sum of the convolution weights along the kernel dimensions helps modulate this mask, allowing adaptive emphasis on certain features.
Enhanced Feature Map (out_diff):
The computed mask is applied to the convolutional weights, and convolution is conducted on the input x.
This operation results in enhanced feature maps that have emphasized or suppressed texture details based on the learnable interactions specified by the mask.
FEM Class Analysis
The FEM class is a simple wrapper that uses the Enhancement_texture_LDC module to enhance input features. Its role is to encapsulate the texture enhancement within a larger potential feature enhancement strategy.
Possible Issues and Considerations
Complex Masking Operations:
The interaction between base_mask, learnable_mask, and learnable_theta might complicate the learning process. It's worth monitoring if the model learns reasonable values for these parameters.
Training Stability:
With multiple learnable components modulating the convolution operation, training stability could be a concern, especially with small datasets or high learning rates.
Effective Use Period:
The effectiveness of texture enhancement needs to be validated with regard to task-specific metrics. Depending on the task (e.g. tracking, classification), additional fine-tuning might be necessary.
Resource Utilization:
As an enhancement module, it could potentially increase computational complexity and require more GPU memory, especially with larger feature maps.
In terms of model performance, it's essential to validate whether the texture enhancement can be meaningfully translated into improvements in your specific tasks such as object tracking. Moreover, testing different configurations of the masks and the theta may yield better generalization and performance.