在此模型: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
import random
import numpy as np
logger = logging.getLogger(name)
class VisionTransformerCE(VisionTransformer):
“”" Vision Transformer with candidate elimination (CE) module
A PyTorch impl of : An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale
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
“”"
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
print(‘shape of event_z before projection:{}, event_x:{}’.format(event_z.shape, event_x.shape))
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)
print(‘shape of event_z:{}, event_x:{}, x:{}, z:{}’.format(event_z.shape,event_x.shape,x.shape,z.shape ))
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)
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)
ex = torch.cat([ex, pad_x], dim=1)
index_all = torch.cat([idex1, idex0], dim=1)
recover original token order
C = ex.shape[-1]
ex = torch.zeros_like(ex).scatter_(dim=1, index=index_all.unsqueeze(-1).expand(B, -1, C).to(torch.int64), src=ex)
x = torch.cat([x,ex],dim=1)
x = recover_tokens(x, lens_z_new, lens_x, mode=self.cat_mode)
event_x = x[:, lens_x:] # RGB head
x = x[:, :lens_x] # RGB head
x = torch.cat([event_x, x], dim=1)
aux_dict = {
“attn”: attn,
“attn”: out_attn,
“removed_indexes_s”: removed_indexes_s, # used for visualization
}
def _create_vision_transformer(pretrained=False, **kwargs):
model = VisionTransformerCE(**kwargs)
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中maksing_fea以及tokens恢复的代码分别是什么?写出来
ex = torch.cat([ex, pad_x], dim=1)
index_all = torch.cat([idex1, idex0], dim=1)
C = ex.shape[-1]
# Recovering the original token order
ex = torch.zeros_like(ex).scatter_(dim=1, index=index_all.unsqueeze(-1).expand(B, -1, C).to(torch.int64), src=ex)
那么现在在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
import random
import numpy as np
from .DCM import Counter_Guide_Enhanced
_logger = logging.getLogger(name)
class VisionTransformerCE(VisionTransformer):
""" Vision Transformer with candidate elimination (CE) module
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 中由于也引入了masking_fea,那么相应的需要将Tokens 恢复逻辑也加进来,那么现在分析一下可以 加在什么位置?
以下是您可以按照此逻辑修改的代码段:
python
def forward_features(self, z, x, event_z, event_x,
mask_z=None, mask_x=None,
ce_template_pass=None, ce_keep_rate=None,
return_last_attn=False):
# Convert and embed patches
x = self.patch_embed(x)
z = self.patch_embed(z)
# Apply position embeddings
x += self.pos_embed_x
z += self.pos_embed_z
event_x = self.pos_embed_event(event_x)
event_x += self.pos_embed_x
event_z = self.pos_embed_event(event_z)
event_z += self.pos_embed_z
# Apply masking feature
masked_z, masked_event_z, masked_x, masked_event_x, token_idx = self.masking_fea(z, event_z, x, event_noir, ratio=0.95)
# Process through blocks
lens_z = z.shape[1]
lens_x = x.shape[1]
for i, blk in enumerate(self.blocks):
x = blk(x)
event_x = blk(event_x)
# Recover the original token order before normalization
x = recover_tokens(x, token_idx['x'], mode='consolidate')
event_x = recover_tokens(event_x, token_idx['ex'], mode='consolidate')
# Normalize the features
x = self.norm(x)
event_x = self.norm(event_x)
# Concatenate or process further if necessary
x_cat = torch.cat([event_x, x], dim=1)
x = x_cat
return x
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]
x = self.patch_embed(x)
z = self.patch_embed(z)
x += self.pos_embed
z += self.pos_embed
event_x = self.pos_embed_event(event_x)
event_z = self.pos_embed_event(event_z)
# Apply random masking and get the indices for restoration
masked_z, masked_event_z, masked_x, masked_event_x, token_idx = self.masking_fea(z, event_z, x, event_x, ratio=0.95)
# Use the masked outputs as inputs for the transformer blocks
x = masked_x
event_x = masked_event_x
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_cut.squeeze(-1)
if self.add_cls_token:
cls_tokens = self.cls_token.expand(B, -1, -1)
if self.dist_token is not None:
dist_tokens = self.dist_token.expand(B, -1, -1)
x = torch.cat((cls_tokens, dist_tokens, x), dim=1)
else:
x = torch.cat((cls_tokens, x), dim=1)
x = self.pos_drop(x)
# Apply transformer blocks
for blk in self.blocks:
x = blk(x)
# Recover the original tokens order before final normalization
x, event_x = recover_tokens(x, event_x, token_idx, mode='consolidate')
# Apply final normalization
x = self.norm(x)
event_x = self.norm(event_x)
# Optionally return attention map for visualization or analysis
if return_last_attn:
x, attn_map = x
return x, attn_map
return x