• swin_transformer源码详解


    注:为了更加实例化的说明,本文假设输入图像大小为(224,224,3)

    整体架构

            对于一张224*224的图像,首先,经过4*4的卷积,将图像维度化为 4,56,56,128的特征图,对特征图维度进行变换,得到4*3136*128的图像,即对图像进行了embeding,然后将图像输入transforer block,将特征图转变为8*8的窗口,进行注意力机制的计算,一个transformer block包含窗口自注意力W-MAS,计算8*8窗口内部的特征和滑动窗口自注意力SW-MSA,计算窗口间的特征,经过transformer的计算后,再进行patch mergeing将特征图大小减半,类似于卷积。

     

     

    1.图像数据patch编码

            首先,对于输入的图像,假设为224*224,我们采用4*4的卷积,然后将图像进行flatten,形成一个个patch,最后输出维度为batch_size * HW * Channels,H=W=224/4

    代码如下:

    1. class PatchEmbed(nn.Module):
    2. r""" Image to Patch Embedding
    3. Args:
    4. img_size (int): Image size. Default: 224.
    5. patch_size (int): Patch token size. Default: 4.
    6. in_chans (int): Number of input image channels. Default: 3.
    7. embed_dim (int): Number of linear projection output channels. Default: 96.
    8. norm_layer (nn.Module, optional): Normalization layer. Default: None
    9. """
    10. def __init__(self, img_size=224, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None):
    11. super().__init__()
    12. img_size = to_2tuple(img_size)
    13. patch_size = to_2tuple(patch_size)
    14. patches_resolution = [img_size[0] // patch_size[0], img_size[1] // patch_size[1]]
    15. self.img_size = img_size
    16. self.patch_size = patch_size
    17. self.patches_resolution = patches_resolution
    18. self.num_patches = patches_resolution[0] * patches_resolution[1]
    19. self.in_chans = in_chans
    20. self.embed_dim = embed_dim
    21. # in_channels:3,out_channels:128
    22. self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
    23. if norm_layer is not None:
    24. self.norm = norm_layer(embed_dim)
    25. else:
    26. self.norm = None
    27. def forward(self, x):
    28. B, C, H, W = x.shape
    29. # FIXME look at relaxing size constraints
    30. assert H == self.img_size[0] and W == self.img_size[1], \
    31. f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
    32. # 卷积
    33. x = self.proj(x).flatten(2).transpose(1, 2) # B Ph*Pw C
    34. # print(x.shape) #4 3136 96 其中3136就是 224/4 * 224/4 相当于有这么长的序列,其中每个元素是96维向量
    35. if self.norm is not None:
    36. x = self.norm(x)
    37. # print(x.shape)
    38. return x
    39. def flops(self):
    40. Ho, Wo = self.patches_resolution
    41. flops = Ho * Wo * self.embed_dim * self.in_chans * (self.patch_size[0] * self.patch_size[1])
    42. if self.norm is not None:
    43. flops += Ho * Wo * self.embed_dim
    44. return flops

    3.transformer block

    一个transformer block由w-MSA和SW-MSA组成 

    W-MSA/SW-MSA

            输入维度为4,3136,128的序列x,首先将其维度变换为4,56,56,128,再经过维度变换,将维度变成 256, 49, 128,即表示,有256个特征图,每个特征图有49个tokens,每个token是128维的向量。

            首先做W-MSA,对于W-SMA,不对窗口进行偏移,经过多头注意力的计算,得到结果,对于SW-MSA,窗口进行偏移,加入mask后,做相同的多头注意力的计算。最后将窗口再偏移回去。

             多头注意力:首先构造维度为256, 4, 49, 32的q,k,v辅助向量,256表示有256个特征图,4表示有4个head,49表示有49个tokens,32表示,每个头32个向量,然后经过多头注意力的计算,其中,会加入相对位置编码

            

    1. class WindowAttention(nn.Module):
    2. r""" Window based multi-head self attention (W-MSA) module with relative position bias.
    3. It supports both of shifted and non-shifted window.
    4. Args:
    5. dim (int): Number of input channels.
    6. window_size (tuple[int]): The height and width of the window.
    7. num_heads (int): Number of attention heads.
    8. qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
    9. qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set
    10. attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
    11. proj_drop (float, optional): Dropout ratio of output. Default: 0.0
    12. """
    13. def __init__(self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0., proj_drop=0.):
    14. super().__init__()
    15. self.dim = dim
    16. self.window_size = window_size # Wh, Ww
    17. self.num_heads = num_heads
    18. head_dim = dim // num_heads
    19. self.scale = qk_scale or head_dim ** -0.5
    20. # define a parameter table of relative position bias
    21. self.relative_position_bias_table = nn.Parameter(
    22. torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)) # 2*Wh-1 * 2*Ww-1, nH
    23. # get pair-wise relative position index for each token inside the window
    24. coords_h = torch.arange(self.window_size[0])
    25. coords_w = torch.arange(self.window_size[1])
    26. coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
    27. coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
    28. relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
    29. relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
    30. relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0
    31. relative_coords[:, :, 1] += self.window_size[1] - 1
    32. relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
    33. relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
    34. self.register_buffer("relative_position_index", relative_position_index)
    35. self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
    36. self.attn_drop = nn.Dropout(attn_drop)
    37. self.proj = nn.Linear(dim, dim)
    38. self.proj_drop = nn.Dropout(proj_drop)
    39. trunc_normal_(self.relative_position_bias_table, std=.02)
    40. self.softmax = nn.Softmax(dim=-1)
    41. def forward(self, x, mask=None):
    42. """
    43. Args:
    44. x: input features with shape of (num_windows*B, N, C)
    45. mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None
    46. """
    47. # num_windows, Wh*Ww, Wh*Ww
    48. B_, N, C = x.shape
    49. # 3, 256, 4, 49, 32
    50. qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
    51. # print(qkv.shape)
    52. # 256, 4, 49, 32
    53. q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
    54. # print(q.shape)
    55. # print(k.shape)
    56. # print(v.shape)
    57. # 256, 4, 49, 49
    58. q = q * self.scale
    59. attn = (q @ k.transpose(-2, -1))
    60. # print(attn.shape)
    61. # 相对位置编码 49*49*4
    62. relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(
    63. self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1) # Wh*Ww,Wh*Ww,nH
    64. # print(relative_position_bias.shape)
    65. # 4, 49, 49
    66. relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
    67. # print(relative_position_bias.shape)
    68. # 加入位置编码 256, 4, 49, 49
    69. attn = attn + relative_position_bias.unsqueeze(0)
    70. # print(attn.shape)
    71. if mask is not None:
    72. nW = mask.shape[0]
    73. attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0)
    74. attn = attn.view(-1, self.num_heads, N, N)
    75. attn = self.softmax(attn)
    76. else:
    77. attn = self.softmax(attn)
    78. # dropout层
    79. attn = self.attn_drop(attn)
    80. # print(attn.shape)
    81. # qkv
    82. x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
    83. # print(x.shape)
    84. # 全连接层
    85. x = self.proj(x)
    86. # print(x.shape)
    87. # dropout层
    88. x = self.proj_drop(x)
    89. # print(x.shape)
    90. return x

    4.下采样 

             下采样操作,但是不同于池化,这个相当于间接的 (对H和W维度进行间隔采样后拼接在一起,得到H/2,W/2,C*4)

    代码如下:

    1. class PatchMerging(nn.Module):
    2. r""" Patch Merging Layer.
    3. Args:
    4. input_resolution (tuple[int]): Resolution of input feature.
    5. dim (int): Number of input channels.
    6. norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
    7. """
    8. def __init__(self, input_resolution, dim, norm_layer=nn.LayerNorm):
    9. super().__init__()
    10. self.input_resolution = input_resolution
    11. self.dim = dim
    12. self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
    13. self.norm = norm_layer(4 * dim)
    14. def forward(self, x):
    15. """
    16. x: B, H*W, C
    17. """
    18. H, W = self.input_resolution
    19. B, L, C = x.shape
    20. assert L == H * W, "input feature has wrong size"
    21. assert H % 2 == 0 and W % 2 == 0, f"x size ({H}*{W}) are not even."
    22. x = x.view(B, H, W, C)
    23. # 间隔采样
    24. x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C
    25. x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C
    26. x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C
    27. x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C
    28. x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C
    29. x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C
    30. x = self.norm(x)
    31. x = self.reduction(x)
    32. return x
    33. def extra_repr(self) -> str:
    34. return f"input_resolution={self.input_resolution}, dim={self.dim}"
    35. def flops(self):
    36. H, W = self.input_resolution
    37. flops = H * W * self.dim
    38. flops += (H // 2) * (W // 2) * 4 * self.dim * 2 * self.dim
    39. return flops

     

             

     

  • 相关阅读:
    mybatis 09: 动态sql --- part1
    web前端面试-10大经典题(HTML基础)
    数据中台的前世今生(一):数据仓库——数据应用需求的涌现
    【Python 千题 —— 基础篇】输出可以被5整除的数
    天天都在说的用户画像到底该如何构建?看这篇就够了!
    k8s(13) : 备份配置
    git学习笔记 - 上传文件
    UnityShader-深度纹理(理解以及遇到的问题)
    非零基础自学Java (老师:韩顺平) 第7章 面向对象编程(基础部分) 7.1 类与对象
    C语言程序设计笔记(浙大翁恺版) 第四周:循环
  • 原文地址:https://blog.csdn.net/qq_52053775/article/details/126353794