分析:"""
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 .moise import LDDiffuse
class Mamba_FEtrack(nn.Module):
""" This is the base class for mamda_fetrack """
code
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)
# 初始化 LDDiffuse
T_STEP = 1
SAMPLE = 1000
self.lddiffuse = LDDiffuse(T_STEP, SAMPLE)
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, #[B, 320, 384]
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, #[B, 320, 384]
inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False)
loss_lddiffuse, new_rgb_feature = self.lddiffuse(rgb_feature, rgb_feature, event_feature)
residual_event_f = 0
residual_rgb_f = 0
event_f = self.cross_mamba(event_feature,residual_event_f,new_rgb_feature) + event_feature
rgb_f = self.cross_mamba(new_rgb_feature,residual_rgb_f,event_feature) + new_rgb_feature
event_searh = event_f[:, -self.feat_len_s:]
rgb_search = rgb_f[:, -self.feat_len_s:]
x = torch.cat((event_searh,rgb_search),dim=-1)
feat_last = x
if isinstance(x, list):
feat_last = x[-1]
out = self.forward_head(feat_last, None)
out['backbone_feat'] = x
out['loss_lddifuse'] = loss_lddiffuse
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
和 import torch
import torch.nn as nn
import torch.nn.functional as F
from .utils import extract
def default(val, d):
if exists(val):
return val
return d() if callable(d) else d
def extract(a, t, x_shape):
"""extract the appropriate t index for a batch of indices"""
batch_size = t.shape[0]
out = a.gather(-1, t)
return out.reshape(batch_size, *((1,) * (len(x_shape) - 1)))
class LDDiffuse(nn.Module):
def init(self, Total=1000):
super(LDDiffuse, self).init()
self.total_timesteps = Total
The provided code appears to define a PyTorch-based deep learning model related to an application called "mamda_fetrack," which seems to be a tracking model. Let's break it down step by step, analyzing key components and their interactions:
Key Components
Mamba_FEtrack Class:
Inherits from nn.Module, signifying it is a neural network model.
It combines vision features (visionmamba), cross-modal interaction using cross_mamba, and a box prediction head (box_head).
The architecture includes an auxiliary option for decoding losses (aux_loss) and supports different head types (e.g., "CORNER", "CENTER") for box prediction.
Uses components like LDDiffuse for a specific process related to the model, which seems like a diffusion process, often used in generative models.
Forward Method:
Takes multiple tensor inputs representing templates and search images, both RGB and event-based.
It extracts features using a backbone (presumably a vision transformer or similar model from the create_model function).
It applies a diffusion process (LDDiffuse) to refine features.
It performs cross-modal feature enhancement (cross_mamba).
Finally, the forward_head method processes combined features to predict bounding boxes and score maps.
LDDiffuse Class:
Implements a variance-preserving diffusion process, often used in generating or denoising tasks.
Contains methods for simulating the forward diffusion process (q_sample) and predicting noise from initial samples.
The approach uses cosine-scheduled beta values for diffusion steps, which modulate how noise is added across timesteps.
Cosine β Schedule:
The cosine_beta_schedule function provides a beta schedule that influences how noise is applied during diffusion.
This schedule is critical for controlling the variance and learning dynamics over time, maintaining stability and convergence properties.
build_mamba_fetrack Function:
Constructs an instance of Mamba_FEtrack using configurations (cfg), potentially loading pretrained weights.
Handles model backbone setup and configuration parameters, emphasizing compatibility and initialization considerations.
结合:① import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
from .utils import cosine_beta_schedule, default, extract
from .UNet import UNet
from .UViT import UViT
from SiamB.core.defaults import cfg
import matplotlib.pyplot as plt
import gc
def get_l2(f):
c, h, w = f.shape
mean = torch.mean(f, dim=0).unsqueeze(0).repeat(c, 1, 1)
f = torch.sum(torch.pow((f - mean), 2), dim=0) / c
f = f
return (f - f.min()) / (f.max() - f.min())
那么在"""
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 .moise import LDDiffuse
class Mamba_FEtrack(nn.Module):
""" This is the base class for mamda_fetrack """
对比:① import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
from .utils import cosine_beta_schedule, default, extract
from .UNet import UNet
from .UViT import UViT
from SiamB.core.defaults import cfg
import matplotlib.pyplot as plt
import gc
def get_l2(f):
c, h, w = f.shape
mean = torch.mean(f, dim=0).unsqueeze(0).repeat(c, 1, 1)
f = torch.sum(torch.pow((f - mean), 2), dim=0) / c
f = f
return (f - f.min()) / (f.max() - f.min())
def default(val, d):
if exists(val):
return val
return d() if callable(d) else d
def extract(a, t, x_shape):
"""extract the appropriate t index for a batch of indices"""
batch_size = t.shape[0]
out = a.gather(-1, t)
return out.reshape(batch_size, *((1,) * (len(x_shape) - 1)))
class LDDiffuse(nn.Module):
def init(self, Total=1000):
super(LDDiffuse, self).init()
self.total_timesteps = Total
class LDDiffuse(nn.Module):
def __init__(self, Total=1000):
super(LDDiffuse, self).__init__()
self.total_timesteps = Total
# ... (rest of the class definition)
影响分析
Total 参数意义:
Total 是扩散过程中总的时间步数。因此,传递 SAMPLE 作为这个参数意味着扩散过程会在 1000 个时间步内进行。
def default(val, d):
if exists(val):
return val
return d() if callable(d) else d
def extract(a, t, x_shape):
"""extract the appropriate t index for a batch of indices"""
batch_size = t.shape[0]
out = a.gather(-1, t)
return out.reshape(batch_size, *((1,) * (len(x_shape) - 1)))
class LDDiffuse(nn.Module):
def init(self, Total=1000):
super(LDDiffuse, self).init()
self.total_timesteps = Total
是在import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
from .utils import cosine_beta_schedule, default, extract
from .UNet import UNet
from .UViT import UViT
from SiamB.core.defaults import cfg
import matplotlib.pyplot as plt
import gc
def get_l2(f):
c, h, w = f.shape
mean = torch.mean(f, dim=0).unsqueeze(0).repeat(c, 1, 1)
f = torch.sum(torch.pow((f - mean), 2), dim=0) / c
f = f
return (f - f.min()) / (f.max() - f.min())
def default(val, d):
if exists(val):
return val
return d() if callable(d) else d
def extract(a, t, x_shape):
"""extract the appropriate t index for a batch of indices"""
batch_size = t.shape[0]
out = a.gather(-1, t)
return out.reshape(batch_size, *((1,) * (len(x_shape) - 1)))
class LDDiffuse(nn.Module):
def init(self, Total=1000):
super(LDDiffuse, self).init()
self.total_timesteps = Total
def default(val, d):
if exists(val):
return val
return d() if callable(d) else d
def extract(a, t, x_shape):
"""extract the appropriate t index for a batch of indices"""
batch_size = t.shape[0]
out = a.gather(-1, t)
return out.reshape(batch_size, *((1,) * (len(x_shape) - 1)))
class LDDiffuse(nn.Module):
def init(self, Total=1000):
super(LDDiffuse, self).init()
self.total_timesteps = Total
def default(val, d):
if exists(val):
return val
return d() if callable(d) else d
def extract(a, t, x_shape):
"""extract the appropriate t index for a batch of indices"""
batch_size = t.shape[0]
out = a.gather(-1, t)
return out.reshape(batch_size, *((1,) * (len(x_shape) - 1)))
class LDDiffuse(nn.Module):
def init(self, Total=1000):
super(LDDiffuse, self).init()
self.total_timesteps = Total
那么在"""
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 .noise import LDDiffuse
class Mamba_FEtrack(nn.Module):
""" This is the base class for mamda_fetrack """
def forward(self, rgb_feature, event_feature):
# Placeholder example of function logic
# This should perform operations on the input features
loss = # calculate some loss or metric
processed_feature = # process and return the modified feature
return loss, processed_feature
自定义逻辑:
方法中逻辑应包括例如正向扩散 q_sample 以及反向扩散 p_sample 来处理特征。
确保输出符合期望
loss 和 new_rgb_feature:
loss_lddiffuse 通常是个损失值,用于模型更新。
new_rgb_feature 是处理后的特征,准备继续在模型中使用。
示例调用与使用逻辑
如果您的 LDDiffuse 类定义了 forward 方法,可以如下进行适配调用:
python
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)
event_feature = self.backbone.forward_features(z=event_template, x=event_search)
# Ensure LDDiffuse has a compatible method
loss_lddiffuse, new_rgb_feature = self.lddiffuse.forward(rgb_feature, event_feature)
# Continue processing with updated features
# ...
return out
def default(val, d):
if exists(val):
return val
return d() if callable(d) else d
def extract(a, t, x_shape):
"""extract the appropriate t index for a batch of indices"""
batch_size = t.shape[0]
out = a.gather(-1, t)
return out.reshape(batch_size, *((1,) * (len(x_shape) - 1)))
class LDDiffuse(nn.Module):
def init(self, Total=1000):
super(LDDiffuse, self).init()
self.total_timesteps = Total
class LDDiffuse(nn.Module):
def __init__(self, Total=1000):
super(LDDiffuse, self).__init__()
self.total_timesteps = Total
# 创建扩散过程中的 beta 和 alpha 序列
betas = cosine_beta_schedule(self.total_timesteps)
alphas = 1.0 - betas
alphas_cumprod = torch.cumprod(alphas, dim=0)
alphas_cumprod_prev = F.pad(alphas_cumprod[:-1], (1, 0), value=1.0)
# 注册为缓冲变量(不会在优化时更新)
self.register_buffer('betas', betas)
self.register_buffer('alphas_cumprod', alphas_cumprod)
self.register_buffer('alphas_cumprod_prev', alphas_cumprod_prev)
self.register_buffer('sqrt_alphas_cumprod', torch.sqrt(alphas_cumprod))
self.register_buffer('sqrt_one_minus_alphas_cumprod', torch.sqrt(1.0 - alphas_cumprod))
self.register_buffer('sqrt_recip_alphas_cumprod', torch.sqrt(1.0 / alphas_cumprod))
self.register_buffer('sqrt_recipm1_alphas_cumprod', torch.sqrt(1.0 / alphas_cumprod - 1))
def forward(self, x_start, t, noise=None, pred_noise=None, mode='forward'):
"""
Perform forward or backward diffusion.
- x_start: the initial data input
- t: the current timestep
- noise: noise to add, if any
- pred_noise: predicted noise, used for backward
- mode: 'forward' for q_sample, and 'backward' for p_sample
"""
if mode == 'forward':
return self.q_sample(x_start, t, noise)
elif mode == 'backward' and pred_noise is not None:
return self.p_sample(x_start, t, pred_noise)
else:
raise ValueError("Invalid mode specified or missing predicted noise for backward diffusion.")
# 正向扩散的 q_sample 方法
def q_sample(self, x_start, t, noise=None):
if noise is None:
noise = torch.randn_like(x_start)
sqrt_alphas_cumprod_t = extract(self.sqrt_alphas_cumprod, t, x_start.shape)
sqrt_one_minus_alphas_cumprod_t = extract(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape)
return (sqrt_alphas_cumprod_t * x_start + sqrt_one_minus_alphas_cumprod_t * noise).float()
# 反向扩散的 p_sample 方法
def p_sample(self, x_t, t, pred_noise):
alpha_t = self.alphas_cumprod[t]
alpha_t_prev = self.alphas_cumprod_prev[t]
pred_x0 = (x_t - self.sqrt_one_minus_alphas_cumprod[t] * pred_noise) / self.sqrt_recip_alphas_cumprod[t]
x_prev = (
alpha_t_prev.sqrt() * pred_x0 +
torch.sqrt(1.0 - alpha_t_prev) * pred_noise
).float()
return x_prev
User
在import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
from .utils import cosine_beta_schedule, default, extract
from .UNet import UNet
from .UViT import UViT
from SiamB.core.defaults import cfg
import matplotlib.pyplot as plt
import gc
def get_l2(f):
c, h, w = f.shape
mean = torch.mean(f, dim=0).unsqueeze(0).repeat(c, 1, 1)
f = torch.sum(torch.pow((f - mean), 2), dim=0) / c
f = f
return (f - f.min()) / (f.max() - f.min())
The model is designed to handle both RGB and event data, which can offer richer information for tracking tasks.
It integrates a diffusion-based approach, potentially for refining features or simulating perturbations that can help in robust training and prediction.
The overall structure aims for modularity, allowing different configurations and components to be customized or replaced, fitting various tracking or detection requirements.
Applications and Implications
Such a model is particularly useful in scenarios requiring robust object tracking under diverse conditions, leveraging both traditional RGB images and event data.
The diffusion process might improve model robustness by enabling it to handle noisy environments or uncertain conditions better, which are common in real-world tracking.
This analysis primarily covers the structural and conceptual aspects of your provided code. Adjustments in specific components or parameters might be necessary to tailor this model to specific datasets or operational environments.
self.sampling_timesteps = default(sampling_timesteps, timesteps)
assert self.sampling_timesteps <= timesteps
self.is_ddim_sampling = self.sampling_timesteps < timesteps
self.ddim_sampling_eta = 1.
self.condition = True
# self.scale = cfg.Diffusion.SNR_SCALE
self.box_renewal = True
self.use_ensemble = True
self.register_buffer('betas', betas)
self.register_buffer('alphas_cumprod', alphas_cumprod)
self.register_buffer('alphas_cumprod_prev', alphas_cumprod_prev)
self.register_buffer('sqrt_alphas_cumprod', torch.sqrt(alphas_cumprod))
self.register_buffer('sqrt_one_minus_alphas_cumprod', torch.sqrt(1. - alphas_cumprod))
self.register_buffer('log_one_minus_alphas_cumprod', torch.log(1. - alphas_cumprod))
self.register_buffer('sqrt_recip_alphas_cumprod', torch.sqrt(1. / alphas_cumprod))
self.register_buffer('sqrt_recipm1_alphas_cumprod', torch.sqrt(1. / alphas_cumprod - 1))
posterior_variance = betas * (1. - alphas_cumprod_prev) / (1. - alphas_cumprod)
self.register_buffer('posterior_variance', posterior_variance)
self.register_buffer('posterior_log_variance_clipped', torch.log(posterior_variance.clamp(min=1e-20)))
self.register_buffer('posterior_mean_coef1', betas * torch.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod))
self.register_buffer('posterior_mean_coef2',
(1. - alphas_cumprod_prev) * torch.sqrt(alphas) / (1. - alphas_cumprod))
self.num_timesteps = Total
self.sample_timesteps = Sample
self.set_loss('l2')
self.unet = UNet(conditional=True)
# self.unet = UViT(conditional=True)
def set_loss(self, type):
if type == 'l1':
self.loss_func = nn.L1Loss(reduction='sum')
elif type == 'l2':
self.loss_func = nn.MSELoss(reduction='sum')
else:
raise NotImplementedError()
def predict_noise_from_start(self, x_t, t, x0):
return (
(extract(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - x0) /
extract(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape)
).float()
# forward diffusion
def q_sample(self, x_start, t, noise=None):
if noise is None:
noise = torch.randn_like(x_start)
sqrt_alphas_cumprod_t = extract(self.sqrt_alphas_cumprod, t, x_start.shape)
sqrt_one_minus_alphas_cumprod_t = extract(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape)
return (sqrt_alphas_cumprod_t * x_start + sqrt_one_minus_alphas_cumprod_t * noise).float(), sqrt_alphas_cumprod_t.float(), sqrt_one_minus_alphas_cumprod_t.float()
# backward generation
def p_sample(self, time, time_next, before, pred_x0, pred_noises):
if time_next == -1:
return before
alpha = self.alphas_cumprod[time]
alpha_next = self.alphas_cumprod[time_next]
sigma = self.ddim_sampling_eta * ((1 - alpha / alpha_next) * (1 - alpha_next) / (1 - alpha)).sqrt()
c = (1 - alpha_next - sigma ** 2).sqrt()
noise = torch.randn_like(before)
# x_start = pred[-1][:, 1, :, :]
# pred_noise = self.predict_noise_from_start(before, time, pred[-1])
# predict_x0 = self.get_predict_x0(before, pred, [beta], [one_beta])
out = alpha_next.sqrt() * pred_x0 + sigma * noise + c * pred_noises
# xt_next = alpha_next.sqrt() * pred +
# out = pred[-1] * alpha_next.sqrt() + \
# c * pred_noise + \
# sigma * noise
return out
## get the random t and noise for each sample within the batch
def prepare_targets(self, num, template):
ts = []
noises = []
for i in range(num):
t = torch.randint(0, self.num_timesteps, (1,)).long().cuda()
noise = torch.randn_like(template).cuda()
ts.append(t)
noises.append(noise)
return ts, noises
def get_predict_x0(self, xt, noises, betas):
x0 = [(xt[i] - (1-betas[i]).sqrt() * noises[i]) / betas[i].sqrt() for i in range(len(betas))]
return x0
def predict(self, fea_rgb, fea_tir):
# get time steps
times = torch.linspace(-1, self.num_timesteps - 1, self.sample_timesteps + 1).cuda()
times = list(reversed(times.int().tolist()))
# times = [999,2,-1]
time_pairs = list(zip(times[:-1], times[1:]))
# time_pairs = time_pairs[1:]
ol = []
pl = []
xl = []
xt = torch.randn_like(fea_rgb).cuda()
for time, time_next in time_pairs:
# time_cond = torch.full((1,), time, dtype=torch.long).cuda()
# time = 500
xl.append(xt)
time = torch.full((1,), time, dtype=torch.long).cuda()
beta = extract(self.alphas_cumprod, time, xt.shape).float()
# one_beta = extract(self.sqrt_one_minus_alphas_cumprod, time, xt.shape).float()
tem = torch.cat((torch.cat((xt, fea_rgb), dim=1), fea_tir), dim=1)
out = self.unet(tem, beta, fea_rgb)
ol.append(out)
pred_n = self.predict_noise_from_start(xt, time, out)
pl.append(pred_n)
# predict_x0 = self.get_predict_x0(xt, out_noises, [beta])[-1]
# xt = self.p_sample(time, time_next, xt, predict_x0, out_noises).float()
if time_next < 0:
# img = out_cls[:,1,:,:]
return out
else:
xt = self.p_sample(time, time_next, xt, out, pred_n).float()
# del out, pred_n
# del out, pred_n
# gc.collect()
# att = self.diffusion_model.p_sample(time_cond, time_next, att, out_cls)
def get_predicts(self, qs, ts, noises, betas):
# out = []
# for i in range(qs.size(0)):
out = self.get_predict_x0(qs, noises, betas)
# out = torch.stack(out)
out = [self.p_sample(ts[i], ts[i]-1, qs[i], out[i], noises[i]).float() for i in range(betas.size(0))]
return torch.stack(out)
def write_times(self, times):
s = ''
for time in times:
s = s + str(time.item()) + ' '
s = s + '\n'
def forward(self, fused_fea, fea_rgb, fea_tir):
sample_num = fused_fea.size(0)
# prepare
ts, noises = self.prepare_targets(sample_num, fused_fea[0])
self.write_times(ts)
qs = []
betas = []
one_betas = []
for i in range(sample_num):
q, beta, one_beta = self.q_sample(fused_fea[i], ts[i], noises[i])
qs.append(q)
betas.append(beta)
one_betas.append(one_beta)
if not self.condition:
out = self.unet(qs, betas)
else:
qs = torch.stack(qs)
betas = torch.stack(betas)
con = torch.cat((fea_rgb, fea_tir), dim=1)
out = self.unet(torch.cat((qs, con), dim=1), betas, fea_rgb)
# self.loss_func.cuda()
noises = torch.stack(noises)
pred_n = [self.predict_noise_from_start(qs[i], ts[i], out[i]) for i in range(len(ts))]
pred_n = torch.stack(pred_n)
loss = self.loss_func(noises, pred_n).cuda()
# predicted_x0s = self.get_predicts(qs, ts, out_noises, betas)
return loss, out
和 ② """
TBSI_Track model. Developed on OSTrack.
"""
import math
from operator import ipow
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, conv
from lib.models.tbsi_track.vit_tbsi_care import vit_base_patch16_224_tbsi
from lib.utils.box_ops import box_xyxy_to_cxcywh
from lib.models.lddifuse.lddifuse import LDDiffuse
'''
add token transfer to feature
'''
def token2feature(tokens):
B,L,D=tokens.shape
H=W=int(L**0.5)
x = tokens.permute(0, 2, 1).view(B, D, W, H).contiguous()
return x
class TBSIGMMTTrack(nn.Module):
""" This is the base class for TBSITrack developed on OSTrack (Ye et al. ECCV 2022) """
code
def __init__(self, transformer, box_head, ldd_head, aux_loss=False, head_type="CORNER", cfg=None):
""" 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__()
hidden_dim = transformer.embed_dim
self.backbone = transformer
self.tbsi_fuse_search = conv(hidden_dim * 2, hidden_dim) # Fuse RGB and T search regions, random initialized
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)
####----------LDDiffuse-----------####
self.lddiffuse = LDDiffuse(cfg.TRAIN.T_STEP, cfg.TEST.SAMPLE)
self.ldd_head = ldd_head
def forward(self, template: torch.Tensor,
search: torch.Tensor,
ce_template_mask=None,
ce_keep_rate=None,
return_last_attn=False,
):
x, aux_dict = self.backbone(z=template, x=search,
ce_template_mask=ce_template_mask,
ce_keep_rate=ce_keep_rate,
return_last_attn=return_last_attn)
# Forward head
feat_last = x
if isinstance(x, list):
feat_last = x[-1]
out, loss_lddifuse = self.forward_head(feat_last, None)
out.update(aux_dict)
out['backbone_feat'] = x
out['loss_lddifuse'] = loss_lddifuse
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)
"""
num_template_token = 64
num_search_token = 256
# encoder outputs for the visible and infrared search regions, both are (B, HW, C)
enc_opt1 = cat_feature[:, num_template_token:num_template_token + num_search_token, :]
enc_opt2 = cat_feature[:, -num_search_token:, :]
enc_opt = torch.cat([enc_opt1, enc_opt2], dim=2)
opt = (enc_opt.unsqueeze(-1)).permute((0, 3, 2, 1)).contiguous()
bs, Nq, C, HW = opt.size()
HW = int(HW/2)
opt_feat = opt.view(-1, C, self.feat_sz_s, self.feat_sz_s)
opt_feat = self.tbsi_fuse_search(opt_feat)
loss_lddifuse, out = self.lddiffuse(opt_feat, token2feature(enc_opt1), token2feature(enc_opt2))
loss_lddifuse = loss_lddifuse / (out.shape[0] * out.shape[1] * out.shape[2] * out.shape[3])
if self.head_type == "CORNER":
# run the corner head
# pred_box, score_map = self.box_head(opt_feat, True)
pred_box, score_map = self.ldd_head(opt_feat, True)
# score_map_ctr, bbox, offset_map = self.ldd_head(opt_feat, gt_score_map)
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, loss_lddifuse
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)
score_map_ctr, bbox, size_map, offset_map = self.ldd_head(out, gt_score_map)
# outputs_coord = box_xyxy_to_cxcywh(bbox)
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, loss_lddifuse
else:
raise NotImplementedError
def test(self, template: torch.Tensor,
search: torch.Tensor,
ce_template_mask=None,
ce_keep_rate=None,
return_last_attn=False,
):
x, aux_dict = self.backbone(z=template, x=search,
ce_template_mask=ce_template_mask,
ce_keep_rate=ce_keep_rate,
return_last_attn=return_last_attn)
# Forward head
feat_last = x
if isinstance(x, list):
feat_last = x[-1]
out = self.forward_head_test(feat_last, None)
out.update(aux_dict)
out['backbone_feat'] = x
return out
def forward_head_test(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)
"""
num_template_token = 64
num_search_token = 256
# encoder outputs for the visible and infrared search regions, both are (B, HW, C)
enc_opt1 = cat_feature[:, num_template_token:num_template_token + num_search_token, :]
enc_opt2 = cat_feature[:, -num_search_token:, :]
enc_opt = torch.cat([enc_opt1, enc_opt2], dim=2)
opt = (enc_opt.unsqueeze(-1)).permute((0, 3, 2, 1)).contiguous()
bs, Nq, C, HW = opt.size()
HW = int(HW/2)
out = self.lddiffuse.predict(token2feature(enc_opt1), token2feature(enc_opt2))
if self.head_type == "CORNER":
# run the corner head
pred_box, score_map = self.ldd_head(out, 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)
score_map_ctr, bbox, size_map, offset_map = self.ldd_head(out, 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_tbsi_gmmt_track(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')
# if cfg.MODEL.PRETRAIN_FILE and ('TBSITrack' not in cfg.MODEL.PRETRAIN_FILE) and training:
# pretrained = os.path.join(pretrained_path, cfg.MODEL.PRETRAIN_FILE)
# print('Load pretrained model from: ' + pretrained)
# else:
# pretrained = ''
pretrained = ''
if cfg.MODEL.BACKBONE.TYPE == 'vit_base_patch16_224_tbsi':
backbone = vit_base_patch16_224_tbsi(pretrained, drop_path_rate=cfg.TRAIN.DROP_PATH_RATE,
tbsi_loc=cfg.MODEL.BACKBONE.TBSI_LOC,
tbsi_drop_path=cfg.TRAIN.TBSI_DROP_PATH
)
else:
raise NotImplementedError
code
hidden_dim = backbone.embed_dim
patch_start_index = 1
backbone.finetune_track(cfg=cfg, patch_start_index=patch_start_index)
box_head = build_box_head(cfg, hidden_dim)
ldd_head = build_box_head(cfg, hidden_dim)
model = TBSIGMMTTrack(
backbone,
box_head,
ldd_head,
aux_loss=False,
head_type=cfg.MODEL.HEAD.TYPE,
cfg=cfg
)
if 'TBSITrack' in cfg.MODEL.PRETRAIN_FILE and training:
pretrained_file = os.path.join(pretrained_path, cfg.MODEL.PRETRAIN_FILE)
checkpoint = torch.load(pretrained_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
分析网络结构和流程。
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)
# 初始化 LDDiffuse
T_STEP = 1
SAMPLE = 1000
self.lddiffuse = LDDiffuse(T_STEP, SAMPLE)
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, #[B, 320, 384]
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, #[B, 320, 384]
inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False)
loss_lddiffuse, new_rgb_feature = self.lddiffuse(rgb_feature, rgb_feature, event_feature)
residual_event_f = 0
residual_rgb_f = 0
event_f = self.cross_mamba(event_feature,residual_event_f,new_rgb_feature) + event_feature
rgb_f = self.cross_mamba(new_rgb_feature,residual_rgb_f,event_feature) + new_rgb_feature
event_searh = event_f[:, -self.feat_len_s:]
rgb_search = rgb_f[:, -self.feat_len_s:]
x = torch.cat((event_searh,rgb_search),dim=-1)
feat_last = x
if isinstance(x, list):
feat_last = x[-1]
out = self.forward_head(feat_last, None)
out['backbone_feat'] = x
out['loss_lddifuse'] = loss_lddiffuse
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
中调用 LDDiffuse模块,检查逻辑以及作用
self.sampling_timesteps = default(sampling_timesteps, timesteps)
assert self.sampling_timesteps <= timesteps
self.is_ddim_sampling = self.sampling_timesteps < timesteps
self.ddim_sampling_eta = 1.
self.condition = True
# self.scale = cfg.Diffusion.SNR_SCALE
self.box_renewal = True
self.use_ensemble = True
self.register_buffer('betas', betas)
self.register_buffer('alphas_cumprod', alphas_cumprod)
self.register_buffer('alphas_cumprod_prev', alphas_cumprod_prev)
self.register_buffer('sqrt_alphas_cumprod', torch.sqrt(alphas_cumprod))
self.register_buffer('sqrt_one_minus_alphas_cumprod', torch.sqrt(1. - alphas_cumprod))
self.register_buffer('log_one_minus_alphas_cumprod', torch.log(1. - alphas_cumprod))
self.register_buffer('sqrt_recip_alphas_cumprod', torch.sqrt(1. / alphas_cumprod))
self.register_buffer('sqrt_recipm1_alphas_cumprod', torch.sqrt(1. / alphas_cumprod - 1))
posterior_variance = betas * (1. - alphas_cumprod_prev) / (1. - alphas_cumprod)
self.register_buffer('posterior_variance', posterior_variance)
self.register_buffer('posterior_log_variance_clipped', torch.log(posterior_variance.clamp(min=1e-20)))
self.register_buffer('posterior_mean_coef1', betas * torch.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod))
self.register_buffer('posterior_mean_coef2',
(1. - alphas_cumprod_prev) * torch.sqrt(alphas) / (1. - alphas_cumprod))
self.num_timesteps = Total
self.sample_timesteps = Sample
self.set_loss('l2')
self.unet = UNet(conditional=True)
# self.unet = UViT(conditional=True)
def set_loss(self, type):
if type == 'l1':
self.loss_func = nn.L1Loss(reduction='sum')
elif type == 'l2':
self.loss_func = nn.MSELoss(reduction='sum')
else:
raise NotImplementedError()
def predict_noise_from_start(self, x_t, t, x0):
return (
(extract(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - x0) /
extract(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape)
).float()
# forward diffusion
def q_sample(self, x_start, t, noise=None):
if noise is None:
noise = torch.randn_like(x_start)
sqrt_alphas_cumprod_t = extract(self.sqrt_alphas_cumprod, t, x_start.shape)
sqrt_one_minus_alphas_cumprod_t = extract(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape)
return (sqrt_alphas_cumprod_t * x_start + sqrt_one_minus_alphas_cumprod_t * noise).float(), sqrt_alphas_cumprod_t.float(), sqrt_one_minus_alphas_cumprod_t.float()
# backward generation
def p_sample(self, time, time_next, before, pred_x0, pred_noises):
if time_next == -1:
return before
alpha = self.alphas_cumprod[time]
alpha_next = self.alphas_cumprod[time_next]
sigma = self.ddim_sampling_eta * ((1 - alpha / alpha_next) * (1 - alpha_next) / (1 - alpha)).sqrt()
c = (1 - alpha_next - sigma ** 2).sqrt()
noise = torch.randn_like(before)
# x_start = pred[-1][:, 1, :, :]
# pred_noise = self.predict_noise_from_start(before, time, pred[-1])
# predict_x0 = self.get_predict_x0(before, pred, [beta], [one_beta])
out = alpha_next.sqrt() * pred_x0 + sigma * noise + c * pred_noises
# xt_next = alpha_next.sqrt() * pred +
# out = pred[-1] * alpha_next.sqrt() + \
# c * pred_noise + \
# sigma * noise
return out
## get the random t and noise for each sample within the batch
def prepare_targets(self, num, template):
ts = []
noises = []
for i in range(num):
t = torch.randint(0, self.num_timesteps, (1,)).long().cuda()
noise = torch.randn_like(template).cuda()
ts.append(t)
noises.append(noise)
return ts, noises
def get_predict_x0(self, xt, noises, betas):
x0 = [(xt[i] - (1-betas[i]).sqrt() * noises[i]) / betas[i].sqrt() for i in range(len(betas))]
return x0
def predict(self, fea_rgb, fea_tir):
# get time steps
times = torch.linspace(-1, self.num_timesteps - 1, self.sample_timesteps + 1).cuda()
times = list(reversed(times.int().tolist()))
# times = [999,2,-1]
time_pairs = list(zip(times[:-1], times[1:]))
# time_pairs = time_pairs[1:]
ol = []
pl = []
xl = []
xt = torch.randn_like(fea_rgb).cuda()
for time, time_next in time_pairs:
# time_cond = torch.full((1,), time, dtype=torch.long).cuda()
# time = 500
xl.append(xt)
time = torch.full((1,), time, dtype=torch.long).cuda()
beta = extract(self.alphas_cumprod, time, xt.shape).float()
# one_beta = extract(self.sqrt_one_minus_alphas_cumprod, time, xt.shape).float()
tem = torch.cat((torch.cat((xt, fea_rgb), dim=1), fea_tir), dim=1)
out = self.unet(tem, beta, fea_rgb)
ol.append(out)
pred_n = self.predict_noise_from_start(xt, time, out)
pl.append(pred_n)
# predict_x0 = self.get_predict_x0(xt, out_noises, [beta])[-1]
# xt = self.p_sample(time, time_next, xt, predict_x0, out_noises).float()
if time_next < 0:
# img = out_cls[:,1,:,:]
return out
else:
xt = self.p_sample(time, time_next, xt, out, pred_n).float()
# del out, pred_n
# del out, pred_n
# gc.collect()
# att = self.diffusion_model.p_sample(time_cond, time_next, att, out_cls)
def get_predicts(self, qs, ts, noises, betas):
# out = []
# for i in range(qs.size(0)):
out = self.get_predict_x0(qs, noises, betas)
# out = torch.stack(out)
out = [self.p_sample(ts[i], ts[i]-1, qs[i], out[i], noises[i]).float() for i in range(betas.size(0))]
return torch.stack(out)
def write_times(self, times):
s = ''
for time in times:
s = s + str(time.item()) + ' '
s = s + '\n'
def forward(self, fused_fea, fea_rgb, fea_tir):
sample_num = fused_fea.size(0)
# prepare
ts, noises = self.prepare_targets(sample_num, fused_fea[0])
self.write_times(ts)
qs = []
betas = []
one_betas = []
for i in range(sample_num):
q, beta, one_beta = self.q_sample(fused_fea[i], ts[i], noises[i])
qs.append(q)
betas.append(beta)
one_betas.append(one_beta)
if not self.condition:
out = self.unet(qs, betas)
else:
qs = torch.stack(qs)
betas = torch.stack(betas)
con = torch.cat((fea_rgb, fea_tir), dim=1)
out = self.unet(torch.cat((qs, con), dim=1), betas, fea_rgb)
# self.loss_func.cuda()
noises = torch.stack(noises)
pred_n = [self.predict_noise_from_start(qs[i], ts[i], out[i]) for i in range(len(ts))]
pred_n = torch.stack(pred_n)
loss = self.loss_func(noises, pred_n).cuda()
# predicted_x0s = self.get_predicts(qs, ts, out_noises, betas)
return loss, out
和 ② import torch
import torch.nn as nn
import torch.nn.functional as F
from .utils import extract
def default(val, d):
if exists(val):
return val
return d() if callable(d) else d
def extract(a, t, x_shape):
"""extract the appropriate t index for a batch of indices"""
batch_size = t.shape[0]
out = a.gather(-1, t)
return out.reshape(batch_size, *((1,) * (len(x_shape) - 1)))
class LDDiffuse(nn.Module):
def init(self, Total=1000):
super(LDDiffuse, self).init()
self.total_timesteps = Total
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 .noise import LDDiffuse
class Mamba_FEtrack(nn.Module):
""" This is the base class for mamda_fetrack """
code
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)
# 初始化 LDDiffuse
SAMPLE = 1000
self.lddiffuse = LDDiffuse(SAMPLE)
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, #[B, 320, 384]
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, #[B, 320, 384]
inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False)
loss_lddiffuse, new_rgb_feature = self.lddiffuse(rgb_feature, rgb_feature, event_feature)
residual_event_f = 0
residual_rgb_f = 0
event_f = self.cross_mamba(event_feature,residual_event_f,new_rgb_feature) + event_feature
rgb_f = self.cross_mamba(new_rgb_feature,residual_rgb_f,event_feature) + new_rgb_feature
event_searh = event_f[:, -self.feat_len_s:]
rgb_search = rgb_f[:, -self.feat_len_s:]
x = torch.cat((event_searh,rgb_search),dim=-1)
feat_last = x
if isinstance(x, list):
feat_last = x[-1]
out = self.forward_head(feat_last, None)
out['backbone_feat'] = x
out['loss_lddifuse'] = loss_lddiffuse
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
self.sampling_timesteps = default(sampling_timesteps, timesteps)
assert self.sampling_timesteps <= timesteps
self.is_ddim_sampling = self.sampling_timesteps < timesteps
self.ddim_sampling_eta = 1.
self.condition = True
# self.scale = cfg.Diffusion.SNR_SCALE
self.box_renewal = True
self.use_ensemble = True
self.register_buffer('betas', betas)
self.register_buffer('alphas_cumprod', alphas_cumprod)
self.register_buffer('alphas_cumprod_prev', alphas_cumprod_prev)
self.register_buffer('sqrt_alphas_cumprod', torch.sqrt(alphas_cumprod))
self.register_buffer('sqrt_one_minus_alphas_cumprod', torch.sqrt(1. - alphas_cumprod))
self.register_buffer('log_one_minus_alphas_cumprod', torch.log(1. - alphas_cumprod))
self.register_buffer('sqrt_recip_alphas_cumprod', torch.sqrt(1. / alphas_cumprod))
self.register_buffer('sqrt_recipm1_alphas_cumprod', torch.sqrt(1. / alphas_cumprod - 1))
posterior_variance = betas * (1. - alphas_cumprod_prev) / (1. - alphas_cumprod)
self.register_buffer('posterior_variance', posterior_variance)
self.register_buffer('posterior_log_variance_clipped', torch.log(posterior_variance.clamp(min=1e-20)))
self.register_buffer('posterior_mean_coef1', betas * torch.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod))
self.register_buffer('posterior_mean_coef2',
(1. - alphas_cumprod_prev) * torch.sqrt(alphas) / (1. - alphas_cumprod))
self.num_timesteps = Total
self.sample_timesteps = Sample
self.set_loss('l2')
self.unet = UNet(conditional=True)
# self.unet = UViT(conditional=True)
def set_loss(self, type):
if type == 'l1':
self.loss_func = nn.L1Loss(reduction='sum')
elif type == 'l2':
self.loss_func = nn.MSELoss(reduction='sum')
else:
raise NotImplementedError()
def predict_noise_from_start(self, x_t, t, x0):
return (
(extract(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - x0) /
extract(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape)
).float()
# forward diffusion
def q_sample(self, x_start, t, noise=None):
if noise is None:
noise = torch.randn_like(x_start)
sqrt_alphas_cumprod_t = extract(self.sqrt_alphas_cumprod, t, x_start.shape)
sqrt_one_minus_alphas_cumprod_t = extract(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape)
return (sqrt_alphas_cumprod_t * x_start + sqrt_one_minus_alphas_cumprod_t * noise).float(), sqrt_alphas_cumprod_t.float(), sqrt_one_minus_alphas_cumprod_t.float()
# backward generation
def p_sample(self, time, time_next, before, pred_x0, pred_noises):
if time_next == -1:
return before
alpha = self.alphas_cumprod[time]
alpha_next = self.alphas_cumprod[time_next]
sigma = self.ddim_sampling_eta * ((1 - alpha / alpha_next) * (1 - alpha_next) / (1 - alpha)).sqrt()
c = (1 - alpha_next - sigma ** 2).sqrt()
noise = torch.randn_like(before)
# x_start = pred[-1][:, 1, :, :]
# pred_noise = self.predict_noise_from_start(before, time, pred[-1])
# predict_x0 = self.get_predict_x0(before, pred, [beta], [one_beta])
out = alpha_next.sqrt() * pred_x0 + sigma * noise + c * pred_noises
# xt_next = alpha_next.sqrt() * pred +
# out = pred[-1] * alpha_next.sqrt() + \
# c * pred_noise + \
# sigma * noise
return out
## get the random t and noise for each sample within the batch
def prepare_targets(self, num, template):
ts = []
noises = []
for i in range(num):
t = torch.randint(0, self.num_timesteps, (1,)).long().cuda()
noise = torch.randn_like(template).cuda()
ts.append(t)
noises.append(noise)
return ts, noises
def get_predict_x0(self, xt, noises, betas):
x0 = [(xt[i] - (1-betas[i]).sqrt() * noises[i]) / betas[i].sqrt() for i in range(len(betas))]
return x0
def predict(self, fea_rgb, fea_tir):
# get time steps
times = torch.linspace(-1, self.num_timesteps - 1, self.sample_timesteps + 1).cuda()
times = list(reversed(times.int().tolist()))
# times = [999,2,-1]
time_pairs = list(zip(times[:-1], times[1:]))
# time_pairs = time_pairs[1:]
ol = []
pl = []
xl = []
xt = torch.randn_like(fea_rgb).cuda()
for time, time_next in time_pairs:
# time_cond = torch.full((1,), time, dtype=torch.long).cuda()
# time = 500
xl.append(xt)
time = torch.full((1,), time, dtype=torch.long).cuda()
beta = extract(self.alphas_cumprod, time, xt.shape).float()
# one_beta = extract(self.sqrt_one_minus_alphas_cumprod, time, xt.shape).float()
tem = torch.cat((torch.cat((xt, fea_rgb), dim=1), fea_tir), dim=1)
out = self.unet(tem, beta, fea_rgb)
ol.append(out)
pred_n = self.predict_noise_from_start(xt, time, out)
pl.append(pred_n)
# predict_x0 = self.get_predict_x0(xt, out_noises, [beta])[-1]
# xt = self.p_sample(time, time_next, xt, predict_x0, out_noises).float()
if time_next < 0:
# img = out_cls[:,1,:,:]
return out
else:
xt = self.p_sample(time, time_next, xt, out, pred_n).float()
# del out, pred_n
# del out, pred_n
# gc.collect()
# att = self.diffusion_model.p_sample(time_cond, time_next, att, out_cls)
def get_predicts(self, qs, ts, noises, betas):
# out = []
# for i in range(qs.size(0)):
out = self.get_predict_x0(qs, noises, betas)
# out = torch.stack(out)
out = [self.p_sample(ts[i], ts[i]-1, qs[i], out[i], noises[i]).float() for i in range(betas.size(0))]
return torch.stack(out)
def write_times(self, times):
s = ''
for time in times:
s = s + str(time.item()) + ' '
s = s + '\n'
def forward(self, fused_fea, fea_rgb, fea_tir):
sample_num = fused_fea.size(0)
# prepare
ts, noises = self.prepare_targets(sample_num, fused_fea[0])
self.write_times(ts)
qs = []
betas = []
one_betas = []
for i in range(sample_num):
q, beta, one_beta = self.q_sample(fused_fea[i], ts[i], noises[i])
qs.append(q)
betas.append(beta)
one_betas.append(one_beta)
if not self.condition:
out = self.unet(qs, betas)
else:
qs = torch.stack(qs)
betas = torch.stack(betas)
con = torch.cat((fea_rgb, fea_tir), dim=1)
out = self.unet(torch.cat((qs, con), dim=1), betas, fea_rgb)
# self.loss_func.cuda()
noises = torch.stack(noises)
pred_n = [self.predict_noise_from_start(qs[i], ts[i], out[i]) for i in range(len(ts))]
pred_n = torch.stack(pred_n)
loss = self.loss_func(noises, pred_n).cuda()
# predicted_x0s = self.get_predicts(qs, ts, out_noises, betas)
return loss, out
中,传入了两个参数
解释与作用
反向扩散目的:
反向扩散通过逐步去除噪声或逐步迭代从随机状态生成的数据,产生最终的无噪声特征或目标数据。
这种方法在图像生成、去噪和逆问题(如复原低质量图像)等领域中尤为重要。
步骤解析:
计算变量: 根据 t 计算当前和先前时间步的 alpha 和 beta,这些值用于控制反向扩散的规模和路径。
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)
# 初始化 LDDiffuse
SAMPLE = 1000
self.lddiffuse = LDDiffuse(SAMPLE)
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, #[B, 320, 384]
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, #[B, 320, 384]
inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False)
loss_lddiffuse, new_rgb_feature = self.lddiffuse(rgb_feature, rgb_feature, event_feature)
residual_event_f = 0
residual_rgb_f = 0
event_f = self.cross_mamba(event_feature,residual_event_f,new_rgb_feature) + event_feature
rgb_f = self.cross_mamba(new_rgb_feature,residual_rgb_f,event_feature) + new_rgb_feature
event_searh = event_f[:, -self.feat_len_s:]
rgb_search = rgb_f[:, -self.feat_len_s:]
x = torch.cat((event_searh,rgb_search),dim=-1)
feat_last = x
if isinstance(x, list):
feat_last = x[-1]
out = self.forward_head(feat_last, None)
out['backbone_feat'] = x
out['loss_lddifuse'] = loss_lddiffuse
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