论文阅读 Vision Transformer - VIT

这篇具有很好参考价值的文章主要介绍了论文阅读 Vision Transformer - VIT。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

1 摘要

1.1 核心

通过将图像切成patch线形层编码成token特征编码的方法,用transformer的encoder来做图像分类

2 模型架构

2.1 概览

论文阅读 Vision Transformer - VIT,论文阅读,transformer,深度学习

2.2 对应CV的特定修改和相关理解

解决问题:

  1. transformer输入限制: 由于自注意力+backbone,算法复杂度为o(n²),token长度一般要<512才足够运算
    解决:a) 将图片转为token输入 b) 将特征图转为token输入 c)√ 切patch转为token输入
  2. transformer无先验知识:卷积存在平移不变性(同特征同卷积核同结果)和局部相似性(相邻特征相似结果),
    而transformer无卷积核概念,只有整个编解码器,需要从头学
    解决:大量数据训练
  3. cv的各种自注意力机制需要复杂工程实现:
    解决:直接用整个transformer模块
  4. 分类head:
    解决:直接沿用transformer cls token
  5. position编码:
    解决:1D编码

pipeline:
224x224输入切成16x16patch进行位置编码和线性编码后增加cls token 一起输入的encoder encoder中有L个selfattention模块
输出的cls token为目标类别

3 代码

如果理解了transformer,看完这个结构感觉真的很简单,这篇论文也只是开山之作,没有特别复杂的结构,所以想到代码里看看。

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 FeedForward(nn.Module):
    def __init__(self, dim, hidden_dim, dropout = 0.):
        super().__init__()
        self.net = nn.Sequential(
            nn.LayerNorm(dim),
            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.norm = nn.LayerNorm(dim)

        self.attend = nn.Softmax(dim = -1)
        self.dropout = nn.Dropout(dropout)

        # linear(1024 , 3072)
        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):
        # [1, 65, 1024]
        x = self.norm(x)
        # [1, 65, 1024]
        qkv = self.to_qkv(x).chunk(3, dim = -1)
        # self.to_qkv(x)                [1, 65, 3072]
        # self.to_qkv(x).chunk(3,-1)    [3, 1, 65, 1024]
        q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> b h n d', h = self.heads), qkv)
        # q,k,v                         [1, 65, 1024] -> [1, 16, 65, 64]
        # 把 65个1024的特征分为 heads个65个d维的特征 然后每个heads去分别有自己要处理的隐藏层,对不同的特征建立不同学习能力
        dots = torch.matmul(q, k.transpose(-1, -2)) * self.scale
        # [1, 16, 65, 64] * [1, 16, 64, 65] -> [1, 16, 65, 65]
        # scale 保证在softmax前所有的值都不太大

        attn = self.attend(dots)
        # softmax [1, 16, 65, 65]
        
        attn = self.dropout(attn)
        # dropout [1, 16, 65, 65]
        
        out = torch.matmul(attn, v)
        # out [1, 16, 65, 64]
        
        out = rearrange(out, 'b h n d -> b n (h d)')
        # out [1, 65, 1024]
        
        return self.to_out(out)
        # out [1, 65, 1024]
        

class Transformer(nn.Module):
    def __init__(self, dim, depth, heads, dim_head, mlp_dim, dropout = 0.):
        super().__init__()
        self.norm = nn.LayerNorm(dim)
        self.layers = nn.ModuleList([])
        for _ in range(depth):
            self.layers.append(nn.ModuleList([
                Attention(dim, heads = heads, dim_head = dim_head, dropout = dropout),
                FeedForward(dim, mlp_dim, dropout = dropout)
            ]))

    def forward(self, x):
        # [1, 65, 1024]
        for attn, ff in self.layers:
            # [1, 65, 1024]
            x = attn(x) + x
            # [1, 65, 1024]
            x = ff(x) + x

        # [1, 65, 1024]
        return self.norm(x)
        # shape不会改变

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)'

        # num_patches   64
        # patch_dim     3072
        # dim           1024
        self.to_patch_embedding = nn.Sequential(
            #Rearrange是einops中的一个方法
            # einops:灵活和强大的张量操作,可读性强和可靠性好的代码。支持numpy、pytorch、tensorflow等。
            # 代码中Rearrage的意思是将传入的image(3,224,224),按照(3,(h,p1),(w,p2))也就是224=hp1,224 = wp2,接着把shape变成b (h w) (p1 p2 c)格式的,这样把图片分成了每个patch并且将patch拉长,方便下一步的全连接层
            # 还有一种方法是采用窗口为16*16,stride 16的卷积核提取每个patch,然后再flatten送入全连接层。
            Rearrange('b c (h p1) (w p2) -> b (h w) (p1 p2 c)', p1 = patch_height, p2 = patch_width),
            nn.LayerNorm(patch_dim),
            nn.Linear(patch_dim, dim),
            nn.LayerNorm(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.Linear(dim, num_classes)

    def forward(self, img):
        # 1. [1, 3, 256, 256]       输入img
        x = self.to_patch_embedding(img)
        # 2. [1, 64, 1024]          patch embd
        b, n, _ = x.shape
        # 3. [1, 1, 1024]           cls_tokens
        cls_tokens = repeat(self.cls_token, '1 1 d -> b 1 d', b = b)
        # 4. [1, 65, 1024]          cat [cls_tokens, x]
        x = torch.cat((cls_tokens, x), dim=1)
        # 5. [1, 65, 1024]          add [x] [pos_embedding]
        x += self.pos_embedding[:, :(n + 1)]
        # 6. [1, 65, 1024]          dropout
        x = self.dropout(x)
        # 7. [1, 65, 1024]          N * transformer
        x = self.transformer(x)
        # 8. [1,1024]               cls_x output
        x = x.mean(dim = 1) if self.pool == 'mean' else x[:, 0]
        # 9. [1,1024]               cls_x output mean
        x = self.to_latent(x)
        # 10.[1,1024]               nn.Identity()不改变输入和输出 占位层
        return self.mlp_head(x)
        # 11.[1,cls]                mlp_cls_head

4 总结

multihead和我原有的理解偏差修正。
我以为的是QKV会有N块相同的copy(),每一份去做后续的linear等操作。
代码里是直接用linear将QKV分为一整个大块,用permute/rearrange的操作切成了N块,f(Q,K)之后再恢复成一整个大块,很强。文章来源地址https://www.toymoban.com/news/detail-791085.html

到了这里,关于论文阅读 Vision Transformer - VIT的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Swin-transformer论文阅读笔记(Swin Transformer: Hierarchical Vision Transformer using Shifted Windows)

    论文标题:Swin Transformer: Hierarchical Vision Transformer using Shifted Windows 论文作者:Ze Liu, Yutong Lin, Yue Cao, Han Hu, Yixuan Wei, Zheng Zhang, Stephen Lin, Baining Guo 论文来源:ICCV 2021,Paper 代码来源:Code 目录 1. 背景介绍 2. 研究现状 CNN及其变体 基于自注意的骨干架构 自注意/Transformer来补充CN

    2024年02月07日
    浏览(37)
  • Vision Transformer(VIT)

    Vision Transformer(ViT)是一种新兴的图像分类模型,它使用了类似于自然语言处理中的Transformer的结构来处理图像。这种方法通过将输入图像分解成一组图像块,并将这些块变换为一组向量来处理图像。然后,这些向量被输入到Transformer编码器中,以便对它们进行进一步的处理。

    2024年02月07日
    浏览(36)
  • Vision Transformer (ViT)

    生成式模型与判别式模型 生成式模型,又称概率模型 ,是指 通过学习数据的分布来建立模型P(y|x) ,然后利用该模型来生成新的数据。生成式模型的典型代表是 朴素贝叶斯模型 ,该模型通过学习数据的分布来建立概率模型,然后利用该模型来生成新的数据。 判别式模型,又

    2024年02月15日
    浏览(47)
  • Vision Transformer (ViT)介绍

    paper:An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale 把transformer直接应用于图像块序列,也可以在图像分类任务上表现很好。 通过在大数据集上预训练,然后迁移到中等规模和小规模数据集上,ViT可以取得和SOTA的卷积网络同样出色(甚至更好)的结果,同时需要更

    2024年02月13日
    浏览(43)
  • Vision Transformer(VIT)调研

    综述参考:https://zhuanlan.zhihu.com/p/598785102 2020 VIT 代码库 https://github.com/lucidrains/vit-pytorch 只有分类任务,有训练的测试。有各种各样的vit模型结构。 原文 https://arxiv.org/abs/2010.11929 2021 Swim Transformer https://arxiv.org/abs/2103.14030 v2 https://arxiv.org/pdf/2111.09883.pdf code and pretrain_model https:/

    2023年04月11日
    浏览(40)
  • ViT-vision transformer

    介绍 Transformer最早是在NLP领域提出的,受此启发,Google将其用于图像,并对分类流程作尽量少的修改。 起源 :从机器翻译的角度来看,一个句子想要翻译好,必须考虑上下文的信息! 如:The animal didn’t cross the street because it was too tired将其翻译成中文,这里面就涉及了it这个

    2024年02月15日
    浏览(31)
  • EfficientViT: Memory Efficient Vision Transformer withCascaded Group Attention论文阅读

    高效的记忆视觉transformer与级联的群体注意 摘要。 视觉transformer由于其高模型能力而取得了巨大的成功。然而,它们卓越的性能伴随着沉重的计算成本,这使得它们不适合实时应用。在这篇论文中,我们提出了一个高速视觉transformer家族,名为EfficientViT。我们发现现有的tran

    2024年01月22日
    浏览(34)
  • 图解Vit 3:Vision Transformer——ViT模型全流程拆解

    先把上一篇中的遗留问题解释清楚:上图中,代码中的all_head_dim就是有多少head。把他们拼接起来。 Encoder在Multi-Head Self-Attention之后,维度一直是BND`,一直没有变。 不论是BN(Batch Normalization)还是LN(Layer Normalization),都是对batch来做的。只是他们的归一化方式不同。我们在求mea

    2024年02月16日
    浏览(31)
  • ViT: Vision transformer的cls token作用?

    知乎:Vision Transformer 超详细解读 (原理分析+代码解读)  CSDN:vit 中的 cls_token 与 position_embed 理解 CSDN:ViT为何引入cls_token CSDN:ViT中特殊class token的一些问题 Vision Transformer在一些任务上超越了CNN,得益于全局信息的聚合。在ViT论文中,作者引入了一个class token作为分类特征。

    2024年02月01日
    浏览(34)
  • 【计算机视觉】Vision Transformer (ViT)详细解析

    论文地址:An Image Is Worth 16x16 Words: Transformers For Image Recognition At Scale code地址:github.com/google-research/vision_transformer Transformer 最早提出是针对NLP领域的,并且在NLP领域引起了强烈的轰动。 提出ViT模型的这篇文章题名为 《An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale》

    2024年02月04日
    浏览(34)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包