在"""
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 .DFuse import TokenSwapMamba, M3
class Mamba_FEtrack(nn.Module):
""" This is the base class for mamda_fetrack """
code
Assistant
根据错误信息,我们可以确定问题出在向量大小不匹配上。具体来说,mu(均值向量)和 sigma(方差向量)的形状与 x 中在维度 2 上的其他张量不匹配。此错误建议 x 在这里的形状为 (batch_size, some_dimension, 3),但在执行某些操作时与 (batch_size, some_dimension, 384) 的向量做了直接操作。
以下是一些可能的调试步骤和修改方案:
检查输入张量的形状:
确保在进行正则化(标准化)操作之前的所有张量形状与预期的一致。例如,在 LayerNorm 类的 forward 方法中,检查传给 to_3d(x) 的 x 的形状是否符合要求。
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,
):
rgb_feature = self.backbone.forward_features( z=template, x=search,
inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False)
event_feature = self.backbone.forward_features(z=event_template, x=event_search,
inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False)
# 获取当前设备
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# 初始化残差特征为与相应特征相同的形状
residual_event_f = torch.zeros_like(event_feature).to(device)
residual_rgb_f = torch.zeros_like(rgb_feature).to(device)
# 将特征通过 TokenSwapMamba 进行处理
token_swap = TokenSwapMamba(dim=rgb_feature.size(-1)).to(device)
event_f, rgb_f, residual_event_f, residual_rgb_f = token_swap(
event_feature,
rgb_feature,
residual_event_f,
residual_rgb_f
)
# event_f = self.cross_mamba(event_feature,residual_event_f,rgb_feature) + event_feature
# rgb_f = self.cross_mamba(rgb_feature,residual_rgb_f,event_feature) + rgb_feature
event_searh = event_f[:, -self.feat_len_s:]
rgb_search = rgb_f[:, -self.feat_len_s:]
print('event_search.shape:',event_searh.shape) # torch.Size([2, 256, 384])
print('rgb_search.shape:',rgb_search.shape) # torch.Size([2, 256, 384])
test_h, test_w = 16, 16
m3 = M3(dim=rgb_search.size(-1)).to(device)
fusion_residual = torch.zeros_like(rgb_search).to(device)
print('fusion_residual.shape:', fusion_residual.shape) # 检查初始化后的残差形状
fusion_result, fusion_residual = m3(I1=rgb_search,
fusion_resi=fusion_residual,
I2=event_search,
fusion=fusion_residual,
test_h=test_h,
test_w=test_w
)
print('m3 output shape:', fusion_result.shape, fusion_residual.shape) # 输出形状的最终确认
# 使用融合结果进行后续处理
feat_last = fusion_result
out = self.forward_head(feat_last, None)
out['backbone_feat'] = fusion_result
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()
bs, Nq, C, HW = opt.size()
opt_feat = opt.view(-1, C, self.feat_sz_s, self.feat_sz_s)
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 = ''
中调用import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from timm.models.layers import to_2tuple, trunc_normal_
from einops import rearrange
import numbers
from mamba_ssm.modules.mamba_simple import Mamba
import torch
def to_3d(x):
return rearrange(x, 'b c h w -> b (h w) c')
def to_4d(x, h, w):
return rearrange(x, 'b (h w) c -> b c h w', h=h, w=w)
class BiasFree_LayerNorm(nn.Module):
def init(self, normalized_shape):
super(BiasFree_LayerNorm, self).init()
if isinstance(normalized_shape, numbers.Integral):
normalized_shape = (normalized_shape,)
normalized_shape = torch.Size(normalized_shape)
中,M3集成之后报错: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 "/home/heyuting/anaconda3/envs/mamba/lib/python3.10/site-packages/torch/nn/parallel/distributed.py", line 1519, in forward
else self._run_ddp_forward(*inputs, **kwargs)
File "/home/heyuting/anaconda3/envs/mamba/lib/python3.10/site-packages/torch/nn/parallel/distributed.py", line 1355, in _run_ddp_forward
return self.module(*inputs, **kwargs) # type: ignore[index]
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 81, in forward
fusion_result, fusion_residual = m3(I1=rgb_search,
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/DFuse.py", line 120, in forward
I2 = self.norm2(I2)
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/DFuse.py", line 60, in forward
return to_4d(self.body(to_3d(x)), h, w)
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/DFuse.py", line 47, in forward
return (x - mu) / torch.sqrt(sigma+1e-5) * self.weight + self.bias
RuntimeError: The size of tensor a (3) must match the size of tensor b (384) at non-singleton dimension 2
Restarting training from last epoch ...
Finished training!
还是报错: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 "/home/heyuting/anaconda3/envs/mamba/lib/python3.10/site-packages/torch/nn/parallel/distributed.py", line 1519, in forward
else self._run_ddp_forward(*inputs, **kwargs)
File "/home/heyuting/anaconda3/envs/mamba/lib/python3.10/site-packages/torch/nn/parallel/distributed.py", line 1355, in _run_ddp_forward
return self.module(*inputs, **kwargs) # type: ignore[index]
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 81, in forward
fusion_result, fusion_residual = m3(I1=rgb_search,
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/DFuse.py", line 123, in forward
I2 = self.norm2(I2)
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/DFuse.py", line 65, in forward
return to_4d(self.body(to_3d(x)), h, w)
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/DFuse.py", line 52, in forward
return ((x - mu) / torch.sqrt(sigma + 1e-5)) * self.weight.unsqueeze(0).unsqueeze(0) + self.bias.unsqueeze(0).unsqueeze(0)
RuntimeError: The size of tensor a (3) must match the size of tensor b (384) at non-singleton dimension 2
Restarting training from last epoch ...
Finished training!