Vision Transformer结构解析
- ViT简介
- ViT三大模块
- ViT图像预处理模块——PatchEmbed
- 多层Transformer Encoder模块
- MLP(FFN)模块
- 基本的Transformer模块
- Vision Transformer类的实现
- Transformer知识点
ViT简介
Vision Transformer。transformer于2017年的Attention is all your need提出,该模型最大的创新点就是将transformer应用于cv任务。
论文题目:An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale
论文链接:https://arxiv.org/pdf/2010.11929.pdf
代码地址:https://github.com/google-research/vision_transformer
ViT模型整体结构图如下:
ViT三种不同尺寸模型的参数对比:
ViT三大模块
ViT主要包含三大模块:PatchEmbed、多层Transformer Encoder、MLP(FFN),下面用结构图和代码解析这第三大模块。
ViT图像预处理模块——PatchEmbed
VIT划分patches的原理:
输入图像尺寸(224x224x3),按16x16的大小进行划分,共(224x224) / (16x16) = 196个patches,每个patch的维度为(16x16x3),为满足Transformer的需求,对每个patch进行投影,[16, 16, 3]->[768],这样就将原始的[224, 224, 3]转化为[196, 768]。
代码实现如下:
class PatchEmbed(nn.Module):
"""
2D Image to Patch Embedding,二维图像patch Embedding
"""
def __init__(self, img_size=224, patch_size=16, in_c=3, embed_dim=768, norm_layer=None):
super().__init__()
img_size = (img_size, img_size) # 图片尺寸224*224
patch_size = (patch_size, patch_size) #下采样倍数,一个grid cell包含了16*16的图片信息
self.img_size = img_size
self.patch_size = patch_size
# grid_size是经过patchembed后的特征层的尺寸
self.grid_size = (img_size[0] // patch_size[0], img_size[1] // patch_size[1])
self.num_patches = self.grid_size[0] * self.grid_size[1] #path个数 14*14=196
# 通过一个卷积,完成patchEmbed
self.proj = nn.Conv2d(in_c, embed_dim, kernel_size=patch_size, stride=patch_size)
# 如果使用了norm层,如BatchNorm2d,将通道数传入,以进行归一化,否则进行恒等映射
self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
def forward(self, x):
B, C, H, W = x.shape #batch,channels,heigth,weigth
# 输入图片的尺寸要满足既定的尺寸
assert H == self.img_size[0] and W == self.img_size[1], \
f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
# proj: [B, C, H, W] -> [B, C, H,W] , [B,3,224,224]-> [B,768,14,14]
# flatten: [B, C, H, W] -> [B, C, HW] , [B,768,14,14]-> [B,768,196]
# transpose: [B, C, HW] -> [B, HW, C] , [B,768,196]-> [B,196,768]
x = self.proj(x).flatten(2).transpose(1, 2)
x = self.norm(x)
return x
多层Transformer Encoder模块
该模块的主要结构是Muti-head Attention,也就是self-attention,它能够使得网络看到全局的信息,而不是CNN的局部感受野。
self-attention的结构示例如下:
class Attention(nn.Module):
"""
muti-head attention模块,也是transformer最主要的操作
"""
def __init__(self,
dim, # 输入token的dim,768
num_heads=8, #muti-head的head个数,实例化时base尺寸的vit默认为12
qkv_bias=False,
qk_scale=None,
attn_drop_ratio=0.,
proj_drop_ratio=0.):
super(Attention, self).__init__()
self.num_heads = num_heads
head_dim = dim // num_heads #平均每个head的维度
self.scale = qk_scale or head_dim ** -0.5 #进行query操作时,缩放因子
# qkv矩阵相乘操作,dim * 3使得一次性进行qkv操作
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
self.attn_drop = nn.Dropout(attn_drop_ratio)
self.proj = nn.Linear(dim, dim)
self.proj_drop = nn.Dropout(proj_drop_ratio)
def forward(self, x):
# [batch_size, num_patches + 1, total_embed_dim] 如 [bactn,197,768]
B, N, C = x.shape # N:197 , C:768
# qkv进行注意力操作,reshape进行muti-head的维度分配,permute维度调换以便后续操作
# qkv(): -> [batch_size, num_patches + 1, 3 * total_embed_dim] 如 [b,197,2304]
# reshape: -> [batch_size, num_patches + 1, 3, num_heads, embed_dim_per_head] 如 [b,197,3,12,64]
# permute: -> [3, batch_size, num_heads, num_patches + 1, embed_dim_per_head]
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
# qkv的维度相同,[batch_size, num_heads, num_patches + 1, embed_dim_per_head]
q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
# transpose: -> [batch_size, num_heads, embed_dim_per_head, num_patches + 1]
# @: multiply -> [batch_size, num_heads, num_patches + 1, num_patches + 1]
attn = (q @ k.transpose(-2, -1)) * self.scale #矩阵相乘操作
attn = attn.softmax(dim=-1) #每一path进行softmax操作
attn = self.attn_drop(attn)
# [b,12,197,197]@[b,12,197,64] -> [b,12,197,64]
# @: multiply -> [batch_size, num_heads, num_patches + 1, embed_dim_per_head]
# 维度交换 transpose: -> [batch_size, num_patches + 1, num_heads, embed_dim_per_head]
# reshape: -> [batch_size, num_patches + 1, total_embed_dim]
x = (attn @ v).transpose(1, 2).reshape(B, N, C)
x = self.proj(x) #经过一层卷积
x = self.proj_drop(x) #Dropout
return x
MLP(FFN)模块
一个MLP模块的结构如下:
class Mlp(nn.Module):
"""
MLP as used in Vision Transformer, MLP-Mixer and related networks
"""
def __init__(self, in_features, hidden_features=None, out_features=None,
act_layer=nn.GELU, # GELU是更加平滑的relu
drop=0.):
super().__init__()
out_features = out_features or in_features #如果out_features不存在,则为in_features
hidden_features = hidden_features or in_features #如果hidden_features不存在,则为in_features
self.fc1 = nn.Linear(in_features, hidden_features) # fc层1
self.act = act_layer() #激活
self.fc2 = nn.Linear(hidden_features, out_features) # fc层2
self.drop = nn.Dropout(drop)
def forward(self, x):
x = self.fc1(x)
x = self.act(x)
x = self.drop(x)
x = self.fc2(x)
x = self.drop(x)
return x
基本的Transformer模块
由Self-attention和MLP可以组合成Transformer的基本模块。Transformer的基本模块还使用了残差连接结构。
一个Transformer Block的结构如下:
class Block(nn.Module):
"""
基本的Transformer模块
"""
def __init__(self,
dim,
num_heads,
mlp_ratio=4.,
qkv_bias=False,
qk_scale=None,
drop_ratio=0.,
attn_drop_ratio=0.,
drop_path_ratio=0.,
act_layer=nn.GELU,
norm_layer=nn.LayerNorm):
super(Block, self).__init__()
self.norm1 = norm_layer(dim) #norm层
self.attn = Attention(dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale,
attn_drop_ratio=attn_drop_ratio, proj_drop_ratio=drop_ratio)
# NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
# 代码使用了DropPath,而不是原版的dropout
self.drop_path = DropPath(drop_path_ratio) if drop_path_ratio > 0. else nn.Identity()
self.norm2 = norm_layer(dim) #norm层
mlp_hidden_dim = int(dim * mlp_ratio) #隐藏层维度扩张后的通道数
# 多层感知机
self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop_ratio)
def forward(self, x):
x = x + self.drop_path(self.attn(self.norm1(x))) # attention后残差连接
x = x + self.drop_path(self.mlp(self.norm2(x))) # mlp后残差连接
return x
Vision Transformer类的实现
class VisionTransformer(nn.Module):
def __init__(self, img_size=224, patch_size=16, in_c=3, num_classes=1000,
embed_dim=768, depth=12, num_heads=12, mlp_ratio=4.0, qkv_bias=True,
qk_scale=None, representation_size=None, distilled=False, drop_ratio=0.,
attn_drop_ratio=0., drop_path_ratio=0., embed_layer=PatchEmbed, norm_layer=None,
act_layer=None):
"""
Args:
img_size (int, tuple): input image size
patch_size (int, tuple): patch size
in_c (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
qk_scale (float): override default qk scale of head_dim ** -0.5 if set
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_ratio (float): dropout rate
attn_drop_ratio (float): attention dropout rate
drop_path_ratio (float): stochastic depth rate
embed_layer (nn.Module): patch embedding layer
norm_layer: (nn.Module): normalization layer
"""
super(VisionTransformer, self).__init__()
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 #distilled在vit中没有使用到
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_c=in_c, embed_dim=embed_dim)
num_patches = self.patch_embed.num_patches
self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) #[1,1,768],以0填充
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_ratio)
# 按照block数量等间距设置drop率
dpr = [x.item() for x in torch.linspace(0, drop_path_ratio, depth)] # stochastic depth decay rule
self.blocks = nn.Sequential(*[
Block(dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,
drop_ratio=drop_ratio, attn_drop_ratio=attn_drop_ratio, drop_path_ratio=dpr[i],
norm_layer=norm_layer, act_layer=act_layer)
for i in range(depth)
])
self.norm = norm_layer(embed_dim) # layer_norm
# Representation layer
if representation_size and not distilled:
self.has_logits = True
self.num_features = representation_size
self.pre_logits = nn.Sequential(OrderedDict([
("fc", nn.Linear(embed_dim, representation_size)),
("act", nn.Tanh())
]))
else:
self.has_logits = False
self.pre_logits = nn.Identity()
# Classifier head(s),分类头,self.num_features=768
self.head = nn.Linear(self.num_features, num_classes) if num_classes > 0 else nn.Identity()
self.head_dist = None
if distilled:
self.head_dist = nn.Linear(self.embed_dim, self.num_classes) if num_classes > 0 else nn.Identity()
# Weight init,权重初始化
nn.init.trunc_normal_(self.pos_embed, std=0.02)
if self.dist_token is not None:
nn.init.trunc_normal_(self.dist_token, std=0.02)
nn.init.trunc_normal_(self.cls_token, std=0.02)
self.apply(_init_vit_weights)
def forward_features(self, x):
# [B, C, H, W] -> [B, num_patches, embed_dim]
x = self.patch_embed(x) # [B, 196, 768]
# cls_token类别token [1, 1, 768] -> [B, 1, 768],扩张为batch个cls_token
cls_token = self.cls_token.expand(x.shape[0], -1, -1)
if self.dist_token is None:
x = torch.cat((cls_token, x), dim=1) # [B, 196, 768]-> [B, 197, 768],维度1上的cat
else:
x = torch.cat((cls_token, self.dist_token.expand(x.shape[0], -1, -1), x), dim=1)
x = self.pos_drop(x + self.pos_embed) #添加位置嵌入信息
x = self.blocks(x) #通过attention堆叠模块(12个)
x = self.norm(x) #layer_norm
if self.dist_token is None:
return self.pre_logits(x[:, 0]) #返回第一层特征,即为分类值
else:
return x[:, 0], x[:, 1]
def forward(self, x):
# 分类头
x = self.forward_features(x) # 经过att操作,但是没有进行分类头的前传
if self.head_dist is not None:
x, x_dist = self.head(x[0]), self.head_dist(x[1])
if self.training and not torch.jit.is_scripting():
# during inference, return the average of both classifier predictions
return x, x_dist
else:
return (x + x_dist) / 2
else:
x = self.head(x)
return x
Transformer知识点
论文:Attention Is All You Need
论文地址:https://arxiv.org/pdf/1706.03762.pdf
Transformer由Attention和Feed Forward Neural Network(也称FFN)组成,其中Attention包含self Attention与Mutil-Head Attention。
网络结构如下:
attention和multi-head-attention结构:
计算过程:
计算复杂度对比: