Vision Transformer模型(ViT模型)是视觉领域一个比较重要的模型,为了更深入的了解模型以及锻炼自己的实践能力,最近手撕了ViT,首先声明,代码是一位叫做rwightman的大神实现的,源码地址是:
https://github.com/huggingface/pytorch-image-models/blob/main/timm/models/vision_transformer.py
本人按照他的代码及思路一点一点搭建ViT模型,本篇博文就来认真解读一下该大神搭建ViT模型的代码风格和代码架构,看一看他是如何用400多行的代码(其实仅200多行)实现ViT的。在他的代码中,我也是学到了很多实战技巧和代码框架技巧,不过还有一些没有看得特别懂,不过整个架构是看明白了,在此和各位分享。
1.Vision Transformer的整体架构
在搭建VIT之前,我们十分有必要去将它的整体框架烂熟于心,原论文中的架构图如下:
由架构图可以看出,VIT模型主要由以下三个部分构成:
1.Embedding层。输入的图片经过该层后被转化为一行行token,每个patch一行token。
2.Encoder层。将蕴含分类和位置信息的token经过该层进行特征提取。注意Encoder层是可以堆叠的。
3.MLP head层。取出Encoder层的输出中用于分类的那一行token,经过该层之后完成分类任务。
其实层与层之间也有一些细节上的操作处理,在最后一个部分我会细说。此部分是为了先让大家了解VIT的整体架构。
2.Vision Transformer各层的架构图以及具体实现
2.1Embedding层
Embedding层的架构图:
代码:
class PatchEmbed(nn.Module):
"""
2D Image to 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)
patch_size = (patch_size, patch_size)
self.img_size = img_size
self.patch_size = patch_size
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]
self.proj = nn.Conv2d(in_c, embed_dim, kernel_size=patch_size, stride=patch_size)
self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
def forward(self, x):
B, C, H, W = x.shape
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]})."
# flatten: [B, C, H, W] -> [B, C, HW]
# transpose: [B, C, HW] -> [B, HW, C]
x = self.proj(x).flatten(2).transpose(1, 2)
x = self.norm(x)
return x
初始化函数:我们需要用到的参数有:img_size:图片的大小, patch_size:一个patch的大小, in_c:输入的通道数, embed_dim:一个token的维数, norm_layer:规范化函数,然后初始化卷积层和规范化层即可。
前向传播函数:首先判断一下图片大小是否符合规范,然后过一个卷积层的前向传播,再过一个Norm规范化层,最后得到每张图片的patch行的token。
2.2Encoder层
Encoder层的架构图:
由架构图可知,Encoder主要分为两个模块,一个是multi-head-Attention模块,一个是MLP模块。
代码(请大家先把下面两个子模块看完之后再来看Encoder的代码!!!):
class Block(nn.Module):
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)
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
self.drop_path = DropPath(drop_path_ratio) if drop_path_ratio > 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_ratio)
def forward(self, x):
x = x + self.drop_path(self.attn(self.norm1(x)))
x = x + self.drop_path(self.mlp(self.norm2(x)))
return x
2.2.1multi-head-Attention模块
multi-head-Attention模块架构图:
总的来说,从上一层传入的token经过了Linear层,并通过对多维张量的操作,得到了注意力机制的重要参数q,k,v,然后进行注意力机制的流程,注意,q和k计算之后会有一个dropout,然后为了更好地让信息融合,会再经过一个Linear层,之后再过一个dropout层,防止过拟合。
代码:
class Attention(nn.Module):
def __init__(self,
dim, # 输入token的dim
num_heads=8,
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
self.scale = qk_scale or head_dim ** -0.5
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]
B, N, C = x.shape
# qkv(): -> [batch_size, num_patches + 1, 3 * total_embed_dim]
# reshape: -> [batch_size, num_patches + 1, 3, num_heads, embed_dim_per_head]
# 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)
# [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)
attn = self.attn_drop(attn)
# @: 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)
return x
初始化函数:我们需要用到的参数有:dim: 输入token的维数,num_heads=8:头的数量, qkv_bias=False:qkv操作是否有偏置, qk_scale=None:dk, attn_drop_ratio=0.:q和k运算之后过的dropout层的p, proj_drop_ratio=0.:最后一个dropout层的p。随后初始化每一个Linear层和dropout层。
前向传播函数:见代码,此处就不多言了。
2.2.2MLP模块
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, drop=0.):
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
self.fc1 = nn.Linear(in_features, hidden_features)
self.act = act_layer()
self.fc2 = nn.Linear(hidden_features, out_features)
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
初始化函数:in_features:输入维度, hidden_features=None:隐藏层维度, out_features=None:输出维度, act_layer=nn.GELU:激活函数, drop=0.:dropout层的p
前向传播函数:见代码,此处不多言。
2.3MLP head层
MLP head层比较简单,没有特别的写一个class来作为一个模块,因为它是用作分类的,所以一个Linear层就可以解决,参数为nn.Linear(dim,分类个数)。
3.Vision Transformer模型的整体搭建
关于VIT模型整体搭建这块我就不画架构图了,架构和最开始那个图一致,但主要是中间的处理细节,下面我会用文字来详细讲解一遍rwightman大神是怎么搭的。(注意:我没有加那个蒸馏头那个维度,关于蒸馏头大家可以去读一下代码就知道是什么意思了)
代码:
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):
super(VisionTransformer, self).__init__()
self.num_classes = num_classes
self.num_features = self.embed_dim = embed_dim
self.num_tokens = 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_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))
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)
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)
# Classifier head(s)
self.head = nn.Linear(self.num_features, num_classes) if num_classes > 0 else nn.Identity()
# Weight init
nn.init.trunc_normal_(self.pos_embed, std=0.02)
nn.init.trunc_normal_(self.cls_token, std=0.02)
self.apply(_init_vit_weights)
def forward(self, x):
# [B, C, H, W] -> [B, num_patches, embed_dim]
x = self.patch_embed(x) # [B, 196, 768]
# [1, 1, 768] -> [B, 1, 768]
cls_token = self.cls_token.expand(x.shape[0], -1, -1)
x = torch.cat((cls_token, x), dim=1) # [B, 197, 768]
x = self.pos_drop(x + self.pos_embed)
x = self.blocks(x)
x = self.norm(x)
x = self.head(x)
return x
VIT整体模型解读:
首先,对于输入x,x是一个mini_batch,是一个四维张量,(B,C,H,W),然后我们实例化一个embedding层的对象:
self.patch_embed = embed_layer(img_size=img_size, patch_size=patch_size, in_c=in_c, embed_dim=embed_dim)
之后我们直接使用该层的forward函数:x = self.patch_embed(x)
然后我们需要加一个关于分类的张量,它的维度和token的维度一致,是三维的,(1,1,embed_dim),然后将它加入到每一个patch的token的第一维,这里需要用到torch.expand函数和torch.cat函数:
#初始化
self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
#前向传播
cls_token = self.cls_token.expand(x.shape[0], -1, -1)
x = torch.cat((cls_token, x), dim=1) # [B, 197, 768]
我们接下来进行位置编码的设置,此处设置可学习的位置编码:
#初始化
self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + self.num_tokens, embed_dim))
#前向传播
x = self.pos_drop(x + self.pos_embed)
接着过N个堆叠的Encoder和规范化层:
#初始化
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)
#前向传播
x = self.blocks(x)
x = self.norm(x)
最后过一个MLP head层:
#初始化
self.head = nn.Linear(self.num_features, num_classes) if num_classes > 0 else nn.Identity()
#前向传播
x = self.head(x)
好了,以上就是本篇博文的所有内容,主要围绕ViT模型的搭建来展开,模型的学习并不是一朝一夕,而是需要耐下心来、认真研究具体实现过程,把别人的好的转化为自己的,这样才能提升。