VIT:Vision Transformer超级详解含代码

论文原文:An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale

1.VIT模型架构图

简单而言,模型由三个模块组成:

(1) Linear Projection of Flattened Patches(Embedding层)

(2) Transformer Encoder

(3) MLP Head:最终用于分类的层结构

具体步骤:

1.1 图片切分为patch

1.2 patch转化为embedding

由于一个patch是正方形,不能直接作为TRM的输入,需要把这一个patch转化成一个固定维度的embedding,然后用embedding作为TRM的输入。方法1:把patch拉平,二维转一维(eg.原来16x16变为256);方法2:把拉平之后的这个维度映射到我自己规定的一个向量长度。

注:在此过程中有两个实验方式,这里用的是Linear Projection是一个线性的转化,还有一种就是说petch=16*16,可以用一个16*16,步长为16的卷积来操作这个,卷积核设置成768,输出通道就是768,也就是说将768转换成了TRM Encoder的维度。

1.3 位置embedding和 token sembedding相加

首先生成CLS符号的token emb,图中*,然后生成所有序列的位置编码,图中1,2,3...,粉色的跟紫色的相加得到输入的embadding。

为啥加入一个CLS符号?

在论文后证明,CLS作用不大,它的作用就是减少对原始TRM模型的更改,BERT中使用CLS是由于,BERT有两个预训练任务,NSP(二分类)任务:预测下一句;MLM:预测当前单词。两个任务如果都使用池化进行损失的话,会在某些tokens上进行重复,使用CLS一定程度上让两个任务保持一种相对的独立。但是VIT不涉及到MLM这种形式的任务,只会有一个多分类任务,所以CLS符号不是必须的。

位置编码

为了保持输入图像patch之间的空间位置信息,还需要对图像块嵌入中添加一个位置编码向量,如上式中的Epos所示,ViT的位置编码没有使用更新的2D位置嵌入方法,而是直接用的一维可学习的位置嵌入变量,原先是论文作者发现实际使用时2D并没有展现出比1D更好的效果。

1.4 输入到TRM模型

输入之后先过一个Normalization层,在进入自注意力层,输出与输入做一个残差,在输入到Normalization,输入到前馈神经网络,在过一个残差,有几个Encoder就做几次,最终得到的每一个token都会生成一个输出。

1.5 CLS输出做多分类任务

把第一个CLS输出拿出来做多分类任务

2.代码

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)  # 把dim维度映射到inner_dim * 3这个维度

        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)  # 对tensor张量分块 x :1*197*1024   qkv 最后是一个元组,tuple,长度是3,每个元素形状:1 197 1024
        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)  # 乘以对应的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([])
        # 把多个encoder堆叠在一起
        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) ## 224*224
        patch_height, patch_width = pair(patch_size)## 16 * 16

        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
        patch_dim = channels * patch_height * patch_width  # 拉平:patch的宽和高乘通道数
        assert pool in {'cls', 'mean'}, 'pool type must be either cls (cls token) or mean (mean pooling)'
        # 图片拉平映射到encoder我们自己规定的模型里
        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))   # 生成CLS token的初始化参数
        self.dropout = nn.Dropout(emb_dropout)

        self.transformer = Transformer(dim, depth, heads, dim_head, mlp_dim, dropout)  # 输入解决了之后,把它放到TRM中

        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)  # img betch:1 通道3 224 224  输出形状x : 1*196*1024
        b, n, _ = x.shape ## 

        cls_tokens = repeat(self.cls_token, '() n d -> b n d', b = b)  # 复制b份,每一个betchsize都要加一个CLS符号
        x = torch.cat((cls_tokens, x), dim=1)  # 把CLS的tokens Embedding 和Patch Embedding进行拼接
        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)



v = ViT(
    image_size = 224,  # 输入图像大小
    patch_size = 16,  # 切分的每一块的大小
    num_classes = 1000,  # 最后CLS拿出来的映射到多少个维度上,类别上
    dim = 1024,
    depth = 6,  # encoder层数
    heads = 16,  # 多头注意力机制参数
    mlp_dim = 2048,
    dropout = 0.1,
    emb_dropout = 0.1
)

img = torch.randn(1, 3, 224, 224)

preds = v(img) # (1, 1000)

3.总结一下下

想总结,总结不太出来,就是这东西很简单,感觉没啥,但是又搞不太懂,先发出去,以后有机会在改。
 

猜你喜欢

转载自blog.csdn.net/Zosse/article/details/125690167
今日推荐