• VIT(Vision Transformer)学习(二)- 基础代码学习


    理解都加在注释里了

    所有代码

    一、主体实现代码

    1. #生成一个类
    2. v = ViT(
    3. image_size = 224,#输入图像大小,宽和高
    4. patch_size = 16,#每个块的大小,宽和高
    5. num_classes = 1000,#拉平序列映射的向量长度
    6. dim = 1024,#维度
    7. depth = 6,#N,encoder*N
    8. heads = 16,#多头注意力机制分为多少个头,打到多少个子空间上
    9. mlp_dim = 2048,#MLP:前馈神经网络(Feed Forward) MLP的维度
    10. dropout = 0.1,#防止过拟合,https://blog.csdn.net/ningyanggege/article/details/83115811
    11. emb_dropout = 0.1#embedding层后的dropout
    12. )
    13. img = torch.randn(1, 3, 224, 224)
    14. preds = v(img) # (1, 1000)

    二、具体架构代码

    1. class ViT(nn.Module):
    2. #初始化函数
    3. 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.):
    4. super().__init__()
    5. image_height, image_width = pair(image_size) ## 224*224
    6. patch_height, patch_width = pair(patch_size)## 16 * 16
    7. assert image_height % patch_height == 0 and image_width % patch_width == 0, 'Image dimensions must be divisible by the patch size.'
    8. num_patches = (image_height // patch_height) * (image_width // patch_width)#patch个数 196个patch
    9. patch_dim = channels * patch_height * patch_width #通道数**768
    10. assert pool in {'cls', 'mean'}, 'pool type must be either cls (cls token) or mean (mean pooling)' #assert A,B 如果A出错则提示B。cls符号做多分类或pooling方式:token输出做池化做多分类
    11. self.to_patch_embedding = nn.Sequential(
    12. Rearrange('b c (h p1) (w p2) -> b (h w) (p1 p2 c)', p1 = patch_height, p2 = patch_width),#Rearrange函数是einops库自带的,作用:改变张量形状
    13. nn.Linear(patch_dim, dim),#patch_dim到encoder_dim映射
    14. )
    15. self.pos_embedding = nn.Parameter(torch.randn(1, num_patches + 1, dim))#生成cls和所有对应token对应的位置编码 1,197,1024
    16. self.cls_token = nn.Parameter(torch.randn(1, 1, dim))#cls token的初始化参数 1,1,1024
    17. self.dropout = nn.Dropout(emb_dropout)
    18. self.transformer = Transformer(dim, depth, heads, dim_head, mlp_dim, dropout)#完成输入后,将输入放入Transformer架构
    19. self.pool = pool
    20. self.to_latent = nn.Identity() #跳过连接的地方用这个层
    21. self.mlp_head = nn.Sequential(
    22. nn.LayerNorm(dim),#对每单个batch进行的归一化
    23. nn.Linear(dim, num_classes)#映射到类别数
    24. )
    25. def forward(self, img):
    26. x = self.to_patch_embedding(img) ## img 1 3(通道) 224 224 输出形状x : 1 196 1024
    27. b, n, _ = x.shape ##
    28. cls_tokens = repeat(self.cls_token, '() n d -> b n d', b = b) #1,1,1024
    29. x = torch.cat((cls_tokens, x), dim=1)#(token emdeding与patch emdeding拼接)1,197,1024
    30. x += self.pos_embedding[:, :(n + 1)]
    31. x = self.dropout(x)
    32. x = self.transformer(x)
    33. x = x.mean(dim = 1) if self.pool == 'mean' else x[:, 0]#mean:输出做mean池化;cls:取切片第0个元素cls符号
    34. x = self.to_latent(x)
    35. return self.mlp_head(x)

    三、Transformer实现

    1. class Transformer(nn.Module):
    2. def __init__(self, dim, depth, heads, dim_head, mlp_dim, dropout = 0.):
    3. super().__init__()
    4. self.layers = nn.ModuleList([])
    5. for _ in range(depth):
    6. #每一个encoder包含两个部分,一个Attention部分是多头注意力机制,一个FeedForward是前馈神经网络部分,preNorm是在之前做Norm
    7. self.layers.append(nn.ModuleList([
    8. PreNorm(dim, Attention(dim, heads = heads, dim_head = dim_head, dropout = dropout)),
    9. PreNorm(dim, FeedForward(dim, mlp_dim, dropout = dropout))
    10. ]))
    11. def forward(self, x):
    12. for attn, ff in self.layers:
    13. x = attn(x) + x
    14. x = ff(x) + x
    15. return x

    四、Attention部分理解

    1. class Attention(nn.Module):
    2. def __init__(self, dim, heads = 8, dim_head = 64, dropout = 0.):
    3. super().__init__()
    4. inner_dim = dim_head * heads
    5. project_out = not (heads == 1 and dim_head == dim)
    6. self.heads = heads
    7. self.scale = dim_head ** -0.5
    8. self.attend = nn.Softmax(dim = -1)#将张量的每个元素缩放到(0,1)区间且和为1
    9. self.to_qkv = nn.Linear(dim, inner_dim * 3, bias = False)
    10. self.to_out = nn.Sequential(
    11. nn.Linear(inner_dim, dim),
    12. nn.Dropout(dropout)
    13. ) if project_out else nn.Identity()
    14. def forward(self, x):
    15. qkv = self.to_qkv(x).chunk(3, dim = -1)## chunk:对tensor张量分块 x :1(一个图片) 197(196patch+1个cls) 1024(每一个token输入的Input embedding是1024) qkv最后是一个元组,tuple,长度是3,每个元素形状:1 197 1024
    16. q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> b h n d', h = self.heads), qkv)#把qkv分到多个子空间
    17. dots = torch.matmul(q, k.transpose(-1, -2)) * self.scale
    18. attn = self.attend(dots)
    19. out = torch.matmul(attn, v)
    20. out = rearrange(out, 'b h n d -> b n (h d)')
    21. return self.to_out(out)

  • 相关阅读:
    新手GitHub使用指南
    2023年之我拿起“java“ java基础进阶2
    Redis——》数据类型:zset(有序集合)
    【Python 千题 —— 基础篇】整数输入
    linux学习总结
    厨卫家居企业应该开展那些线上营销如何开展?
    《JavaSE-第十章》之抽象类与接口
    因发表不当言论,开源作者遭 OBS 项目社区封杀
    [NLP] LLM---<训练中文LLama2(四)方式一>对LLama2进行SFT微调
    C#的基本知识(1)
  • 原文地址:https://blog.csdn.net/weixin_61235989/article/details/133757448