那么在import math
import logging
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, PatchEmbed_event, xcorr_depthwise
from .utils import combine_tokens, recover_tokens
from .vit import VisionTransformer
from ..layers.attn_blocks import CEBlock
from math import sqrt
_logger = logging.getLogger(name)
class VisionTransformerCE(VisionTransformer):
""" Vision Transformer with candidate elimination (CE) module
import torch
import torch.nn as nn
import torch.nn.functional as F
class BSplineActivation(nn.Module):
def __init__(self, degree=3, num_knots=100):
super(BSplineActivation, self).__init__()
self.degree = degree
self.num_knots = num_knots
# Initialize knots, can be learned or fixed
self.knots = nn.Parameter(torch.linspace(0, 1, num_knots), requires_grad=True)
def forward(self, x):
# Implement B-Spline basis function evaluation
# This is a simplified logic, in a real case it may involve recursively calculating basis splines
# (actual implementation requires more work, like using De Boor's algorithm)
# Here we just simulate a possible spline computation for educational purposes
x = torch.clip(x, 0, 1)
return torch.sin(3.14 * x) # Example complex function, replace with actual B-spline evaluation
# 在模型定义中应用此激活函数
class VisionTransformerCERedesigned(VisionTransformerCE):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# 将B样条激活函数集成到CEBlock或MLP层中
self.act_layer = BSplineActivation()
那么现在在import math
import logging
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, PatchEmbed_event, xcorr_depthwise
from .utils import combine_tokens, recover_tokens
from .vit import VisionTransformer
from ..layers.attn_blocks import CEBlock
from math import sqrt
_logger = logging.getLogger(name)
class VisionTransformerCE(VisionTransformer):
""" Vision Transformer with candidate elimination (CE) module
VisionTransformerCE中采用的CEBlock是: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 math import sqrt
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
实际 B 样条实现:当前的 forward 方法只是简单地应用了 torch.sin(3.14 * x) 暗示一种非线性的复杂函数计算。这实际上并不是 B 样条的计算方式。B 样条的计算通常涉及到多项式的线性组合,根据节点的分段基函数来评估。
B 样条的实现:如果要实现一个真实的 B 样条激活函数,你需要使用节点(knots)来定义 B 样条基函数。这会涉及递归地计算分段多项式,对于每个输入段求和并考虑多项式的权重。
复杂程度:由于 B 样条基函数通常比较复杂,一个简化版的实现可能无法捕捉 B 样条的全部特征。在真实使用中,通常会借助库直接去实现这些,比如 NumPy 的 bisplev 函数,SciPy 中的相关函数,或者直接使用 B 样条相关文献中的实现。
进一步改进建议:
实际计算:研究和实现递归的 De Boor 算法,或者使用有现成工具包去支持 B 样条计算。
测试和验证:对实际实现进行单元测试,以验证其输出与预期的 B 样条函数输出一致。
性能优化:注意在 GPU 上高效地执行数值计算,避免不必要的计算瓶颈。
假如要在这个基础上继续实现完整的 B 样条功能,建议再对 B 样条数学进行详细研究或寻求已有工具的支持。
User
现在根据KAN里面的B样条设计,修改import torch
import torch.nn as nn
import torch.nn.functional as F
class BSplineActivation(nn.Module):
def init(self, degree=3, num_knots=100):
super(BSplineActivation, self).init()
self.degree = degree
self.num_knots = num_knots
# Initialize knots, can be learned or fixed
self.knots = nn.Parameter(torch.linspace(0, 1, num_knots), requires_grad=True)
code
def forward(self, x):
x = torch.clip(x, 0, 1)
return torch.sin(3.14 * x) # Example complex function, replace with actual B-spline evaluation
Assistant
要根据 KAN 中的 B 样条设计来修改您的 BSplineActivation 类,我们需要强调真正的 B 样条基函数计算。在 B 样条中,通常通过基础多项式结合节点(knots)实现输入特征的非线性转换。以下是修改后的示例,尽管实现完整的 B 样条算法相当复杂,以下代码提供了一个基础框架和示例,用于演示如何通过节点和权重线性组合来实现一种可能的基函数激活。
python
import torch
import torch.nn as nn
class BSplineActivation(nn.Module):
def __init__(self, degree=3, num_knots=100):
super(BSplineActivation, self).__init__()
self.degree = degree
self.num_knots = num_knots
# Initialize knots as a learnable parameter
self.knots = nn.Parameter(torch.linspace(0, 1, num_knots), requires_grad=True)
self.weights = nn.Parameter(torch.randn(num_knots), requires_grad=True)
def forward(self, x):
# Ensure input tensor is in the range [0, 1]
x = torch.clip(x, 0, 1)
# Compute B-spline basis functions (example approximation)
b_spline_values = self.compute_bspline_basis(x)
# Compute the activation value based on B-spline basis
activation = torch.matmul(b_spline_values, self.weights)
return activation
def compute_bspline_basis(self, x):
# Simplified illustration of computing B-spline basis for input tensor x
# Compute the basis function values for each knot interval
# This is a simplified example, actual B-spline computation would be more complex
n = self.num_knots
degree = self.degree
basis = torch.zeros(x.size(0), n)
for i in range(n - degree):
# Calculate basis values for each interval using a simple linear method
left = i
right = i + degree + 1
in_interval = (x.unsqueeze(1) >= self.knots[left]) & (x.unsqueeze(1) < self.knots[right])
basis[:, i] = in_interval.float() * (1 - (x.unsqueeze(1) - self.knots[left]) / (self.knots[right] - self.knots[left]))
return basis
解释:
初始化:
knots 和 weights 是可学习的参数,表示节点和相应多项式的权重。
前向传播:
在 forward 方法中,将输入 x 限制到 [0, 1] 范围。
compute_bspline_basis 应实现 B 样条基函数的计算,此处提供了一个非常简化的线性近似,实际情况应该根据具体 B 样条特性和应用进行复杂实现。
B 样条基函数计算:
compute_bspline_basis 是一个简化的示例说明。需要实现 B 样条基函数的形式,通常使用递归定义,处理多个节点之间的多项式关系。
A PyTorch impl of : `An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale`
- https://arxiv.org/abs/2010.11929
Includes distillation token & head support for `DeiT: Data-efficient Image Transformers`
- https://arxiv.org/abs/2012.12877
"""
def __init__(self, img_size=224, patch_size=16, in_chans=3, num_classes=1000, embed_dim=768, depth=12,
num_heads=12, mlp_ratio=4., qkv_bias=True, representation_size=None, distilled=False,
drop_rate=0., attn_drop_rate=0., drop_path_rate=0., embed_layer=PatchEmbed, norm_layer=None,
act_layer=None, weight_init='',
ce_loc=None, ce_keep_ratio=None):
"""
Args:
img_size (int, tuple): input image size
patch_size (int, tuple): patch size
in_chans (int): number of input channels
num_classes (int): number of classes for classification head
embed_dim (int): embedding dimension
depth (int): depth of transformer
num_heads (int): number of attention heads
mlp_ratio (int): ratio of mlp hidden dim to embedding dim
qkv_bias (bool): enable bias for qkv if True
representation_size (Optional[int]): enable and set representation layer (pre-logits) to this value if set
distilled (bool): model includes a distillation token and head as in DeiT models
drop_rate (float): dropout rate
attn_drop_rate (float): attention dropout rate
drop_path_rate (float): stochastic depth rate
embed_layer (nn.Module): patch embedding layer
norm_layer: (nn.Module): normalization layer
weight_init: (str): weight init scheme
"""
# super().__init__()
super().__init__()
if isinstance(img_size, tuple):
self.img_size = img_size
else:
self.img_size = to_2tuple(img_size)
self.patch_size = patch_size
self.in_chans = in_chans
self.num_classes = num_classes
self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
self.num_tokens = 2 if distilled else 1
norm_layer = norm_layer or partial(nn.LayerNorm, eps=1e-6)
act_layer = act_layer or nn.GELU
self.patch_embed = embed_layer(
img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim)
num_patches = self.patch_embed.num_patches
self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
self.dist_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) if distilled else None
self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + self.num_tokens, embed_dim))
self.pos_drop = nn.Dropout(p=drop_rate)
self.pos_embed_event = PatchEmbed_event(in_chans=32, embed_dim=768, kernel_size=4, stride=4)
# self.pos_embed_event = PatchEmbed_event(in_chans=32, embed_dim=768, kernel_size=4, stride=4)
# self.pos_embed_event_z = PatchEmbed_event(in_chans=32, embed_dim=768, kernel_size=3, stride=1)
# attn = CrossAttn(768, 4, 3072, 0.1, 'relu')
# self.cross_attn = Iter_attn(attn, 2)
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
blocks = []
ce_index = 0
self.ce_loc = ce_loc
for i in range(depth):
ce_keep_ratio_i = 1.0
if ce_loc is not None and i in ce_loc:
ce_keep_ratio_i = ce_keep_ratio[ce_index]
ce_index += 1
blocks.append(
CEBlock(
dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, drop=drop_rate,
attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer, act_layer=act_layer,
keep_ratio_search=ce_keep_ratio_i)
)
self.blocks = nn.Sequential(*blocks)
# hopufield_layer
num_prototype = 1000
self.lookup = nn.Linear(embed_dim, num_prototype ,bias=False)
self.beta = 1./sqrt(embed_dim)
self.content = nn.Sequential(
nn.Linear(num_prototype, embed_dim,bias=False),
nn.LayerNorm(embed_dim),
)
##############################################################
self.norm = norm_layer(embed_dim)
self.init_weights(weight_init)
def forward_features(self, z, x, event_z, event_x,
mask_z=None, mask_x=None,
ce_template_mask=None, ce_keep_rate=None,
return_last_attn=False
):
B, H, W = x.shape[0], x.shape[2], x.shape[3]
event_z = self.pos_embed_event(event_z) # [:,:,:,:1000]
event_x = self.pos_embed_event(event_x) # B 768 1024
x = self.patch_embed(x)
z = self.patch_embed(z)
event_z += self.pos_embed_z
event_x += self.pos_embed_x
z += self.pos_embed_z
x += self.pos_embed_x
# 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)
mask_x = F.interpolate(mask_x[None].float(), scale_factor=1. / self.patch_size).to(torch.bool)[0]
mask_x = mask_x.flatten(1).unsqueeze(-1)
mask_x = combine_tokens(mask_z, mask_x, mode=self.cat_mode)
mask_x = mask_x.squeeze(-1)
if self.add_cls_token:
cls_tokens = self.cls_token.expand(B, -1, -1)
cls_tokens = cls_tokens + self.cls_pos_embed
if self.add_sep_seg:
x += self.search_segment_pos_embed
z += self.template_segment_pos_embed
x = combine_tokens(z, event_z, x, event_x, mode=self.cat_mode) # 64+64+256+256=640
# x = combine_tokens(z, x, event_z, event_x, mode=self.cat_mode) # 64+64+256+256=640
if self.add_cls_token:
x = torch.cat([cls_tokens, x], dim=1)
x = self.pos_drop(x)
lens_z = self.pos_embed_z.shape[1]
lens_x = self.pos_embed_x.shape[1]
global_index_t = torch.linspace(0, lens_z - 1, lens_z).to(x.device)
global_index_t = global_index_t.repeat(B, 1)
global_index_s = torch.linspace(0, lens_x - 1, lens_x).to(x.device)
global_index_s = global_index_s.repeat(B, 1)
removed_indexes_s = []
for i, blk in enumerate(self.blocks):
x, global_index_t, global_index_s, removed_index_s, attn = \
blk(x, global_index_t, global_index_s, mask_x, ce_template_mask, ce_keep_rate, i)
if self.ce_loc is not None and i in self.ce_loc:
removed_indexes_s.append(removed_index_s)
# The last hopufield layer
x = torch.softmax(self.lookup(x)*self.beta, dim=-1)
x = self.content(x)
x = self.norm(x)
lens_x_new = global_index_s.shape[1]
lens_z_new = global_index_t.shape[1]
z = x[:, :lens_z_new*2]
x = x[:, lens_z_new*2:]
if removed_indexes_s and removed_indexes_s[0] is not None:
removed_indexes_cat = torch.cat(removed_indexes_s, dim=1)
pruned_lens_x = lens_x - lens_x_new
pad_x = torch.zeros([B, pruned_lens_x, x.shape[2]], device=x.device)
x = torch.cat([x, pad_x], dim=1)
index_all = torch.cat([global_index_s, removed_indexes_cat], dim=1)
# recover original token order
C = x.shape[-1]
x = torch.zeros_like(x).scatter_(dim=1, index=index_all.unsqueeze(-1).expand(B, -1, C).to(torch.int64), src=x)
x = recover_tokens(x, lens_z_new, lens_x, mode=self.cat_mode)
x = x[:, :lens_x] # RGB head
x = torch.cat([event_x, x], dim=1)
# x = x[:, lens_x//2:] # event head
# x = torch.cat([z, x], dim=1)
# re-concatenate with the template, which may be further used by other modules
# x, event_x = x[:, :lens_x//2], x[:, lens_x//2:]
# x = x[:, -lens_x//2:]
aux_dict = {
"attn": attn,
"removed_indexes_s": removed_indexes_s, # used for visualization
}
return x, aux_dict
def forward(self, z, x, event_z, event_x,
ce_template_mask=None, ce_keep_rate=None,
tnc_keep_rate=None,
return_last_attn=False):
x, aux_dict = self.forward_features(z, x, event_z, event_x, ce_template_mask=ce_template_mask, ce_keep_rate=ce_keep_rate,)
return x, aux_dict
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["model"], strict=False)
print('Load pretrained model from: ' + pretrained)
return model
def vit_base_patch16_224_ce(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(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
中,如何将B样条集成进去?
A PyTorch impl of : `An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale`
- https://arxiv.org/abs/2010.11929
Includes distillation token & head support for `DeiT: Data-efficient Image Transformers`
- https://arxiv.org/abs/2012.12877
"""
def __init__(self, img_size=224, patch_size=16, in_chans=3, num_classes=1000, embed_dim=768, depth=12,
num_heads=12, mlp_ratio=4., qkv_bias=True, representation_size=None, distilled=False,
drop_rate=0., attn_drop_rate=0., drop_path_rate=0., embed_layer=PatchEmbed, norm_layer=None,
act_layer=None, weight_init='',
ce_loc=None, ce_keep_ratio=None):
"""
Args:
img_size (int, tuple): input image size
patch_size (int, tuple): patch size
in_chans (int): number of input channels
num_classes (int): number of classes for classification head
embed_dim (int): embedding dimension
depth (int): depth of transformer
num_heads (int): number of attention heads
mlp_ratio (int): ratio of mlp hidden dim to embedding dim
qkv_bias (bool): enable bias for qkv if True
representation_size (Optional[int]): enable and set representation layer (pre-logits) to this value if set
distilled (bool): model includes a distillation token and head as in DeiT models
drop_rate (float): dropout rate
attn_drop_rate (float): attention dropout rate
drop_path_rate (float): stochastic depth rate
embed_layer (nn.Module): patch embedding layer
norm_layer: (nn.Module): normalization layer
weight_init: (str): weight init scheme
"""
# super().__init__()
super().__init__()
if isinstance(img_size, tuple):
self.img_size = img_size
else:
self.img_size = to_2tuple(img_size)
self.patch_size = patch_size
self.in_chans = in_chans
self.num_classes = num_classes
self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
self.num_tokens = 2 if distilled else 1
norm_layer = norm_layer or partial(nn.LayerNorm, eps=1e-6)
act_layer = act_layer or nn.GELU
self.patch_embed = embed_layer(
img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim)
num_patches = self.patch_embed.num_patches
self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
self.dist_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) if distilled else None
self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + self.num_tokens, embed_dim))
self.pos_drop = nn.Dropout(p=drop_rate)
self.pos_embed_event = PatchEmbed_event(in_chans=32, embed_dim=768, kernel_size=4, stride=4)
# self.pos_embed_event = PatchEmbed_event(in_chans=32, embed_dim=768, kernel_size=4, stride=4)
# self.pos_embed_event_z = PatchEmbed_event(in_chans=32, embed_dim=768, kernel_size=3, stride=1)
# attn = CrossAttn(768, 4, 3072, 0.1, 'relu')
# self.cross_attn = Iter_attn(attn, 2)
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
blocks = []
ce_index = 0
self.ce_loc = ce_loc
for i in range(depth):
ce_keep_ratio_i = 1.0
if ce_loc is not None and i in ce_loc:
ce_keep_ratio_i = ce_keep_ratio[ce_index]
ce_index += 1
blocks.append(
CEBlock(
dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, drop=drop_rate,
attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer, act_layer=act_layer,
keep_ratio_search=ce_keep_ratio_i)
)
self.blocks = nn.Sequential(*blocks)
# hopufield_layer
num_prototype = 1000
self.lookup = nn.Linear(embed_dim, num_prototype ,bias=False)
self.beta = 1./sqrt(embed_dim)
self.content = nn.Sequential(
nn.Linear(num_prototype, embed_dim,bias=False),
nn.LayerNorm(embed_dim),
)
self.norm = norm_layer(embed_dim)
self.init_weights(weight_init)
def forward_features(self, z, x, event_z, event_x,
mask_z=None, mask_x=None,
ce_template_mask=None, ce_keep_rate=None,
return_last_attn=False
):
B, H, W = x.shape[0], x.shape[2], x.shape[3]
event_z = self.pos_embed_event(event_z) # [:,:,:,:1000]
event_x = self.pos_embed_event(event_x) # B 768 1024
x = self.patch_embed(x)
z = self.patch_embed(z)
event_z += self.pos_embed_z
event_x += self.pos_embed_x
z += self.pos_embed_z
x += self.pos_embed_x
# 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)
mask_x = F.interpolate(mask_x[None].float(), scale_factor=1. / self.patch_size).to(torch.bool)[0]
mask_x = mask_x.flatten(1).unsqueeze(-1)
mask_x = combine_tokens(mask_z, mask_x, mode=self.cat_mode)
mask_x = mask_x.squeeze(-1)
if self.add_cls_token:
cls_tokens = self.cls_token.expand(B, -1, -1)
cls_tokens = cls_tokens + self.cls_pos_embed
if self.add_sep_seg:
x += self.search_segment_pos_embed
z += self.template_segment_pos_embed
x = combine_tokens(z, event_z, x, event_x, mode=self.cat_mode) # 64+64+256+256=640
# x = combine_tokens(z, x, event_z, event_x, mode=self.cat_mode) # 64+64+256+256=640
if self.add_cls_token:
x = torch.cat([cls_tokens, x], dim=1)
x = self.pos_drop(x)
lens_z = self.pos_embed_z.shape[1]
lens_x = self.pos_embed_x.shape[1]
global_index_t = torch.linspace(0, lens_z - 1, lens_z).to(x.device)
global_index_t = global_index_t.repeat(B, 1)
global_index_s = torch.linspace(0, lens_x - 1, lens_x).to(x.device)
global_index_s = global_index_s.repeat(B, 1)
removed_indexes_s = []
for i, blk in enumerate(self.blocks):
x, global_index_t, global_index_s, removed_index_s, attn = \
blk(x, global_index_t, global_index_s, mask_x, ce_template_mask, ce_keep_rate, i)
if self.ce_loc is not None and i in self.ce_loc:
removed_indexes_s.append(removed_index_s)
# The last hopufield layer
x = torch.softmax(self.lookup(x)*self.beta, dim=-1)
x = self.content(x)
x = self.norm(x)
lens_x_new = global_index_s.shape[1]
lens_z_new = global_index_t.shape[1]
z = x[:, :lens_z_new*2]
x = x[:, lens_z_new*2:]
if removed_indexes_s and removed_indexes_s[0] is not None:
removed_indexes_cat = torch.cat(removed_indexes_s, dim=1)
pruned_lens_x = lens_x - lens_x_new
pad_x = torch.zeros([B, pruned_lens_x, x.shape[2]], device=x.device)
x = torch.cat([x, pad_x], dim=1)
index_all = torch.cat([global_index_s, removed_indexes_cat], dim=1)
# recover original token order
C = x.shape[-1]
x = torch.zeros_like(x).scatter_(dim=1, index=index_all.unsqueeze(-1).expand(B, -1, C).to(torch.int64), src=x)
x = recover_tokens(x, lens_z_new, lens_x, mode=self.cat_mode)
x = x[:, :lens_x] # RGB head
x = torch.cat([event_x, x], dim=1)
aux_dict = {
"attn": attn,
"removed_indexes_s": removed_indexes_s, # used for visualization
}
return x, aux_dict
def forward(self, z, x, event_z, event_x,
ce_template_mask=None, ce_keep_rate=None,
tnc_keep_rate=None,
return_last_attn=False):
x, aux_dict = self.forward_features(z, x, event_z, event_x, ce_template_mask=ce_template_mask, ce_keep_rate=ce_keep_rate,)
return x, aux_dict
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["model"], strict=False)
print('Load pretrained model from: ' + pretrained)
return model
def vit_base_patch16_224_ce(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(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
中,如何将上文中的B样条集成进来,分析以下KAN和visionTransformer的区别和联系,KAN有何优势?
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:
box_mask_z = box_mask_z.unsqueeze(1).unsqueeze(-1).expand(-1, attn_t.shape[1], -1, attn_t.shape[-1])
box_mask_z = torch.cat([box_mask_z, box_mask_z], dim=-2)
# 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)
return tokens_new, keep_index, removed_index