VIT(vision transformer)模型介绍+pytorch代码炸裂解析
前言
一直对transformer都有很大的兴趣,之前看到有vision transformer,一直没来得及好好看,这两天拿出来吸收了下精华,顺便写个文章记录一哈
地址
论文:https://arxiv.org/pdf/2010.11929.pdf
代码:https://github.com/lucidrains/vit-pytorch/blob/main/vit_pytorch/vit.py
讲解视频:https://www.bilibili.com/video/BV1U3411e7Bq?spm_id_from=333.999.0.0
因为实在写解读有点费事,直接录了个视频,简单解读在文章中
模型VIT解读
这个论文的好处就是可以直接看这个overview的图,我读的时候可能都没看后面文章,直接看图就懂了,不得不说很清晰了。
直接说明一下。
把一个图进行patch的操作切割,得到很多个patch图块,之后每个图块,根据从上到下,从左到右的顺序进行输入,这个看图非常清晰,之后对每个patch进行flatten拉平(这里相当于把每个图片patch转换为了一维向量,比较匹配NLP的输入性质了,即CV->NLP),之后过一个全连接层,得到每个patch对应的token,之后再加上position的编码送到transformer中,这里其实只用了encoder部分,因为主要做分类任务,每个token在transformer中都是两两互相做attention的,那最终输出哪个呢?所以引入了一个cls token和其他的token做attention,相当于或取了其他的token的信息,直接用它作为输出即可。
这里如果看不懂我建议直接看代码,秒懂。
源码解读
复习下transformer的encoder部分
其中multihead-attention:
其中的self-attention:
这个multihead attention的代码因为用了几个我个人感觉很不错的写法变得很简洁
使用了einops,可以直接从代码看出来维度变化
算qkv的时候直接用的三倍的linear,之后chunk一下,这样节省几行代码
加入了Identity,让整体网络更标准化
在multi head的处理中,这里需要注意具体是怎么操作的,我发现网上很多这块都是错的,这块具体的操作是把qkv的维度按照head的个数进行等分,最后算为attention的值再进行concat在一起,这个代码用einops中的rearrange直接简洁一起操作了
但是这个实现和torch官方的实现还是有一定的小区别的,我们看下源码的attention部分
看上面那个部分,要求embed_dim可以被head整除,这样才能几个head同时工作,主要的原因在于官方里的head_dim是直接这么算出来的,而并非定义的,而这个vision transformer中的代码是自定义的反推。
残差的两个部分 transformer中都是先加上之前的输入x再进行layerNorm
x = layerNorm(x + attention(x))
x = layerNorm(x + feedforward(x)) 但这个论文里稍显不同
相当于第一步layernorm再干别的,并且代码中把这种操作直接定义成一个类。
其中的kwargs的解释可以看这个:https://www.jianshu.com/p/0ed914608a2c
feedforward的是两个全连接中间夹个激活函数,可以是RELU或者GELU,加入了dropout,这块代码一看就懂
加一起就是transformer的encoder部分,这篇文章主要用到的是encoder部分
而整体的VIT还需要变换patch,以及patch embedding,以及加入cls_token和position信息,之后transformer输出的位置还有个MLP的变换
整体的VIT class代码如上。
“感兴趣的看我40分钟的代码详细解读:https://www.bilibili.com/video/BV1U3411e7Bq?spm_id_from=333.999.0.0
”
所有代码如下:
import torch
from torch import nn
from einops import rearrange, repeat
from einops.layers.torch import Rearrange
# helpers
def pair(t):
return t if isinstance(t, tuple) else (t, t)
# classes
class PreNorm(nn.Module):
def __init__(self, dim, fn):
super().__init__()
self.norm = nn.LayerNorm(dim)
self.fn = fn
def forward(self, x, **kwargs):
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
self.attend = nn.Softmax(dim = -1)
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):
qkv = self.to_qkv(x).chunk(3, dim = -1)
q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> b h n d', h = self.heads), qkv)
dots = torch.matmul(q, k.transpose(-1, -2)) * self.scale
attn = self.attend(dots)
out = torch.matmul(attn, v)
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))
]))
def forward(self, x):
for attn, ff in self.layers:
x = attn(x) + x
x = ff(x) + x
return x
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)
assert image_height % patch_height == 0 and image_width % patch_width == 0, 'Image dimensions must be divisible by the patch size.'
num_patches = (image_height // patch_height) * (image_width // patch_width)
patch_dim = channels * patch_height * patch_width
assert pool in {'cls', 'mean'}, 'pool type must be either cls (cls token) or mean (mean pooling)'
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),
)
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)
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):
x = self.to_patch_embedding(img)
b, n, _ = x.shape
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)]
x = self.dropout(x)
x = self.transformer(x)
x = x.mean(dim = 1) if self.pool == 'mean' else x[:, 0]
x = self.to_latent(x)
return self.mlp_head(x)
推荐阅读:
公众号:AI蜗牛车
保持谦逊、保持自律、保持进步

发送【蜗牛】获取一份《手把手AI项目》(AI蜗牛车著)
发送【1222】获取一份不错的leetcode刷题笔记
发送【AI四大名著】获取四本经典AI电子书
更多推荐


所有评论(0)