① import torch
from torch import nn
import timm
import math
'''
def forward_block(self, x):
x = x + self.drop_path(self.attn(self.norm1(x))) + self.drop_path(self.adapter_attn(self.norm1(x))) * self.s
x = x + self.drop_path(self.mlp(self.norm2(x))) + self.drop_path(self.adapter_mlp(self.norm2(x))) * self.s
return x
def forward_block_attn(self, x):
x = x + self.drop_path(self.attn(self.norm1(x))) + self.drop_path(self.adapter_attn(self.norm1(x))) * self.s
x = x + self.drop_path(self.mlp(self.norm2(x)))
return x
'''
class QuickGELU(nn.Module):
def forward(self, x: torch.Tensor):
return x * torch.sigmoid(1.702 * x)
class Bi_direct_adapter(nn.Module):
def init(self, dim=8, xavier_init=False):
super().init()
""" ② import math
import torch
import torch.nn as nn
from timm.models.layers import Mlp, DropPath, trunc_normal_, lecun_normal_
from lib.models.layers.attn import Attention
from lib.models.layers.adapter import Bi_direct_adapter
def candidate_elimination(attn: torch.Tensor, tokens: torch.Tensor, lens_t: int, keep_ratio: float, global_index: torch.Tensor, box_mask_z: torch.Tensor):
"""
Eliminate potential background candidates for computation reduction and noise cancellation.
Args:
attn (torch.Tensor): [B, num_heads, L_t + L_s, L_t + L_s], attention weights
tokens (torch.Tensor): [B, L_t + L_s, C], template and search region tokens
lens_t (int): length of template
keep_ratio (float): keep ratio of search region tokens (candidates)
global_index (torch.Tensor): global index of search region tokens
box_mask_z (torch.Tensor): template mask used to accumulate attention weights
code
Returns:
tokens_new (torch.Tensor): tokens after candidate elimination
keep_index (torch.Tensor): indices of kept search region tokens
removed_index (torch.Tensor): indices of removed search region tokens
"""
lens_s = attn.shape[-1] - lens_t
bs, hn, _, _ = attn.shape
lens_keep = math.ceil(keep_ratio * lens_s)
if lens_keep == lens_s:
return tokens, global_index, None
attn_t = attn[:, :, :lens_t, lens_t:]
if box_mask_z is not None:
#print("\n1\n1\n1")
box_mask_z = box_mask_z.unsqueeze(1).unsqueeze(-1).expand(-1, attn_t.shape[1], -1, attn_t.shape[-1])
# attn_t = attn_t[:, :, box_mask_z, :]
attn_t = attn_t[box_mask_z]
attn_t = attn_t.view(bs, hn, -1, lens_s)
attn_t = attn_t.mean(dim=2).mean(dim=1) # B, H, L-T, L_s --> B, L_s
# attn_t = [attn_t[i, :, box_mask_z[i, :], :] for i in range(attn_t.size(0))]
# attn_t = [attn_t[i].mean(dim=1).mean(dim=0) for i in range(len(attn_t))]
# attn_t = torch.stack(attn_t, dim=0)
else:
attn_t = attn_t.mean(dim=2).mean(dim=1) # B, H, L-T, L_s --> B, L_s
# use sort instead of topk, due to the speed issue
# https://github.com/pytorch/pytorch/issues/22812
sorted_attn, indices = torch.sort(attn_t, dim=1, descending=True)
topk_attn, topk_idx = sorted_attn[:, :lens_keep], indices[:, :lens_keep]
non_topk_attn, non_topk_idx = sorted_attn[:, lens_keep:], indices[:, lens_keep:]
keep_index = global_index.gather(dim=1, index=topk_idx)
removed_index = global_index.gather(dim=1, index=non_topk_idx)
# separate template and search tokens
tokens_t = tokens[:, :lens_t]
tokens_s = tokens[:, lens_t:]
# obtain the attentive and inattentive tokens
B, L, C = tokens_s.shape
# topk_idx_ = topk_idx.unsqueeze(-1).expand(B, lens_keep, C)
attentive_tokens = tokens_s.gather(dim=1, index=topk_idx.unsqueeze(-1).expand(B, -1, C))
# inattentive_tokens = tokens_s.gather(dim=1, index=non_topk_idx.unsqueeze(-1).expand(B, -1, C))
# compute the weighted combination of inattentive tokens
# fused_token = non_topk_attn @ inattentive_tokens
# concatenate these tokens
# tokens_new = torch.cat([tokens_t, attentive_tokens, fused_token], dim=0)
tokens_new = torch.cat([tokens_t, attentive_tokens], dim=1)
#print("finish ce func")
return tokens_new, keep_index, removed_index # x, global_index_search, removed_index_search
class CEABlock(nn.Module):
code
def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, drop=0., attn_drop=0.,
drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, keep_ratio_search=1.0,):
super().__init__()
self.norm1 = norm_layer(dim)
self.attn = Attention(dim, num_heads=num_heads, qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop)
# NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
self.norm2 = norm_layer(dim)
mlp_hidden_dim = int(dim * mlp_ratio)
self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) #from timm.models.layers import Mlp, DropPath, trunc_normal_, lecun_normal_
self.keep_ratio_search = keep_ratio_search
self.adap_t = Bi_direct_adapter()
self.adap2_t = Bi_direct_adapter()
def forward(self, x, xi, global_index_template, global_index_templatei, global_index_search, global_index_searchi, mask=None, ce_template_mask=None, keep_ratio_search=None):
xori = x
x_attn, attn = self.attn(self.norm1(x), mask, True)
x = x + self.drop_path(x_attn) + self.drop_path(self.adap_t(self.norm1(xi))) #########-------------------------adapter
xi_attn, i_attn = self.attn(self.norm1(xi), mask,True)
xi = xi + self.drop_path(xi_attn) + self.drop_path(self.adap_t(self.norm1(xori))) #########-------------------------adapter
lens_t = global_index_template.shape[1]
removed_index_search = None
removed_index_searchi = None
if self.keep_ratio_search < 1 and (keep_ratio_search is None or keep_ratio_search < 1):
keep_ratio_search = self.keep_ratio_search if keep_ratio_search is None else keep_ratio_search
x, global_index_search, removed_index_search = candidate_elimination(attn, x, lens_t, keep_ratio_search, global_index_search, ce_template_mask)
xi, global_index_searchi, removed_index_searchi = candidate_elimination(i_attn, xi, lens_t, keep_ratio_search, global_index_searchi, ce_template_mask)
xori = x
x = x + self.drop_path(self.mlp(self.norm2(x))) + self.drop_path(self.adap2_t(self.norm2(xi))) ###-------adapter
xi = xi + self.drop_path(self.mlp(self.norm2(xi))) + self.drop_path(self.adap2_t(self.norm2(xori))) ###-------adapter
return x, global_index_template, global_index_search, removed_index_search, attn, xi, global_index_templatei, global_index_searchi, removed_index_searchi, i_attn
class Block(nn.Module):
code
def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, drop=0., attn_drop=0.,
drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm):
super().__init__()
self.norm1 = norm_layer(dim)
#print("class Block ")
self.attn = Attention(dim, num_heads=num_heads, qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop)
# NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
self.norm2 = norm_layer(dim)
mlp_hidden_dim = int(dim * mlp_ratio)
self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
def forward(self, x, mask=None):
#print("class Block forward")
x = x + self.drop_path(self.attn(self.norm1(x), mask))
x = x + self.drop_path(self.mlp(self.norm2(x)))
return x ③ import math
import torch
import torch.nn as nn
from timm.models.layers import Mlp, DropPath, trunc_normal_, lecun_normal_
from lib.models.layers.attn import Attention
from lib.models.layers.adapter import Bi_direct_adapter
def candidate_elimination(attn: torch.Tensor, tokens: torch.Tensor, lens_t: int, keep_ratio: float, global_index: torch.Tensor, box_mask_z: torch.Tensor):
"""
Eliminate potential background candidates for computation reduction and noise cancellation.
Args:
attn (torch.Tensor): [B, num_heads, L_t + L_s, L_t + L_s], attention weights
tokens (torch.Tensor): [B, L_t + L_s, C], template and search region tokens
lens_t (int): length of template
keep_ratio (float): keep ratio of search region tokens (candidates)
global_index (torch.Tensor): global index of search region tokens
box_mask_z (torch.Tensor): template mask used to accumulate attention weights
code
Returns:
tokens_new (torch.Tensor): tokens after candidate elimination
keep_index (torch.Tensor): indices of kept search region tokens
removed_index (torch.Tensor): indices of removed search region tokens
"""
lens_s = attn.shape[-1] - lens_t
bs, hn, _, _ = attn.shape
lens_keep = math.ceil(keep_ratio * lens_s)
if lens_keep == lens_s:
return tokens, global_index, None
attn_t = attn[:, :, :lens_t, lens_t:]
#print("box_mask_z")
if box_mask_z is not None:
#print("\n1\n1\n1")
box_mask_z = box_mask_z.unsqueeze(1).unsqueeze(-1).expand(-1, attn_t.shape[1], -1, attn_t.shape[-1])
# attn_t = attn_t[:, :, box_mask_z, :]
attn_t = attn_t[box_mask_z]
attn_t = attn_t.view(bs, hn, -1, lens_s)
attn_t = attn_t.mean(dim=2).mean(dim=1) # B, H, L-T, L_s --> B, L_s
# attn_t = [attn_t[i, :, box_mask_z[i, :], :] for i in range(attn_t.size(0))]
# attn_t = [attn_t[i].mean(dim=1).mean(dim=0) for i in range(len(attn_t))]
# attn_t = torch.stack(attn_t, dim=0)
else:
attn_t = attn_t.mean(dim=2).mean(dim=1) # B, H, L-T, L_s --> B, L_s
# use sort instead of topk, due to the speed issue
# https://github.com/pytorch/pytorch/issues/22812
sorted_attn, indices = torch.sort(attn_t, dim=1, descending=True)
topk_attn, topk_idx = sorted_attn[:, :lens_keep], indices[:, :lens_keep]
non_topk_attn, non_topk_idx = sorted_attn[:, lens_keep:], indices[:, lens_keep:]
keep_index = global_index.gather(dim=1, index=topk_idx)
removed_index = global_index.gather(dim=1, index=non_topk_idx)
# separate template and search tokens
tokens_t = tokens[:, :lens_t]
tokens_s = tokens[:, lens_t:]
# obtain the attentive and inattentive tokens
B, L, C = tokens_s.shape
# topk_idx_ = topk_idx.unsqueeze(-1).expand(B, lens_keep, C)
attentive_tokens = tokens_s.gather(dim=1, index=topk_idx.unsqueeze(-1).expand(B, -1, C))
# inattentive_tokens = tokens_s.gather(dim=1, index=non_topk_idx.unsqueeze(-1).expand(B, -1, C))
# compute the weighted combination of inattentive tokens
# fused_token = non_topk_attn @ inattentive_tokens
# concatenate these tokens
# tokens_new = torch.cat([tokens_t, attentive_tokens, fused_token], dim=0)
tokens_new = torch.cat([tokens_t, attentive_tokens], dim=1)
#print("finish ce func")
return tokens_new, keep_index, removed_index # x, global_index_search, removed_index_search
class DSBlock(nn.Module):
code
def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, drop=0., attn_drop=0.,
drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, keep_ratio_search=1.0,):
super().__init__()
self.norm1 = norm_layer(dim)
self.attn = Attention(dim, num_heads=num_heads, qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop)
# NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
self.norm2 = norm_layer(dim)
mlp_hidden_dim = int(dim * mlp_ratio)
self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) #from timm.models.layers import Mlp, DropPath, trunc_normal_, lecun_normal_
self.keep_ratio_search = keep_ratio_search
def forward(self, x, xi, global_index_template, global_index_templatei, global_index_search, global_index_searchi, mask=None, ce_template_mask=None, keep_ratio_search=None):
x_attn, attn = self.attn(self.norm1(x), mask, True)
x = x + self.drop_path(x_attn)
xi_attn, i_attn = self.attn(self.norm1(xi), mask,True)
xi = xi + self.drop_path(xi_attn)
lens_t = global_index_template.shape[1]
removed_index_search = None
removed_index_searchi = None
if self.keep_ratio_search < 1 and (keep_ratio_search is None or keep_ratio_search < 1):
keep_ratio_search = self.keep_ratio_search if keep_ratio_search is None else keep_ratio_search
x, global_index_search, removed_index_search = candidate_elimination(attn, x, lens_t, keep_ratio_search, global_index_search, ce_template_mask)
xi, global_index_searchi, removed_index_searchi = candidate_elimination(i_attn, xi, lens_t, keep_ratio_search, global_index_searchi, ce_template_mask)
x = x + self.drop_path(self.mlp(self.norm2(x)))
xi = xi + self.drop_path(self.mlp(self.norm2(xi)))
return x, global_index_template, global_index_search, removed_index_search, attn, xi, global_index_templatei, global_index_searchi, removed_index_searchi, i_attn
class Block(nn.Module):
code
def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, drop=0., attn_drop=0.,
drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm):
super().__init__()
self.norm1 = norm_layer(dim)
#print("class Block ")
self.attn = Attention(dim, num_heads=num_heads, qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop)
# NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
self.norm2 = norm_layer(dim)
mlp_hidden_dim = int(dim * mlp_ratio)
self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
def forward(self, x, mask=None):
#print("class Block forward")
x = x + self.drop_path(self.attn(self.norm1(x), mask))
x = x + self.drop_path(self.mlp(self.norm2(x)))
return x ④ import math
import logging
import pdb
from functools import partial
from collections import OrderedDict
from copy import deepcopy
import torch
import torch.nn as nn
import torch.nn.functional as F
from timm.models.layers import to_2tuple
from lib.models.layers.patch_embed import PatchEmbed
from .utils import combine_tokens, recover_tokens, token2feature, feature2token
from .vit import VisionTransformer
from ..layers.attn_blocks import CEBlock, candidate_elimination_adapter
from ..layers.attn_adapt_blocks import CEABlock ##BAT
from ..layers.dualstream_attn_blocks import DSBlock ## Dual Stream without adapter
from lib.models.layers.adapter import Bi_direct_adapter
_logger = logging.getLogger(name)
class VisionTransformerCE(VisionTransformer):
""" Vision Transformer with candidate elimination (CE) module
code
###################################################################===========
# attention mask handling
# B, H, W
if mask_z is not None and mask_x is not None:
mask_z = F.interpolate(mask_z[None].float(), scale_factor=1. / self.patch_size).to(torch.bool)[0]
mask_z = mask_z.flatten(1).unsqueeze(-1)
code
def _create_vision_transformer(pretrained=False, **kwargs):
model = VisionTransformerCE(**kwargs)
code
if pretrained:
if 'npz' in pretrained:
model.load_pretrained(pretrained, prefix='')
else:
checkpoint = torch.load(pretrained, map_location="cpu")
missing_keys, unexpected_keys = model.load_state_dict(checkpoint["net"], strict=False)
print('Load pretrained OSTrack from: ' + pretrained)
print(f"missing_keys: {missing_keys}")
print(f"unexpected_keys: {unexpected_keys}")
return model
def vit_base_patch16_224_ce_adapter(pretrained=False, **kwargs):
""" ViT-Base model (ViT-B/16) from original paper (https://arxiv.org/abs/2010.11929).
"""
model_kwargs = dict(
patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs)
model = _create_vision_transformer(pretrained=pretrained, **model_kwargs)
return model
def vit_large_patch16_224_ce_adapter(pretrained=False, **kwargs):
""" ViT-Large model (ViT-L/16) from original paper (https://arxiv.org/abs/2010.11929).
"""
model_kwargs = dict(
patch_size=16, embed_dim=1024, depth=24, num_heads=16, **kwargs)
model = _create_vision_transformer(pretrained=pretrained, **model_kwargs)
return model 综上代码,再分析Bi_direct_adapter 的作用,以及集成位置。
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
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
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"]:
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)