Vision 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三种不同尺寸模型的参数对比:

Panda

ViT参数量

vit_base_patch16_224,num_classes=5, has_logits=False

Total params: 85,650,437
Trainable params: 85,650,437
Non-trainable params: 0
----------------------------------------------------------------
Input size (MB): 0.57
Forward/backward pass size (MB): 408.54
Params size (MB): 326.73
Estimated Total Size (MB): 735.84
----------------------------------------------------------------

vit_base_patch32_224,num_classes=5, has_logits=False

Total params: 87,419,909
Trainable params: 87,419,909
Non-trainable params: 0
----------------------------------------------------------------
Input size (MB): 0.57
Forward/backward pass size (MB): 95.61
Params size (MB): 333.48
Estimated Total Size (MB): 429.66
----------------------------------------------------------------

vit_large_patch32_224,num_classes=5, has_logits=False

Total params: 305,463,301
Trainable params: 305,463,301
Non-trainable params: 0
----------------------------------------------------------------
Input size (MB): 0.57
Forward/backward pass size (MB): 253.01
Params size (MB): 1165.25
Estimated Total Size (MB): 1418.84

vit_huge_patch14_224,num_classes=5, has_logits=False

Total params: 630,440,965
Trainable params: 630,440,965
Non-trainable params: 0
----------------------------------------------------------------
Input size (MB): 0.57
Forward/backward pass size (MB): 2358.66
Params size (MB): 2404.94
Estimated Total Size (MB): 4764.17
----------------------------------------------------------------

网络结构打印,以常用的【vit_base_patch32_224,num_classes=5】为例:

----------------------------------------------------------------
        Layer (type)               Output Shape         Param #
================================================================
            Conv2d-1            [-1, 768, 7, 7]       2,360,064
          Identity-2              [-1, 49, 768]               0
        PatchEmbed-3              [-1, 49, 768]               0
           Dropout-4              [-1, 50, 768]               0
         LayerNorm-5              [-1, 50, 768]           1,536
            Linear-6             [-1, 50, 2304]       1,771,776
           Dropout-7           [-1, 12, 50, 50]               0
            Linear-8              [-1, 50, 768]         590,592
           Dropout-9              [-1, 50, 768]               0
        Attention-10              [-1, 50, 768]               0
         Identity-11              [-1, 50, 768]               0
        LayerNorm-12              [-1, 50, 768]           1,536
           Linear-13             [-1, 50, 3072]       2,362,368
             GELU-14             [-1, 50, 3072]               0
          Dropout-15             [-1, 50, 3072]               0
           Linear-16              [-1, 50, 768]       2,360,064
          Dropout-17              [-1, 50, 768]               0
              Mlp-18              [-1, 50, 768]               0
         Identity-19              [-1, 50, 768]               0
            Block-20              [-1, 50, 768]               0
        LayerNorm-21              [-1, 50, 768]           1,536
           Linear-22             [-1, 50, 2304]       1,771,776
          Dropout-23           [-1, 12, 50, 50]               0
           Linear-24              [-1, 50, 768]         590,592
          Dropout-25              [-1, 50, 768]               0
        Attention-26              [-1, 50, 768]               0
         Identity-27              [-1, 50, 768]               0
        LayerNorm-28              [-1, 50, 768]           1,536
           Linear-29             [-1, 50, 3072]       2,362,368
             GELU-30             [-1, 50, 3072]               0
          Dropout-31             [-1, 50, 3072]               0
           Linear-32              [-1, 50, 768]       2,360,064
          Dropout-33              [-1, 50, 768]               0
              Mlp-34              [-1, 50, 768]               0
         Identity-35              [-1, 50, 768]               0
            Block-36              [-1, 50, 768]               0
        LayerNorm-37              [-1, 50, 768]           1,536
           Linear-38             [-1, 50, 2304]       1,771,776
          Dropout-39           [-1, 12, 50, 50]               0
           Linear-40              [-1, 50, 768]         590,592
          Dropout-41              [-1, 50, 768]               0
        Attention-42              [-1, 50, 768]               0
         Identity-43              [-1, 50, 768]               0
        LayerNorm-44              [-1, 50, 768]           1,536
           Linear-45             [-1, 50, 3072]       2,362,368
             GELU-46             [-1, 50, 3072]               0
          Dropout-47             [-1, 50, 3072]               0
           Linear-48              [-1, 50, 768]       2,360,064
          Dropout-49              [-1, 50, 768]               0
              Mlp-50              [-1, 50, 768]               0
         Identity-51              [-1, 50, 768]               0
            Block-52              [-1, 50, 768]               0
        LayerNorm-53              [-1, 50, 768]           1,536
           Linear-54             [-1, 50, 2304]       1,771,776
          Dropout-55           [-1, 12, 50, 50]               0
           Linear-56              [-1, 50, 768]         590,592
          Dropout-57              [-1, 50, 768]               0
        Attention-58              [-1, 50, 768]               0
         Identity-59              [-1, 50, 768]               0
        LayerNorm-60              [-1, 50, 768]           1,536
           Linear-61             [-1, 50, 3072]       2,362,368
             GELU-62             [-1, 50, 3072]               0
          Dropout-63             [-1, 50, 3072]               0
           Linear-64              [-1, 50, 768]       2,360,064
          Dropout-65              [-1, 50, 768]               0
              Mlp-66              [-1, 50, 768]               0
         Identity-67              [-1, 50, 768]               0
            Block-68              [-1, 50, 768]               0
        LayerNorm-69              [-1, 50, 768]           1,536
           Linear-70             [-1, 50, 2304]       1,771,776
          Dropout-71           [-1, 12, 50, 50]               0
           Linear-72              [-1, 50, 768]         590,592
          Dropout-73              [-1, 50, 768]               0
        Attention-74              [-1, 50, 768]               0
         Identity-75              [-1, 50, 768]               0
        LayerNorm-76              [-1, 50, 768]           1,536
           Linear-77             [-1, 50, 3072]       2,362,368
             GELU-78             [-1, 50, 3072]               0
          Dropout-79             [-1, 50, 3072]               0
           Linear-80              [-1, 50, 768]       2,360,064
          Dropout-81              [-1, 50, 768]               0
              Mlp-82              [-1, 50, 768]               0
         Identity-83              [-1, 50, 768]               0
            Block-84              [-1, 50, 768]               0
        LayerNorm-85              [-1, 50, 768]           1,536
           Linear-86             [-1, 50, 2304]       1,771,776
          Dropout-87           [-1, 12, 50, 50]               0
           Linear-88              [-1, 50, 768]         590,592
          Dropout-89              [-1, 50, 768]               0
        Attention-90              [-1, 50, 768]               0
         Identity-91              [-1, 50, 768]               0
        LayerNorm-92              [-1, 50, 768]           1,536
           Linear-93             [-1, 50, 3072]       2,362,368
             GELU-94             [-1, 50, 3072]               0
          Dropout-95             [-1, 50, 3072]               0
           Linear-96              [-1, 50, 768]       2,360,064
          Dropout-97              [-1, 50, 768]               0
              Mlp-98              [-1, 50, 768]               0
         Identity-99              [-1, 50, 768]               0
           Block-100              [-1, 50, 768]               0
       LayerNorm-101              [-1, 50, 768]           1,536
          Linear-102             [-1, 50, 2304]       1,771,776
         Dropout-103           [-1, 12, 50, 50]               0
          Linear-104              [-1, 50, 768]         590,592
         Dropout-105              [-1, 50, 768]               0
       Attention-106              [-1, 50, 768]               0
        Identity-107              [-1, 50, 768]               0
       LayerNorm-108              [-1, 50, 768]           1,536
          Linear-109             [-1, 50, 3072]       2,362,368
            GELU-110             [-1, 50, 3072]               0
         Dropout-111             [-1, 50, 3072]               0
          Linear-112              [-1, 50, 768]       2,360,064
         Dropout-113              [-1, 50, 768]               0
             Mlp-114              [-1, 50, 768]               0
        Identity-115              [-1, 50, 768]               0
           Block-116              [-1, 50, 768]               0
       LayerNorm-117              [-1, 50, 768]           1,536
          Linear-118             [-1, 50, 2304]       1,771,776
         Dropout-119           [-1, 12, 50, 50]               0
          Linear-120              [-1, 50, 768]         590,592
         Dropout-121              [-1, 50, 768]               0
       Attention-122              [-1, 50, 768]               0
        Identity-123              [-1, 50, 768]               0
       LayerNorm-124              [-1, 50, 768]           1,536
          Linear-125             [-1, 50, 3072]       2,362,368
            GELU-126             [-1, 50, 3072]               0
         Dropout-127             [-1, 50, 3072]               0
          Linear-128              [-1, 50, 768]       2,360,064
         Dropout-129              [-1, 50, 768]               0
             Mlp-130              [-1, 50, 768]               0
        Identity-131              [-1, 50, 768]               0
           Block-132              [-1, 50, 768]               0
       LayerNorm-133              [-1, 50, 768]           1,536
          Linear-134             [-1, 50, 2304]       1,771,776
         Dropout-135           [-1, 12, 50, 50]               0
          Linear-136              [-1, 50, 768]         590,592
         Dropout-137              [-1, 50, 768]               0
       Attention-138              [-1, 50, 768]               0
        Identity-139              [-1, 50, 768]               0
       LayerNorm-140              [-1, 50, 768]           1,536
          Linear-141             [-1, 50, 3072]       2,362,368
            GELU-142             [-1, 50, 3072]               0
         Dropout-143             [-1, 50, 3072]               0
          Linear-144              [-1, 50, 768]       2,360,064
         Dropout-145              [-1, 50, 768]               0
             Mlp-146              [-1, 50, 768]               0
        Identity-147              [-1, 50, 768]               0
           Block-148              [-1, 50, 768]               0
       LayerNorm-149              [-1, 50, 768]           1,536
          Linear-150             [-1, 50, 2304]       1,771,776
         Dropout-151           [-1, 12, 50, 50]               0
          Linear-152              [-1, 50, 768]         590,592
         Dropout-153              [-1, 50, 768]               0
       Attention-154              [-1, 50, 768]               0
        Identity-155              [-1, 50, 768]               0
       LayerNorm-156              [-1, 50, 768]           1,536
          Linear-157             [-1, 50, 3072]       2,362,368
            GELU-158             [-1, 50, 3072]               0
         Dropout-159             [-1, 50, 3072]               0
          Linear-160              [-1, 50, 768]       2,360,064
         Dropout-161              [-1, 50, 768]               0
             Mlp-162              [-1, 50, 768]               0
        Identity-163              [-1, 50, 768]               0
           Block-164              [-1, 50, 768]               0
       LayerNorm-165              [-1, 50, 768]           1,536
          Linear-166             [-1, 50, 2304]       1,771,776
         Dropout-167           [-1, 12, 50, 50]               0
          Linear-168              [-1, 50, 768]         590,592
         Dropout-169              [-1, 50, 768]               0
       Attention-170              [-1, 50, 768]               0
        Identity-171              [-1, 50, 768]               0
       LayerNorm-172              [-1, 50, 768]           1,536
          Linear-173             [-1, 50, 3072]       2,362,368
            GELU-174             [-1, 50, 3072]               0
         Dropout-175             [-1, 50, 3072]               0
          Linear-176              [-1, 50, 768]       2,360,064
         Dropout-177              [-1, 50, 768]               0
             Mlp-178              [-1, 50, 768]               0
        Identity-179              [-1, 50, 768]               0
           Block-180              [-1, 50, 768]               0
       LayerNorm-181              [-1, 50, 768]           1,536
          Linear-182             [-1, 50, 2304]       1,771,776
         Dropout-183           [-1, 12, 50, 50]               0
          Linear-184              [-1, 50, 768]         590,592
         Dropout-185              [-1, 50, 768]               0
       Attention-186              [-1, 50, 768]               0
        Identity-187              [-1, 50, 768]               0
       LayerNorm-188              [-1, 50, 768]           1,536
          Linear-189             [-1, 50, 3072]       2,362,368
            GELU-190             [-1, 50, 3072]               0
         Dropout-191             [-1, 50, 3072]               0
          Linear-192              [-1, 50, 768]       2,360,064
         Dropout-193              [-1, 50, 768]               0
             Mlp-194              [-1, 50, 768]               0
        Identity-195              [-1, 50, 768]               0
           Block-196              [-1, 50, 768]               0
       LayerNorm-197              [-1, 50, 768]           1,536
        Identity-198                  [-1, 768]               0
          Linear-199                    [-1, 5]           3,845
================================================================

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]。

Panda

代码实现如下:

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计算公式: Q = x W , K = x W K , V = x W V Q=xW_,K=xW_K,V=xW_V Q=xW,K=xWK,V=xWV
x o u t = s o f t m a x ( Q K T h ) ∗ V ∗ W o + x x_{out}=softmax(\frac{QK^T}{\sqrt{h}})*V*W_o+x xout=softmax(h QKT)VWo+x

self-attention的结构示例如下:

Panda
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] 如 [batch,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) #每一patch进行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)  #经过一层FC
        x = self.proj_drop(x)  #Dropout
        return x

MLP(FFN)模块

一个MLP模块的结构如下:

Panda
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的结构如下:

Panda
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。

网络结构

Panda

attention和multi-head-attention结构:

Panda

计算过程:

Panda

计算复杂度对比

Panda

Transformer的参数量和计算量

值得注意的是,模型具体的延时 (Latency) 指标也很重要,相同 FLOPs 的两个模型,它们的延时可能会差出很远来。因为 FLOPs 只考虑模型总的计算量,而不考虑内存访问成本 (memory access cost, MAC) 和并行度 (degree of parallelism)。

transformer模型由L个相同的层组成,每个层分为两部分:self-attention块和MLP块。

为表示方便,下面统一记transformer模型的层数为 l l l,隐藏层维度为 h h h,注意力头数为 a a a。词表大小为 V V V,训练数据的批次大小为 b b b,序列长度为 s s s

Transformer的参数量

self-attention块的模型参数有Q、K、V的权重矩阵Wq、Wk、Wv和偏置,输出权重矩阵Wo和偏置,4个权重矩阵的形状为 [ h , h ] [h,h] [h,h],4个偏置的形状为 [ h ] [h] [h]。所以self- attention块的参数量为 4 h 2 + 4 h 4h^{2}+4h 4h2+4h

MLP块由2个线性层组成,一般地,第一个线性层是先将维度从 h h h映射到 4 h 4h 4h,第二个线性层再将维度从 4 h 4h 4h映射到 h h h。第一个线性层的权重矩阵W1的形状为 [ h , 4 h ] [h,4h] [h,4h],偏置的形状为 [ 4 h ] [4h] [4h]。第二个线性层权重矩阵W2的形状为 [ 4 h , h ] [4h,h] [4h,h],偏置形状为 [ h ] [h] [h]。MLP块的参数量为 8 h 2 + 5 h 8h^{2}+5h 8h2+5h

self-attention块和MLP块各有一个layer normalization,包含了2个可训练模型参数:缩放参数 γ \gamma γ和平移参数 β \beta β,形状都是 [ h ] [h] [h]。2个layer normalization的参数量为 4 h 4h 4h

所以,每个transformer层的参数量为 4 h 2 + 4 h + 8 h 2 + 5 h + 4 h = 12 h 2 + 13 h 4h^{2}+4h+ 8h^{2}+5h+4h=12h^{2}+13h 4h2+4h+8h2+5h+4h=12h2+13h

除此之外,词嵌入矩阵的参数量也较多,词向量维度通常等于隐藏层维度 h h h,词嵌入矩阵的参数量为 V h Vh Vh。最后的输出层的权重矩阵通常与词嵌入矩阵是参数共享的。

综上, l l l层transformer模型的可训练模型参数量为 l ( 12 h 2 + 13 h ) + V h l(12h^{2}+13h)+Vh l(12h2+13h)+Vh。当隐藏维度 h h h较大时,可以忽略一次项,模型参数量近似为 12 l h 2 12lh^{2} 12lh2

Transformer的显存占用

推理的显存占用明显低于训练阶段。

1.推理阶段: 2 Φ 2\Phi bytes
显存主要来源于模型参数,如果使用float16进行推理,由于float16数据类型的元素占2个bytes,设模型参数量为 Φ \Phi Φ,则显存为 2 Φ 2\Phi bytes。此外,输入数据也需要放到GPU上,还有一些中间结果(推理过程中的中间结果用完会尽快释放掉),不过这部分占用的显存很小,可以忽略。

2.训练阶段: 20 Φ 20\Phi 20Φ bytes
占用显存的大头主要分为四部分:模型参数、前向计算过程中产生的中间激活、后向传递计算得到的梯度、优化器状态。
训练大模型时通常会采用AdamW优化器,并用混合精度训练来加速训练,基于这个前提分析显存占用。
在一次训练迭代中,每个可训练模型参数都会对应1个梯度,并对应2个优化器状态(Adam优化器梯度的一阶动量和二阶动量)。设模型参数量为 Φ \Phi Φ,那么梯度的元素数量为 Φ \Phi Φ,AdamW优化器的元素数量为 2 Φ 2\Phi 。float16数据类型的元素占2个bytes,float32数据类型的元素占4个bytes。在混合精度训练中,会使用float16的模型参数进行前向传递和后向传递,计算得到float16的梯度;在优化器更新模型参数时,会使用float32的优化器状态、float32的梯度、float32的模型参数来更新模型参数。因此,对于每个可训练模型参数,占用了weight、gradients、Adam states分别 ( 2 + 4 ) + ( 2 + 4 ) + ( 4 + 4 ) = 20 (2+4)+(2+4)+(4+4)=20 (2+4)+(2+4)+(4+4)=20 bytes。

Transformer的计算量FLOPs

FLOPs,floating point operations,表示浮点数运算次数,衡量了计算量的大小。
计算量主要包括self-attention块、MLP、logits三部分的计算。

在这里插入图片描述

  • 13
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Vision Transformer (ViT)是一种基于Transformer的模型,用于处理计算机视觉任务。这个模型的灵感来自于自然语言处理领域的Transformer模型。ViT将图像的像素转换为序列数据,然后使用Transformer编码器来学习图像的特征表示。 ViT的关键思想是将图像分割为固定大小的图块,并将这些图块重新排列成一维序列。然后,ViT使用一个嵌入层将每个图块映射到一个更高维度的向量表示。这些向量表示被输入到Transformer编码器中进行特征提取和建模。 在ViT中,位置信息的嵌入也是非常重要的。因为Transformer模型不具备对位置信息的直接感知能力,所以需要通过位置嵌入来提供图像中每个图块的位置信息。这样,Transformer编码器就能够在处理图像时保持空间结构的关联性。 通过将图像像素分割为图块,并使用Transformer编码器进行特征提取和建模,ViT能够捕捉到图像中的全局信息和局部上下文,从而在计算机视觉任务中取得了很好的表现。 如果你想深入了解ViT的细节和原理,可以参考引用中关于ViT的论文和引用中关于Transformer编码器结构的详细解析。另外,引用中的文章也提供了关于Transformer位置嵌入的解读,可以进一步增进你对ViT的理解。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [【深度学习】详解 Vision Transformer (ViT)](https://blog.csdn.net/qq_39478403/article/details/118704747)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值