当前位置:   article > 正文

swin_transformer源码详解_swin transformer源码

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

5.相对位置编码

有关swin transformer相对位置编码的理解:

假设window_size是7*7

那么窗口中共有49个patch,共有49*49个相对位置,每个相对位置有两个索引对应x和y两个方向,每个索引值的取值范围是[-6,6]。(第0行相对第6行,x索引相对值为-6;第6行相对第0行,x索引相对值为6;所以索引取值范围是[-6,6])

    # get pair-wise relative position index for each token inside the window
    coords_h = torch.arange(self.window_size[0])
    coords_w = torch.arange(self.window_size[1])
    coords = torch.stack(torch.meshgrid([coords_h, coords_w]))  # 2, Wh, Ww
    coords_flatten = torch.flatten(coords, 1)  # 2, Wh*Ww
    # 2, Wh*Ww, Wh*Ww, https://www.cnblogs.com/sgdd123/p/7603004.html
    relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :]  
    # Wh*Ww, Wh*Ww, 2, [i,j,:]表示窗口内第i个patch相对于第j个patch的坐标
    relative_coords = relative_coords.permute(1, 2, 0).contiguous()

此时,构建出来的relative_coords的shape是[49, 49, 2],[i, j, :]表示窗口内第i个patch相对于第j个patch的坐标。

由于此时索引取值范围中包含负值,可分别在每个方向上加上6,使得索引取值从0开始。此时,索引取值范围为[0,12]

    relative_coords[:, :, 0] += self.window_size[0] - 1  # shift to start from 0
    relative_coords[:, :, 1] += self.window_size[1] - 1

有了这些相对位置坐标之后,就可以根据这些坐标获取对应的position bias,即论文中公式(4)中的B:

这个时候可以构建一个shape为[13,13]的table,则当相对位置为(i,j)时,B=table[i, j]。(i,j的取值范围都是[0, 12]) 

由于论文中使用的时multi-head-self-attention,所以table[i, j]的值应该是一个维度为num_heads的一维向量。

在代码中,实现如下:(注意,此时的table将二维的位置关系,合并为了一维的位置关系)

    # define a parameter table of relative position bias  # shape : 2*Wh-1 * 2*Ww-1, nH
    self.relative_position_bias_table = nn.Parameter(
        torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads))

为了与table对应,根据相对位置坐标取值时,也需要将二维相对坐标(i, j)映射为一维相对坐标(i*13+j), 在代码中体现为:

     relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
    relative_position_index = relative_coords.sum(-1)  # Wh*Ww, Wh*Ww

最后,就可以根据映射后的坐标来对B进行取值了:

    relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(
        self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1)  # Wh*Ww,Wh*Ww,nH
    relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous()  # nH, Wh*Ww, Wh*Ww

附注:

将二维相对坐标(i, j)映射为一维相对坐标时,最简单的映射方式是将i和j相加,但这样无法区分(0, 2)和(2, 0),因为相加的结果都是2;所以作者采用了i*13+j这种方式,其中13 = 2*window_size - 1, 即j取值的最大值。类似于将一个二维数组打平后,每个元素的位置。

参考信息:

https://blog.csdn.net/weixin_42364196/article/details/119954379

         

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/371442
推荐阅读
相关标签
  

闽ICP备14008679号