2021-08-17 14:16:55 +08:00
|
|
|
# Copyright (c) OpenMMLab. All rights reserved.
|
2021-04-22 11:19:55 +08:00
|
|
|
import math
|
2021-06-20 06:53:13 +08:00
|
|
|
import warnings
|
2021-04-22 11:19:55 +08:00
|
|
|
|
|
|
|
import torch
|
|
|
|
import torch.nn as nn
|
2022-04-01 21:01:45 +08:00
|
|
|
import torch.utils.checkpoint as cp
|
2021-12-06 19:59:33 +08:00
|
|
|
from mmcv.cnn import build_norm_layer
|
2021-06-18 01:41:25 +08:00
|
|
|
from mmcv.cnn.bricks.transformer import FFN, MultiheadAttention
|
2021-12-06 19:59:33 +08:00
|
|
|
from mmcv.cnn.utils.weight_init import (constant_init, kaiming_init,
|
|
|
|
trunc_normal_)
|
2022-02-09 13:52:42 +08:00
|
|
|
from mmcv.runner import (BaseModule, CheckpointLoader, ModuleList,
|
|
|
|
load_state_dict)
|
2021-06-18 01:41:25 +08:00
|
|
|
from torch.nn.modules.batchnorm import _BatchNorm
|
|
|
|
from torch.nn.modules.utils import _pair as to_2tuple
|
2021-04-22 11:19:55 +08:00
|
|
|
|
2021-07-28 16:56:22 +08:00
|
|
|
from mmseg.ops import resize
|
2021-04-22 11:19:55 +08:00
|
|
|
from mmseg.utils import get_root_logger
|
|
|
|
from ..builder import BACKBONES
|
2021-08-26 06:00:41 +08:00
|
|
|
from ..utils import PatchEmbed
|
2021-04-22 11:19:55 +08:00
|
|
|
|
|
|
|
|
2021-06-18 01:41:25 +08:00
|
|
|
class TransformerEncoderLayer(BaseModule):
|
|
|
|
"""Implements one encoder layer in Vision Transformer.
|
2021-04-22 11:19:55 +08:00
|
|
|
|
|
|
|
Args:
|
2021-06-24 00:39:29 +08:00
|
|
|
embed_dims (int): The feature dimension.
|
|
|
|
num_heads (int): Parallel attention heads.
|
|
|
|
feedforward_channels (int): The hidden dimension for FFNs.
|
2021-06-18 01:41:25 +08:00
|
|
|
drop_rate (float): Probability of an element to be zeroed
|
2021-06-24 00:39:29 +08:00
|
|
|
after the feed forward layer. Default: 0.0.
|
2021-06-18 01:41:25 +08:00
|
|
|
attn_drop_rate (float): The drop out rate for attention layer.
|
2021-06-24 00:39:29 +08:00
|
|
|
Default: 0.0.
|
2021-06-18 01:41:25 +08:00
|
|
|
drop_path_rate (float): stochastic depth rate. Default 0.0.
|
2021-06-24 00:39:29 +08:00
|
|
|
num_fcs (int): The number of fully-connected layers for FFNs.
|
|
|
|
Default: 2.
|
|
|
|
qkv_bias (bool): enable bias for qkv if True. Default: True
|
|
|
|
act_cfg (dict): The activation config for FFNs.
|
2021-10-13 21:21:17 +08:00
|
|
|
Default: dict(type='GELU').
|
2021-06-24 00:39:29 +08:00
|
|
|
norm_cfg (dict): Config dict for normalization layer.
|
|
|
|
Default: dict(type='LN').
|
2021-06-18 01:41:25 +08:00
|
|
|
batch_first (bool): Key, Query and Value are shape of
|
|
|
|
(batch, n, embed_dim)
|
2021-06-24 00:39:29 +08:00
|
|
|
or (n, batch, embed_dim). Default: True.
|
2022-04-01 21:01:45 +08:00
|
|
|
with_cp (bool): Use checkpoint or not. Using checkpoint will save
|
|
|
|
some memory while slowing down the training speed. Default: False.
|
2021-04-22 11:19:55 +08:00
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self,
|
2021-06-18 01:41:25 +08:00
|
|
|
embed_dims,
|
2021-04-22 11:19:55 +08:00
|
|
|
num_heads,
|
2021-06-18 01:41:25 +08:00
|
|
|
feedforward_channels,
|
|
|
|
drop_rate=0.,
|
|
|
|
attn_drop_rate=0.,
|
|
|
|
drop_path_rate=0.,
|
|
|
|
num_fcs=2,
|
|
|
|
qkv_bias=True,
|
2021-04-22 11:19:55 +08:00
|
|
|
act_cfg=dict(type='GELU'),
|
2021-06-18 01:41:25 +08:00
|
|
|
norm_cfg=dict(type='LN'),
|
2022-04-01 21:01:45 +08:00
|
|
|
batch_first=True,
|
|
|
|
with_cp=False):
|
2021-06-18 01:41:25 +08:00
|
|
|
super(TransformerEncoderLayer, self).__init__()
|
|
|
|
|
|
|
|
self.norm1_name, norm1 = build_norm_layer(
|
|
|
|
norm_cfg, embed_dims, postfix=1)
|
|
|
|
self.add_module(self.norm1_name, norm1)
|
|
|
|
|
|
|
|
self.attn = MultiheadAttention(
|
|
|
|
embed_dims=embed_dims,
|
|
|
|
num_heads=num_heads,
|
|
|
|
attn_drop=attn_drop_rate,
|
|
|
|
proj_drop=drop_rate,
|
|
|
|
dropout_layer=dict(type='DropPath', drop_prob=drop_path_rate),
|
|
|
|
batch_first=batch_first,
|
|
|
|
bias=qkv_bias)
|
|
|
|
|
|
|
|
self.norm2_name, norm2 = build_norm_layer(
|
|
|
|
norm_cfg, embed_dims, postfix=2)
|
|
|
|
self.add_module(self.norm2_name, norm2)
|
|
|
|
|
|
|
|
self.ffn = FFN(
|
|
|
|
embed_dims=embed_dims,
|
|
|
|
feedforward_channels=feedforward_channels,
|
|
|
|
num_fcs=num_fcs,
|
|
|
|
ffn_drop=drop_rate,
|
2021-06-24 00:39:29 +08:00
|
|
|
dropout_layer=dict(type='DropPath', drop_prob=drop_path_rate),
|
2021-06-18 01:41:25 +08:00
|
|
|
act_cfg=act_cfg)
|
|
|
|
|
2022-04-01 21:01:45 +08:00
|
|
|
self.with_cp = with_cp
|
|
|
|
|
2021-06-18 01:41:25 +08:00
|
|
|
@property
|
|
|
|
def norm1(self):
|
|
|
|
return getattr(self, self.norm1_name)
|
|
|
|
|
|
|
|
@property
|
|
|
|
def norm2(self):
|
|
|
|
return getattr(self, self.norm2_name)
|
2021-04-22 11:19:55 +08:00
|
|
|
|
|
|
|
def forward(self, x):
|
2022-04-01 21:01:45 +08:00
|
|
|
|
|
|
|
def _inner_forward(x):
|
|
|
|
x = self.attn(self.norm1(x), identity=x)
|
|
|
|
x = self.ffn(self.norm2(x), identity=x)
|
|
|
|
return x
|
|
|
|
|
|
|
|
if self.with_cp and x.requires_grad:
|
|
|
|
x = cp.checkpoint(_inner_forward, x)
|
|
|
|
else:
|
|
|
|
x = _inner_forward(x)
|
2021-06-18 01:41:25 +08:00
|
|
|
return x
|
2021-04-22 11:19:55 +08:00
|
|
|
|
|
|
|
|
|
|
|
@BACKBONES.register_module()
|
2021-06-17 12:41:29 +08:00
|
|
|
class VisionTransformer(BaseModule):
|
2021-06-18 01:41:25 +08:00
|
|
|
"""Vision Transformer.
|
2021-04-22 11:19:55 +08:00
|
|
|
|
2021-09-02 17:06:43 +08:00
|
|
|
This backbone is the implementation of `An Image is Worth 16x16 Words:
|
|
|
|
Transformers for Image Recognition at
|
|
|
|
Scale <https://arxiv.org/abs/2010.11929>`_.
|
2021-04-22 11:19:55 +08:00
|
|
|
|
|
|
|
Args:
|
2021-06-18 01:41:25 +08:00
|
|
|
img_size (int | tuple): Input image size. Default: 224.
|
|
|
|
patch_size (int): The patch size. Default: 16.
|
|
|
|
in_channels (int): Number of input channels. Default: 3.
|
|
|
|
embed_dims (int): embedding dimension. Default: 768.
|
|
|
|
num_layers (int): depth of transformer. Default: 12.
|
2021-04-22 11:19:55 +08:00
|
|
|
num_heads (int): number of attention heads. Default: 12.
|
2021-05-01 01:37:47 +08:00
|
|
|
mlp_ratio (int): ratio of mlp hidden dim to embedding dim.
|
|
|
|
Default: 4.
|
|
|
|
out_indices (list | tuple | int): Output from which stages.
|
|
|
|
Default: -1.
|
2021-04-22 11:19:55 +08:00
|
|
|
qkv_bias (bool): enable bias for qkv if True. Default: True.
|
2021-06-18 01:41:25 +08:00
|
|
|
drop_rate (float): Probability of an element to be zeroed.
|
|
|
|
Default 0.0
|
|
|
|
attn_drop_rate (float): The drop out rate for attention layer.
|
|
|
|
Default 0.0
|
|
|
|
drop_path_rate (float): stochastic depth rate. Default 0.0
|
2021-07-20 00:27:10 +08:00
|
|
|
with_cls_token (bool): Whether concatenating class token into image
|
|
|
|
tokens as transformer input. Default: True.
|
|
|
|
output_cls_token (bool): Whether output the cls_token. If set True,
|
|
|
|
`with_cls_token` must be True. Default: False.
|
2021-04-22 11:19:55 +08:00
|
|
|
norm_cfg (dict): Config dict for normalization layer.
|
2021-06-18 01:41:25 +08:00
|
|
|
Default: dict(type='LN')
|
|
|
|
act_cfg (dict): The activation config for FFNs.
|
2021-10-13 21:21:17 +08:00
|
|
|
Default: dict(type='GELU').
|
2021-06-20 06:53:13 +08:00
|
|
|
patch_norm (bool): Whether to add a norm in PatchEmbed Block.
|
|
|
|
Default: False.
|
|
|
|
final_norm (bool): Whether to add a additional layer to normalize
|
2021-05-01 01:37:47 +08:00
|
|
|
final feature map. Default: False.
|
|
|
|
interpolate_mode (str): Select the interpolate mode for position
|
|
|
|
embeding vector resize. Default: bicubic.
|
2021-06-18 01:41:25 +08:00
|
|
|
num_fcs (int): The number of fully-connected layers for FFNs.
|
|
|
|
Default: 2.
|
|
|
|
norm_eval (bool): Whether to set norm layers to eval mode, namely,
|
|
|
|
freeze running stats (mean and var). Note: Effect on Batch Norm
|
|
|
|
and its variants only. Default: False.
|
|
|
|
with_cp (bool): Use checkpoint or not. Using checkpoint will save
|
|
|
|
some memory while slowing down the training speed. Default: False.
|
2021-06-20 06:53:13 +08:00
|
|
|
pretrained (str, optional): model pretrained path. Default: None.
|
|
|
|
init_cfg (dict or list[dict], optional): Initialization config dict.
|
|
|
|
Default: None.
|
2021-04-22 11:19:55 +08:00
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self,
|
2021-06-18 01:41:25 +08:00
|
|
|
img_size=224,
|
2021-04-22 11:19:55 +08:00
|
|
|
patch_size=16,
|
|
|
|
in_channels=3,
|
2021-06-18 01:41:25 +08:00
|
|
|
embed_dims=768,
|
|
|
|
num_layers=12,
|
2021-04-22 11:19:55 +08:00
|
|
|
num_heads=12,
|
|
|
|
mlp_ratio=4,
|
2021-06-24 00:39:29 +08:00
|
|
|
out_indices=-1,
|
2021-04-22 11:19:55 +08:00
|
|
|
qkv_bias=True,
|
|
|
|
drop_rate=0.,
|
|
|
|
attn_drop_rate=0.,
|
2021-05-01 01:37:47 +08:00
|
|
|
drop_path_rate=0.,
|
2021-06-18 01:41:25 +08:00
|
|
|
with_cls_token=True,
|
2021-07-20 00:27:10 +08:00
|
|
|
output_cls_token=False,
|
2021-06-18 01:41:25 +08:00
|
|
|
norm_cfg=dict(type='LN'),
|
2021-04-22 11:19:55 +08:00
|
|
|
act_cfg=dict(type='GELU'),
|
2021-06-20 06:53:13 +08:00
|
|
|
patch_norm=False,
|
2021-05-01 01:37:47 +08:00
|
|
|
final_norm=False,
|
|
|
|
interpolate_mode='bicubic',
|
2021-06-18 01:41:25 +08:00
|
|
|
num_fcs=2,
|
|
|
|
norm_eval=False,
|
2021-06-17 12:41:29 +08:00
|
|
|
with_cp=False,
|
2021-06-20 06:53:13 +08:00
|
|
|
pretrained=None,
|
|
|
|
init_cfg=None):
|
2021-11-04 01:36:09 +08:00
|
|
|
super(VisionTransformer, self).__init__(init_cfg=init_cfg)
|
2021-06-18 01:41:25 +08:00
|
|
|
|
|
|
|
if isinstance(img_size, int):
|
|
|
|
img_size = to_2tuple(img_size)
|
|
|
|
elif isinstance(img_size, tuple):
|
|
|
|
if len(img_size) == 1:
|
|
|
|
img_size = to_2tuple(img_size[0])
|
|
|
|
assert len(img_size) == 2, \
|
|
|
|
f'The size of image should have length 1 or 2, ' \
|
|
|
|
f'but got {len(img_size)}'
|
2021-06-17 12:41:29 +08:00
|
|
|
|
2021-07-20 00:27:10 +08:00
|
|
|
if output_cls_token:
|
|
|
|
assert with_cls_token is True, f'with_cls_token must be True if' \
|
|
|
|
f'set output_cls_token to True, but got {with_cls_token}'
|
2021-06-20 06:53:13 +08:00
|
|
|
|
2021-11-04 01:36:09 +08:00
|
|
|
assert not (init_cfg and pretrained), \
|
|
|
|
'init_cfg and pretrained cannot be set at the same time'
|
|
|
|
if isinstance(pretrained, str):
|
|
|
|
warnings.warn('DeprecationWarning: pretrained is deprecated, '
|
2021-06-20 06:53:13 +08:00
|
|
|
'please use "init_cfg" instead')
|
2021-11-04 01:36:09 +08:00
|
|
|
self.init_cfg = dict(type='Pretrained', checkpoint=pretrained)
|
|
|
|
elif pretrained is not None:
|
2021-06-20 06:53:13 +08:00
|
|
|
raise TypeError('pretrained must be a str or None')
|
|
|
|
|
2021-04-22 11:19:55 +08:00
|
|
|
self.img_size = img_size
|
|
|
|
self.patch_size = patch_size
|
2021-06-20 06:53:13 +08:00
|
|
|
self.interpolate_mode = interpolate_mode
|
|
|
|
self.norm_eval = norm_eval
|
|
|
|
self.with_cp = with_cp
|
|
|
|
self.pretrained = pretrained
|
2021-06-18 01:41:25 +08:00
|
|
|
|
2021-04-22 11:19:55 +08:00
|
|
|
self.patch_embed = PatchEmbed(
|
|
|
|
in_channels=in_channels,
|
2021-06-24 00:39:29 +08:00
|
|
|
embed_dims=embed_dims,
|
2021-07-01 23:41:55 +08:00
|
|
|
conv_type='Conv2d',
|
|
|
|
kernel_size=patch_size,
|
|
|
|
stride=patch_size,
|
2021-09-29 08:46:33 +08:00
|
|
|
padding='corner',
|
2021-07-01 23:41:55 +08:00
|
|
|
norm_cfg=norm_cfg if patch_norm else None,
|
|
|
|
init_cfg=None,
|
|
|
|
)
|
2021-06-20 06:53:13 +08:00
|
|
|
|
2021-06-24 00:39:29 +08:00
|
|
|
num_patches = (img_size[0] // patch_size) * \
|
|
|
|
(img_size[1] // patch_size)
|
2021-04-22 11:19:55 +08:00
|
|
|
|
2021-05-01 01:37:47 +08:00
|
|
|
self.with_cls_token = with_cls_token
|
2021-07-20 00:27:10 +08:00
|
|
|
self.output_cls_token = output_cls_token
|
2021-06-18 01:41:25 +08:00
|
|
|
self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dims))
|
2021-04-22 11:19:55 +08:00
|
|
|
self.pos_embed = nn.Parameter(
|
2021-06-18 01:41:25 +08:00
|
|
|
torch.zeros(1, num_patches + 1, embed_dims))
|
|
|
|
self.drop_after_pos = nn.Dropout(p=drop_rate)
|
2021-04-22 11:19:55 +08:00
|
|
|
|
2021-05-01 01:37:47 +08:00
|
|
|
if isinstance(out_indices, int):
|
2021-06-24 00:39:29 +08:00
|
|
|
if out_indices == -1:
|
|
|
|
out_indices = num_layers - 1
|
2021-05-01 01:37:47 +08:00
|
|
|
self.out_indices = [out_indices]
|
|
|
|
elif isinstance(out_indices, list) or isinstance(out_indices, tuple):
|
|
|
|
self.out_indices = out_indices
|
|
|
|
else:
|
|
|
|
raise TypeError('out_indices must be type of int, list or tuple')
|
|
|
|
|
2021-06-18 01:41:25 +08:00
|
|
|
dpr = [
|
|
|
|
x.item() for x in torch.linspace(0, drop_path_rate, num_layers)
|
|
|
|
] # stochastic depth decay rule
|
|
|
|
|
|
|
|
self.layers = ModuleList()
|
|
|
|
for i in range(num_layers):
|
|
|
|
self.layers.append(
|
|
|
|
TransformerEncoderLayer(
|
|
|
|
embed_dims=embed_dims,
|
|
|
|
num_heads=num_heads,
|
|
|
|
feedforward_channels=mlp_ratio * embed_dims,
|
|
|
|
attn_drop_rate=attn_drop_rate,
|
|
|
|
drop_rate=drop_rate,
|
|
|
|
drop_path_rate=dpr[i],
|
|
|
|
num_fcs=num_fcs,
|
|
|
|
qkv_bias=qkv_bias,
|
|
|
|
act_cfg=act_cfg,
|
|
|
|
norm_cfg=norm_cfg,
|
2022-04-01 21:01:45 +08:00
|
|
|
with_cp=with_cp,
|
2021-06-18 01:41:25 +08:00
|
|
|
batch_first=True))
|
2021-05-06 13:49:28 +08:00
|
|
|
|
2021-05-01 01:37:47 +08:00
|
|
|
self.final_norm = final_norm
|
|
|
|
if final_norm:
|
2021-06-18 01:41:25 +08:00
|
|
|
self.norm1_name, norm1 = build_norm_layer(
|
|
|
|
norm_cfg, embed_dims, postfix=1)
|
|
|
|
self.add_module(self.norm1_name, norm1)
|
2021-04-22 11:19:55 +08:00
|
|
|
|
2021-06-18 01:41:25 +08:00
|
|
|
@property
|
|
|
|
def norm1(self):
|
|
|
|
return getattr(self, self.norm1_name)
|
|
|
|
|
2021-06-20 06:53:13 +08:00
|
|
|
def init_weights(self):
|
2021-11-04 01:36:09 +08:00
|
|
|
if (isinstance(self.init_cfg, dict)
|
|
|
|
and self.init_cfg.get('type') == 'Pretrained'):
|
2021-04-22 11:19:55 +08:00
|
|
|
logger = get_root_logger()
|
2022-02-09 13:52:42 +08:00
|
|
|
checkpoint = CheckpointLoader.load_checkpoint(
|
2021-11-04 01:36:09 +08:00
|
|
|
self.init_cfg['checkpoint'], logger=logger, map_location='cpu')
|
|
|
|
|
2021-04-22 11:19:55 +08:00
|
|
|
if 'state_dict' in checkpoint:
|
|
|
|
state_dict = checkpoint['state_dict']
|
|
|
|
else:
|
|
|
|
state_dict = checkpoint
|
|
|
|
|
|
|
|
if 'pos_embed' in state_dict.keys():
|
|
|
|
if self.pos_embed.shape != state_dict['pos_embed'].shape:
|
2021-06-18 01:41:25 +08:00
|
|
|
logger.info(msg=f'Resize the pos_embed shape from '
|
|
|
|
f'{state_dict["pos_embed"].shape} to '
|
|
|
|
f'{self.pos_embed.shape}')
|
2021-04-22 11:19:55 +08:00
|
|
|
h, w = self.img_size
|
2021-05-01 01:37:47 +08:00
|
|
|
pos_size = int(
|
|
|
|
math.sqrt(state_dict['pos_embed'].shape[1] - 1))
|
2021-04-22 11:19:55 +08:00
|
|
|
state_dict['pos_embed'] = self.resize_pos_embed(
|
2021-07-20 00:27:10 +08:00
|
|
|
state_dict['pos_embed'],
|
|
|
|
(h // self.patch_size, w // self.patch_size),
|
|
|
|
(pos_size, pos_size), self.interpolate_mode)
|
2021-05-01 01:37:47 +08:00
|
|
|
|
2022-02-09 13:52:42 +08:00
|
|
|
load_state_dict(self, state_dict, strict=False, logger=logger)
|
2021-11-04 01:36:09 +08:00
|
|
|
elif self.init_cfg is not None:
|
2021-06-20 06:53:13 +08:00
|
|
|
super(VisionTransformer, self).init_weights()
|
2021-11-04 01:36:09 +08:00
|
|
|
else:
|
2021-04-22 11:19:55 +08:00
|
|
|
# We only implement the 'jax_impl' initialization implemented at
|
|
|
|
# https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py#L353 # noqa: E501
|
2021-12-06 19:59:33 +08:00
|
|
|
trunc_normal_(self.pos_embed, std=.02)
|
|
|
|
trunc_normal_(self.cls_token, std=.02)
|
2021-04-22 11:19:55 +08:00
|
|
|
for n, m in self.named_modules():
|
2021-06-18 01:41:25 +08:00
|
|
|
if isinstance(m, nn.Linear):
|
2021-12-06 19:59:33 +08:00
|
|
|
trunc_normal_(m.weight, std=.02)
|
2021-04-22 11:19:55 +08:00
|
|
|
if m.bias is not None:
|
2021-06-18 01:41:25 +08:00
|
|
|
if 'ffn' in n:
|
2021-12-06 19:59:33 +08:00
|
|
|
nn.init.normal_(m.bias, mean=0., std=1e-6)
|
2021-04-22 11:19:55 +08:00
|
|
|
else:
|
2021-12-06 19:59:33 +08:00
|
|
|
nn.init.constant_(m.bias, 0)
|
2021-06-18 01:41:25 +08:00
|
|
|
elif isinstance(m, nn.Conv2d):
|
2021-12-06 19:59:33 +08:00
|
|
|
kaiming_init(m, mode='fan_in', bias=0.)
|
2021-04-22 11:19:55 +08:00
|
|
|
elif isinstance(m, (_BatchNorm, nn.GroupNorm, nn.LayerNorm)):
|
2021-12-06 19:59:33 +08:00
|
|
|
constant_init(m, val=1.0, bias=0.)
|
2021-04-22 11:19:55 +08:00
|
|
|
|
2021-07-20 00:27:10 +08:00
|
|
|
def _pos_embeding(self, patched_img, hw_shape, pos_embed):
|
2021-04-22 11:19:55 +08:00
|
|
|
"""Positiong embeding method.
|
|
|
|
|
|
|
|
Resize the pos_embed, if the input image size doesn't match
|
|
|
|
the training size.
|
|
|
|
Args:
|
|
|
|
patched_img (torch.Tensor): The patched image, it should be
|
|
|
|
shape of [B, L1, C].
|
2021-07-20 00:27:10 +08:00
|
|
|
hw_shape (tuple): The downsampled image resolution.
|
2021-04-22 11:19:55 +08:00
|
|
|
pos_embed (torch.Tensor): The pos_embed weighs, it should be
|
|
|
|
shape of [B, L2, c].
|
|
|
|
Return:
|
|
|
|
torch.Tensor: The pos encoded image feature.
|
|
|
|
"""
|
|
|
|
assert patched_img.ndim == 3 and pos_embed.ndim == 3, \
|
|
|
|
'the shapes of patched_img and pos_embed must be [B, L, C]'
|
|
|
|
x_len, pos_len = patched_img.shape[1], pos_embed.shape[1]
|
|
|
|
if x_len != pos_len:
|
|
|
|
if pos_len == (self.img_size[0] // self.patch_size) * (
|
2021-05-01 01:37:47 +08:00
|
|
|
self.img_size[1] // self.patch_size) + 1:
|
2021-04-22 11:19:55 +08:00
|
|
|
pos_h = self.img_size[0] // self.patch_size
|
|
|
|
pos_w = self.img_size[1] // self.patch_size
|
|
|
|
else:
|
|
|
|
raise ValueError(
|
|
|
|
'Unexpected shape of pos_embed, got {}.'.format(
|
|
|
|
pos_embed.shape))
|
2021-07-20 00:27:10 +08:00
|
|
|
pos_embed = self.resize_pos_embed(pos_embed, hw_shape,
|
|
|
|
(pos_h, pos_w),
|
2021-05-01 01:37:47 +08:00
|
|
|
self.interpolate_mode)
|
2021-06-18 01:41:25 +08:00
|
|
|
return self.drop_after_pos(patched_img + pos_embed)
|
2021-04-22 11:19:55 +08:00
|
|
|
|
|
|
|
@staticmethod
|
2021-07-20 00:27:10 +08:00
|
|
|
def resize_pos_embed(pos_embed, input_shpae, pos_shape, mode):
|
2021-04-22 11:19:55 +08:00
|
|
|
"""Resize pos_embed weights.
|
|
|
|
|
|
|
|
Resize pos_embed using bicubic interpolate method.
|
|
|
|
Args:
|
2021-07-20 00:27:10 +08:00
|
|
|
pos_embed (torch.Tensor): Position embedding weights.
|
|
|
|
input_shpae (tuple): Tuple for (downsampled input image height,
|
|
|
|
downsampled input image width).
|
|
|
|
pos_shape (tuple): The resolution of downsampled origin training
|
|
|
|
image.
|
|
|
|
mode (str): Algorithm used for upsampling:
|
|
|
|
``'nearest'`` | ``'linear'`` | ``'bilinear'`` | ``'bicubic'`` |
|
|
|
|
``'trilinear'``. Default: ``'nearest'``
|
2021-04-22 11:19:55 +08:00
|
|
|
Return:
|
|
|
|
torch.Tensor: The resized pos_embed of shape [B, L_new, C]
|
|
|
|
"""
|
|
|
|
assert pos_embed.ndim == 3, 'shape of pos_embed must be [B, L, C]'
|
|
|
|
pos_h, pos_w = pos_shape
|
2021-05-01 01:37:47 +08:00
|
|
|
cls_token_weight = pos_embed[:, 0]
|
|
|
|
pos_embed_weight = pos_embed[:, (-1 * pos_h * pos_w):]
|
|
|
|
pos_embed_weight = pos_embed_weight.reshape(
|
|
|
|
1, pos_h, pos_w, pos_embed.shape[2]).permute(0, 3, 1, 2)
|
2021-07-28 16:56:22 +08:00
|
|
|
pos_embed_weight = resize(
|
2021-07-20 00:27:10 +08:00
|
|
|
pos_embed_weight, size=input_shpae, align_corners=False, mode=mode)
|
2021-05-01 01:37:47 +08:00
|
|
|
cls_token_weight = cls_token_weight.unsqueeze(1)
|
|
|
|
pos_embed_weight = torch.flatten(pos_embed_weight, 2).transpose(1, 2)
|
|
|
|
pos_embed = torch.cat((cls_token_weight, pos_embed_weight), dim=1)
|
2021-04-22 11:19:55 +08:00
|
|
|
return pos_embed
|
|
|
|
|
|
|
|
def forward(self, inputs):
|
2021-05-01 01:37:47 +08:00
|
|
|
B = inputs.shape[0]
|
|
|
|
|
2021-09-29 08:46:33 +08:00
|
|
|
x, hw_shape = self.patch_embed(inputs)
|
|
|
|
|
2021-06-18 01:41:25 +08:00
|
|
|
# stole cls_tokens impl from Phil Wang, thanks
|
2021-05-01 01:37:47 +08:00
|
|
|
cls_tokens = self.cls_token.expand(B, -1, -1)
|
|
|
|
x = torch.cat((cls_tokens, x), dim=1)
|
2021-07-20 00:27:10 +08:00
|
|
|
x = self._pos_embeding(x, hw_shape, self.pos_embed)
|
2021-05-01 01:37:47 +08:00
|
|
|
|
|
|
|
if not self.with_cls_token:
|
2021-06-18 01:41:25 +08:00
|
|
|
# Remove class token for transformer encoder input
|
2021-05-01 01:37:47 +08:00
|
|
|
x = x[:, 1:]
|
|
|
|
|
|
|
|
outs = []
|
2021-06-18 01:41:25 +08:00
|
|
|
for i, layer in enumerate(self.layers):
|
|
|
|
x = layer(x)
|
|
|
|
if i == len(self.layers) - 1:
|
2021-05-01 01:37:47 +08:00
|
|
|
if self.final_norm:
|
2021-06-18 01:41:25 +08:00
|
|
|
x = self.norm1(x)
|
2021-05-01 01:37:47 +08:00
|
|
|
if i in self.out_indices:
|
|
|
|
if self.with_cls_token:
|
|
|
|
# Remove class token and reshape token for decoder head
|
|
|
|
out = x[:, 1:]
|
|
|
|
else:
|
|
|
|
out = x
|
2021-07-20 00:27:10 +08:00
|
|
|
B, _, C = out.shape
|
|
|
|
out = out.reshape(B, hw_shape[0], hw_shape[1],
|
2021-10-25 18:11:48 +08:00
|
|
|
C).permute(0, 3, 1, 2).contiguous()
|
2021-07-20 00:27:10 +08:00
|
|
|
if self.output_cls_token:
|
|
|
|
out = [out, x[:, 0]]
|
2021-05-01 01:37:47 +08:00
|
|
|
outs.append(out)
|
|
|
|
|
|
|
|
return tuple(outs)
|
2021-04-22 11:19:55 +08:00
|
|
|
|
|
|
|
def train(self, mode=True):
|
|
|
|
super(VisionTransformer, self).train(mode)
|
|
|
|
if mode and self.norm_eval:
|
|
|
|
for m in self.modules():
|
|
|
|
if isinstance(m, nn.LayerNorm):
|
|
|
|
m.eval()
|