论文链接:An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale
最近开始恶补CV了(指->新建文件夹)。作为CV Transformer的开山大作,首先要学习的就是ViT(Vision Transformer)模型。有很多大佬都已经解读过这篇工作了,我比较推荐李沐大神团队的视频,不仅能了解模型架构,还能学到些论文写作技巧。也参考了我的b站导师 (代码是基于timm的) 本文代码基于vit-pytorch,该项目包含了ViT和诸多变体。需要预训练模型的话可以参考timm的实现(pytorch-image-models)
ViT的架构
ViT的结构如上图,我们按照流程一步步讲解。大概来说,ViT分为这几个步骤。1.图片分块和映射;2.Transformer;3.线性层输出。原论文给出了3种不同大小的模型:Base、Large、Huge,他们的Transformer层数,head不同,中间维度、线性层维度也不相同,具体数值请参考原论文。文章代码基于Base/16
ViT-Base
先来看最终的总体架构,具体步骤我已经做了注释,解释下形参
- image_size:图片尺寸,int或者tuple皆可,例如224,或者(224, 224),长宽不一定要一样大
- path_size:分块path尺寸,int或tuple,默认为16,需要确保image_size能被path_size整除
- num_classes:分类数,int
- dim:Transformer隐层维度,对于Base来说是768,Large为1024
- depth:Transformer个数,Base为12
- head:多头的个数,Base=12
- mlp_dim:Transformer中的FeedForward中第一个线性层升维后的维度,默认为768*4,先升维4倍再降维回去
- pool:默认'cls,选取CLS token作为输出,可选'mean',在patch维度做平均池化
- channel:图片输入的特征维度,RGB图像为3,灰度图为1
class ViT(nn.Module):
def __init__(self, *, image_size, patch_size, num_classes, dim, depth, heads, mlp_dim, pool = 'cls', channels = 3, dim_head = 64, dropout = 0., emb_dropout = 0.):
super().__init__()
image_height, image_width = pair(image_size) # 在这个项目中没有限定图片的尺寸
patch_height, patch_width = pair(patch_size) # 默认为16
assert image_height % patch_height == 0 and image_width % patch_width == 0, 'Image dimensions must be divisible by the patch size.'
# num patches -> (224 / 16) = 14, 14 * 14 = 196
num_patches = (image_height // patch_height) * (image_width // patch_width)
# path dim -> 3 * 16 * 16 = 768,和Bert-base一致
patch_dim = channels * patch_height * patch_width
assert pool in {'cls', 'mean'}, 'pool type must be either cls (cls token) or mean (mean pooling)' # 输出选cls token还是做平均池化
# 步骤一:图像分块与映射。首先将图片分块,然后接一个线性层做映射
self.to_patch_embedding = nn.Sequential(
Rearrange('b c (h p1) (w p2) -> b (h w) (p1 p2 c)', p1 = patch_height, p2 = patch_width),
nn.Linear(patch_dim, dim),
)
# pos_embedding:位置编码;cls_token:在序列最前面插入一个cls token作为分类输出
self.pos_embedding = nn.Parameter(torch.randn(1, num_patches + 1, dim))
self.cls_token = nn.Parameter(torch.randn(1, 1, dim))
self.dropout = nn.Dropout(emb_dropout)
# 步骤二:Transformer Encoder结构来提特征
self.transformer = Transformer(dim, depth, heads, dim_head, mlp_dim, dropout)
self.pool = pool
self.to_latent = nn.Identity() # 这一步上面都没做
# 线性层输出
self.mlp_head = nn.Sequential(
nn.LayerNorm(dim),
nn.Linear(dim, num_classes)
)
def forward(self, img):
...
1. 分块与映射
分块这里调用了einops这个库,可以很方便直观地进行维度变换。简单起见,下面按照默认的patch 宽高=16的设置,所以在行和列上一共有224 / 16 = 14个patch。这里的操作就是把一个batch的,shape为(batch, 3, 224, 224)的图片,首先划分为(batch, 3, ( 14 x 16), (14 x 16)),按照块给他展平,操作和动图里的一样,最后的输出就是(batch, ( 14 x 14), ( 16 x 16 x 3 = 768))。除掉第一维的batch,单独拎一个path来看,其特征维度是768,就是每一个像素铺平后的长度(RGB图像有3个特征维度)。铺平后接上一个linear做线性映射,维度也是768。
from einops.layers.torch import Rearrange
self.to_patch_embedding = nn.Sequential(
Rearrange('b c (h p1) (w p2) -> b (h w) (p1 p2 c)', p1 = patch_height, p2 = patch_width),
nn.Linear(patch_dim, dim),
)
# forward:
x = self.to_patch_embedding(img)
接下来要加上位置编码。文章采用的是一维位置编码,作者也测试了2维和相对位置编码,结果都差不多。一维的意思就是把展平后的图片看成一个序列,第二维的14 * 14 =196看成NLP里token的长度,只考虑这个长度。ViT的位置编码也可以理解为一种可以训练的绝对位置编码(因为取的是embedding中前196+1个,然后对应位置和x相加)。
论文的附录图10
然后在拼上一个CLS token
self.pos_embedding = nn.Parameter(torch.randn(1, num_patches + 1, dim))
self.cls_token = nn.Parameter(torch.randn(1, 1, dim))
self.dropout = nn.Dropout(emb_dropout)
# forward:
b, n, _ = x.shape
# 1 x 1 x 768的CLS token重复至 batch x 1 x 768
cls_tokens = repeat(self.cls_token, '() n d -> b n d', b = b)
x = torch.cat((cls_tokens, x), dim=1)
x += self.pos_embedding[:, :(n + 1)] # 因为多了个CLS token所以要n+1
x = self.dropout(x)
# x.shape -> (batch, 196 + 1, 768)
2. Transformer Encoder
ViT框架里就这么一步
self.transformer = Transformer(dim, depth, heads, dim_head, mlp_dim, dropout)
# forward
x = self.transformer(x)
Transformer的流程我简单画了一下,这一块我直接在代码里注释了下,如果有不懂的建议大家先去看一下Transformer的代码和原理,ViT和Bert一样只有encoder的部分,要简单一些。
Self-Attention总结起来就是 ���(�,�,�)=�������(�⋅����)�
class PreNorm(nn.Module):
def __init__(self, dim, fn):
super().__init__()
self.norm = nn.LayerNorm(dim)
self.fn = fn
def forward(self, x, **kwargs):
# 先LN
return self.fn(self.norm(x), **kwargs)
class FeedForward(nn.Module):
def __init__(self, dim, hidden_dim, dropout = 0.):
super().__init__()
self.net = nn.Sequential(
nn.Linear(dim, hidden_dim),
nn.GELU(),
nn.Dropout(dropout),
nn.Linear(hidden_dim, dim),
nn.Dropout(dropout)
)
def forward(self, x):
return self.net(x)
class Attention(nn.Module):
def __init__(self, dim, heads = 8, dim_head = 64, dropout = 0.):
super().__init__()
inner_dim = dim_head * heads
project_out = not (heads == 1 and dim_head == dim)
self.heads = heads
self.scale = dim_head ** -0.5 # 论文里的\sqrt{d_k}
self.attend = nn.Softmax(dim = -1)
# Q K V一块处理了,有的工作是用了3个维度为dim的Linear层分别得到的
self.to_qkv = nn.Linear(dim, inner_dim * 3, bias = False)
self.to_out = nn.Sequential(
nn.Linear(inner_dim, dim),
nn.Dropout(dropout)
) if project_out else nn.Identity()
def forward(self, x):
# 输入 x -> (batch, 197, 768)即(batch, num_patch + 1, hid_dims)
# 按照最后一维(特征维度)分成3块,分别对应QKV
# chunk后是一个tuple,即(q, k, v)
qkv = self.to_qkv(x).chunk(3, dim = -1)
# q, k, v都做维度变换,(batch, 197, 768) -> (batch, 12, 197, 768 / 12 = 64)
# 12是head的数量,目的是做**多头**注意力机制
q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> b h n d', h = self.heads), qkv)
# Q @ K^T / \sqrt{d_k}
dots = torch.matmul(q, k.transpose(-1, -2)) * self.scale
attn = self.attend(dots) # softmax
out = torch.matmul(attn, v)
# 把多头拼回去 -> (batch, 197, 768)
out = rearrange(out, 'b h n d -> b n (h d)')
return self.to_out(out)
class Transformer(nn.Module):
def __init__(self, dim, depth, heads, dim_head, mlp_dim, dropout = 0.):
super().__init__()
self.layers = nn.ModuleList([])
for _ in range(depth):
self.layers.append(nn.ModuleList([
PreNorm(dim, Attention(dim, heads = heads, dim_head = dim_head, dropout = dropout)),
PreNorm(dim, FeedForward(dim, mlp_dim, dropout = dropout))
]))
# 先LN再做Att或者Forward
def forward(self, x):
for attn, ff in self.layers: # attn为Multi-head Attention,ff就是FeedForward
x = attn(x) + x # 残差连接,图片中的边线
x = ff(x) + x
return x
3.线性层输出
self.pool = pool
self.to_latent = nn.Identity()
# 线性层输出
self.mlp_head = nn.Sequential(
nn.LayerNorm(dim),
nn.Linear(dim, num_classes)
)
# forward
x = x.mean(dim = 1) if self.pool == 'mean' else x[:, 0]
x = self.to_latent(x)
return self.mlp_head(x)
这一块没什么好说的,一般直接用CLS token作为输出。为什么cls可以作为输出呢?主要还是因为Transformer的自注意机制,每个地方都能兼顾全局,而不是CNN那种的局部信息。
ViT-timm实现
从论文中我们知道如果训练的图片数据集规模没有特别大的话,ViT是不如CNN的。在实际项目中我们更多用到的是微调预训练模型,上边的库没有预训练模型,所以提供预训练模型的timm的使用率会更高。timm的实现要更复杂,因为源码里包含了DEIT(ViT+蒸馏),源代码里还有很多初始化、加载预训练权重等操作。这里就只看模型的架构,说一下和上边不同的地方。
总体架构部分
class VisionTransformer(nn.Module):
""" Vision Transformer
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=''):
"""
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
"""
首先如果要用timm的预训练权重,图片尺寸必须为224x224或者384x384,使用方法如下
import timm
model = timm.from_pretrained('vit_base_patch16_224', num_classes=xx)
形参上多了mlp_ratio,对应mlp_dim(4 x 768的4);
以及qkv_bias=True的可选操作;
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) # Attention模块
# forward
B, N, C = x.shape
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
distilled=False是为DEIT准备的
embed_layer=PatchEmbed:实现如下
class PatchEmbed(nn.Module):
""" 2D Image to Patch Embedding
"""
def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768, norm_layer=None, flatten=True):
super().__init__()
img_size = to_2tuple(img_size)
patch_size = to_2tuple(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]) # 224 / 16 = 14,即(14, 14)
self.num_patches = self.grid_size[0] * self.grid_size[1] # 196
self.flatten = flatten
self.proj = nn.Conv2d(in_chans, 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], f"Input image height ({H}) doesn't match model ({self.img_size[0]}).")
_assert(W == self.img_size[1], f"Input image width ({W}) doesn't match model ({self.img_size[1]}).")
x = self.proj(x)
if self.flatten:
x = x.flatten(2).transpose(1, 2) # BCHW -> BNC
x = self.norm(x) # 默认是没有norm的
return x
从之前的线性层替换为2维卷积了,卷积大小和stride都为patch size,即16
经过卷积,输入(batch, 3, 224, 224) -> (batch, 768, 14, 14),非常取巧的操作啊,花里胡哨的,和线性层是一样的效果
之后在第三个维度展平:(batch, 768, 14, 14) flatten -> (batch, 768, 196) transpose(1, 2) -> (batch, 196, 768)
其他地方在写法上有不同,但方法是基本一样的,对了,timm还在Transformer那部分加入了drop_path