当前位置:   article > 正文

Swin Transformer代码详解(必懂)

swin transformer代码

上一篇文章中我们写完了最难的两个数学原理部分,mask和相对位置编码的代码。本篇文章将讲解Swin的全部代码。文章仅供学习,若有纰漏请不吝赐教。全部代码放在文章最后。

我看这些代码的经验是跟着维度一点一点的串,当然只是个人经验。可以跟我下面的维度图走

整体框架 SwinTransformer类

        初始化函数

  1. class SwinTransformer(nn.Module):
  2. def __init__(self, patch_size=4, in_chans=3, num_classes=1000,
  3. embed_dim=96, depths=(2, 2, 6, 2), num_heads=(3, 6, 12, 24),
  4. window_size=7, mlp_ratio=4., qkv_bias=True,
  5. drop_rate=0., attn_drop_rate=0., drop_path_rate=0.1,
  6. norm_layer=nn.LayerNorm, patch_norm=True,
  7. use_checkpoint=False, **kwargs):

        参数中值得注意的是depths和num_heads,len(depths)作为Swin中的stage数,而depths中的每一个值代表每一个stage中有多少个Swin Transformer Block。需要注意的是一个block中只会有一个MSA,就是说W-MSA和SW-MSA必然存在于不同的Block。num_heads指的是在每一个stage中的所有Block中的MSA使用的头数,由默认值我们可以看到第一个stage中的MSA的头数是3个。checkpoint如果使用可以节省空间。

  1. self.num_classes = num_classes
  2. self.num_layers = len(depths) # stage数
  3. self.embed_dim = embed_dim
  4. self.patch_norm = patch_norm
  5. # stage4输出特征矩阵的channels
  6. self.num_features = int(embed_dim * 2 ** (self.num_layers - 1))
  7. self.mlp_ratio = mlp_ratio
  8. # 对应Patch partition和Linear Embedding
  9. self.patch_embed = PatchEmbed(
  10. patch_size=patch_size, in_c=in_chans, embed_dim=embed_dim,
  11. norm_layer=norm_layer if self.patch_norm else None)
  12. self.pos_drop = nn.Dropout(p=drop_rate)
  13. # stochastic depth
  14. dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule

        初始化中是一些简单的赋值,因为每层的patchmerging会将通道变为两倍,所以

self.num_features = int(embed_dim * 2 ** (self.num_layers - 1))

        drp是指drop_path_rate 在每一个Swin Transformer Block之中都不一样,它是一个递增序列

  1. self.layers = nn.ModuleList()
  2. for i_layer in range(self.num_layers):
  3. # downsample是Patch merging,并且在最后一个stage为None
  4. layers = BasicLayer(dim=int(embed_dim * 2 ** i_layer),
  5. depth=depths[i_layer],
  6. num_heads=num_heads[i_layer],
  7. window_size=window_size,
  8. mlp_ratio=self.mlp_ratio,
  9. qkv_bias=qkv_bias,
  10. drop=drop_rate,
  11. attn_drop=attn_drop_rate,
  12. drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])],
  13. norm_layer=norm_layer,
  14. downsample=PatchMerging if (i_layer < self.num_layers - 1) else None,
  15. use_checkpoint=use_checkpoint)
  16. self.layers.append(layers)
  17. self.norm = norm_layer(self.num_features)
  18. self.avgpool = nn.AdaptiveAvgPool1d(1) # 在这个分类任务中,用全局平均池化取代cls token
  19. self.head = nn.Linear(self.num_features, num_classes) if num_classes > 0 else nn.Identity()
  20. self.apply(self._init_weights)

        然后搭建我们的stage。代码与论文的区别在于每个stage包含的是Block和紧随其后的Patch Merging,因此在最后一个stage中就没有Patch merging

downsample=PatchMerging if (i_layer < self.num_layers - 1) else None

        并且拿走这一层所有block的dpr

drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])]

        然后还有正则化和全局平均池化,用来顶替Vit中的cls token,最后一个linear用来分类。

        权重初始化函数

  1. def _init_weights(self, m):
  2. if isinstance(m, nn.Linear):
  3. nn.init.trunc_normal_(m.weight, std=.02)
  4. if isinstance(m, nn.Linear) and m.bias is not None:
  5. nn.init.constant_(m.bias, 0)
  6. elif isinstance(m, nn.LayerNorm):
  7. nn.init.constant_(m.bias, 0)
  8. nn.init.constant_(m.weight, 1.0)

         forward函数

  1. def forward(self, x):
  2. # x: [B, L, C]
  3. x, H, W = self.patch_embed(x) # [B, HW, C]
  4. x = self.pos_drop(x)
  5. # 依次通过每个stage
  6. for layer in self.layers:
  7. x, H, W = layer(x, H, W)
  8. x = self.norm(x) # [B, L, C]
  9. x = self.avgpool(x.transpose(1, 2)) # [B, C, 1]
  10. x = torch.flatten(x, 1)
  11. x = self.head(x)
  12. return x

        layer的输入是[B, HW, C]

PatchEmbed类

        初始化函数

        

  1. class PatchEmbed(nn.Module):
  2. def __init__(self, patch_size=4, in_c=3, embed_dim=96, norm_layer=None):
  3. super().__init__()
  4. patch_size = (patch_size, patch_size)
  5. self.patch_size = patch_size
  6. self.in_chans = in_c
  7. self.embed_dim = embed_dim
  8. self.proj = nn.Conv2d(in_c, embed_dim, kernel_size=patch_size, stride=patch_size)
  9. self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()

         紧接着,我们来顺藤摸瓜摸一摸PatchEmbed函数,与Vit一样,通过一个卷积实现Embedding。

          forward函数

  

  1. def forward(self, x):
  2. _, _, H, W = x.shape
  3. # padding
  4. # 如果输入图片的H,W不是patch_size的整数倍,需要进行padding
  5. pad_input = (H % self.patch_size[0] != 0) or (W % self.patch_size[1] != 0)
  6. if pad_input:
  7. # (W_left, W_right, H_top,H_bottom, C_front, C_back)
  8. # pad是从后往前,从左往右,从上往下,原顺序是(B,C,H,W) pad顺序就是(W,H,C)
  9. x = F.pad(x, (0, self.patch_size[1] - W % self.patch_size[1],
  10. 0, self.patch_size[0] - H % self.patch_size[0],
  11. 0, 0))
  12. # 下采样patch_size
  13. x = self.proj(x)
  14. _, _, H, W = x.shape
  15. # flatten: [B, C, H, W] -> [B, C, HW]
  16. # transpose: [B, C, HW] -> [B, HW, C]
  17. x = x.flatten(2).transpose(1, 2)
  18. x = self.norm(x)
  19. return x, H, W # 这里是经过padding的H和W

        这里需要注意的就是为了解决多尺度问题,需要使用padding。整体来说没有难点,我在注释已经写的很清楚了。返回的x的维度是[B, HW, C]。

BasicLayer类

        初始化函数

  1. class BasicLayer(nn.Module):
  2. def __init__(self, dim, depth, num_heads, window_size,
  3. mlp_ratio=4., qkv_bias=True, drop=0., attn_drop=0.,
  4. drop_path=0., norm_layer=nn.LayerNorm, downsample=None, use_checkpoint=False):
  5. super().__init__()
  6. self.dim = dim
  7. self.depth = depth
  8. self.window_size = window_size
  9. self.use_checkpoint = use_checkpoint
  10. self.shift_size = window_size // 2 # 移动尺寸

        下来到重点了,depth是这个stage中的block数,downsample就是patchmerging的意思,刚刚我解释过如果最后一层就不会有patchmerging。这里的shift_size在后面很关键,我们判断一个MSA是W-MSA还是SW-MSA全靠shift_size存不存在判断。

  1. self.blocks = nn.ModuleList([
  2. SwinTransformerBlock(
  3. dim=dim,
  4. num_heads=num_heads,
  5. window_size=window_size,
  6. shift_size=0 if (i % 2 == 0) else self.shift_size,
  7. mlp_ratio=mlp_ratio,
  8. qkv_bias=qkv_bias,
  9. drop=drop,
  10. attn_drop=attn_drop,
  11. drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,
  12. norm_layer=norm_layer)
  13. for i in range(depth)])
  14. # patch merging layer
  15. if downsample is not None:
  16. self.downsample = downsample(dim=dim, norm_layer=norm_layer)
  17. else:
  18. self.downsample = None

        然后搭建depth个block,因为W-MSA和SW-MSA肯定是成对出现,所以用i%2来判断,downsample我们也刚刚提过。   

create_mask函数

  1. def create_mask(self, x, H, W):
  2. # calculate attention mask for SW-MSA
  3. # 保证Hp和Wp是window_size的整数倍
  4. Hp = int(np.ceil(H / self.window_size)) * self.window_size
  5. Wp = int(np.ceil(W / self.window_size)) * self.window_size
  6. # 拥有和feature map一样的通道排列顺序,方便后续window_partition
  7. img_mask = torch.zeros((1, Hp, Wp, 1), device=x.device) # [1, Hp, Wp, 1]
  8. # 将窗口切分,然后进行标号
  9. h_slices = (slice(0, -self.window_size),
  10. slice(-self.window_size, -self.shift_size),
  11. slice(-self.shift_size, None))
  12. w_slices = (slice(0, -self.window_size),
  13. slice(-self.window_size, -self.shift_size),
  14. slice(-self.shift_size, None))
  15. cnt = 0
  16. for h in h_slices:
  17. for w in w_slices:
  18. img_mask[:, h, w, :] = cnt
  19. cnt += 1
  20. mask_windows = window_partition(img_mask, self.window_size) # [nW, Mh, Mw, 1] 划为窗口
  21. mask_windows = mask_windows.view(-1, self.window_size * self.window_size) # [nW, Mh*Mw] 窗口展平
  22. attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2) # [nW, 1, Mh*Mw] - [nW, Mh*Mw, 1]
  23. # [nW, Mh*Mw, Mh*Mw]
  24. attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0))
  25. return attn_mask

        在我的上一篇文章中花了大量精力详细讲解了create_mask和相对位置编码两个函数,这里就不细说了。x返回时的维度不变,仍然是[B, HW, C]。

        forward函数

  1. def forward(self, x, H, W):
  2. # 先创建一个mask蒙版,在图像尺寸不变的情况下蒙版也不改变
  3. attn_mask = self.create_mask(x, H, W) # [nW, Mh*Mw, Mh*Mw]
  4. for blk in self.blocks:
  5. blk.H, blk.W = H, W
  6. # 默认不适用checkpoint方法
  7. if not torch.jit.is_scripting() and self.use_checkpoint:
  8. x = checkpoint.checkpoint(blk, x, attn_mask)
  9. else:
  10. x = blk(x, attn_mask)
  11. if self.downsample is not None:
  12. x = self.downsample(x, H, W)
  13. H, W = (H + 1) // 2, (W + 1) // 2
  14. return x, H, W

        在一个stage中特征图的尺寸肯定是不会改变的,shift_size也不会改变,所以生成的蒙版可以一直使用。这里不用管checkpoint,值得注意的是最后的 

H, W = (H + 1) // 2, (W + 1) // 2

        因为下采样每次都会将特征图高和宽缩小二倍,所以如果特征图高和宽是奇数的话,我们会在下采样时使用padding将特征图补成偶数。如果是偶数,加一除二取整后与直接取整除二值一样,如果是奇数,直接除二取整就会比padding后的尺寸小。

        最后需要注意的就是

else:
    x = blk(x, attn_mask)

        attn_mask是直接传进SwinTransformerBlock的forward函数

SwinTransformerBlock类

        初始化函数

  1. class SwinTransformerBlock(nn.Module):
  2. # 与Vit的block结构是相同的
  3. def __init__(self, dim, num_heads, window_size=7, shift_size=0,
  4. mlp_ratio=4., qkv_bias=True, drop=0., attn_drop=0., drop_path=0.,
  5. act_layer=nn.GELU, norm_layer=nn.LayerNorm):
  6. super().__init__()
  7. self.dim = dim
  8. self.num_heads = num_heads
  9. self.window_size = window_size
  10. self.shift_size = shift_size
  11. self.mlp_ratio = mlp_ratio
  12. assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size"
  13. self.norm1 = norm_layer(dim)
  14. self.attn = WindowAttention(
  15. dim, window_size=(self.window_size, self.window_size), num_heads=num_heads, qkv_bias=qkv_bias,
  16. attn_drop=attn_drop, proj_drop=drop)
  17. self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
  18. self.norm2 = norm_layer(dim)
  19. mlp_hidden_dim = int(dim * mlp_ratio)
  20. self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)

        它的初始化函数没什么值得说的,稍后会说WindowAttention和MLP

        forward函数

  1. def forward(self, x, attn_mask):
  2. # x(B,L,C),因此需要记录h和w
  3. H, W = self.H, self.W
  4. B, L, C = x.shape
  5. assert L == H * W, "input feature has wrong size"
  6. # 残差网络
  7. shortcut = x
  8. x = self.norm1(x)
  9. x = x.view(B, H, W, C)
  10. # pad feature maps to multiples of window size
  11. # 把feature map给pad到window size的整数倍
  12. pad_l = pad_t = 0
  13. pad_r = (self.window_size - W % self.window_size) % self.window_size
  14. pad_b = (self.window_size - H % self.window_size) % self.window_size
  15. x = F.pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b))
  16. _, Hp, Wp, _ = x.shape
  17. # cyclic shift
  18. if self.shift_size > 0:
  19. # 对窗口进行移位。从上向下移,从左往右移,因此是负的
  20. shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
  21. else:
  22. shifted_x = x
  23. attn_mask = None
  24. # partition windows
  25. x_windows = window_partition(shifted_x, self.window_size) # [nW*B, Mh, Mw, C]
  26. x_windows = x_windows.view(-1, self.window_size * self.window_size, C) # [nW*B, Mh*Mw, C]

         进入SwinTransformerBlock前,x上一个经历的是create_mask,维度是[B, HW, C],所以需要单独传入H和W。shortcut是为了实现残差,之后将x的维度变为(B, H, W, C)。并且还要保证特征图是window_size的整数倍,所以要进行一次padding,此时维度是(B, Hp, Wp, C)。再进行mask中的移位,如果shift_size是0就说明是W-MSA,不需要移位。然后划分窗口并维度变换

  1. # W-MSA/SW-MSA
  2. attn_windows = self.attn(x_windows, mask=attn_mask) # [nW*B, Mh*Mw, C]
  3. # 窗口还原
  4. attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C) # [nW*B, Mh, Mw, C]
  5. shifted_x = window_reverse(attn_windows, self.window_size, Hp, Wp) # [B, H', W', C]
  6. # shift还原,如果没有shifted就不用还原
  7. if self.shift_size > 0:
  8. x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
  9. else:
  10. x = shifted_x
  11. if pad_r > 0 or pad_b > 0:
  12. # 把前面pad的数据移除掉
  13. x = x[:, :H, :W, :].contiguous()
  14. x = x.view(B, H * W, C)
  15. # FFN
  16. x = shortcut + self.drop_path(x)
  17. x = x + self.drop_path(self.mlp(self.norm2(x)))
  18. return x

 attn_mask在这里传给WindowAttention,之后先取消窗口划分,再将刚才的shift操作还原,再移除刚刚的padding

window_partition + window_reverse类

  1. def window_partition(x, window_size: int):
  2. """
  3. 将feature map按照window_size划分成一个个没有重叠的window
  4. Args:
  5. x: (B, H, W, C)
  6. window_size (int): window size(M)
  7. Returns:
  8. windows: (num_windows*B, window_size, window_size, C)
  9. """
  10. B, H, W, C = x.shape
  11. x = x.view(B, H // window_size, window_size, W // window_size, window_size, C)
  12. # permute: [B, H//Mh, Mh, W//Mw, Mw, C] -> [B, H//Mh, W//Mh, Mw, Mw, C]
  13. # view: [B, H//Mh, W//Mw, Mh, Mw, C] -> [B*num_windows, Mh, Mw, C]
  14. windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
  15. return windows
  16. def window_reverse(windows, window_size: int, H: int, W: int):
  17. """
  18. 将一个个window还原成一个feature map
  19. Args:
  20. windows: (num_windows*B, window_size, window_size, C)
  21. window_size (int): Window size(M)
  22. H (int): Height of image
  23. W (int): Width of image
  24. Returns:
  25. x: (B, H, W, C)
  26. """
  27. B = int(windows.shape[0] / (H * W / window_size / window_size))
  28. # view: [B*num_windows, Mh, Mw, C] -> [B, H//Mh, W//Mw, Mh, Mw, C]
  29. x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1)
  30. # permute: [B, H//Mh, W//Mw, Mh, Mw, C] -> [B, H//Mh, Mh, W//Mw, Mw, C]
  31. # view: [B, H//Mh, Mh, W//Mw, Mw, C] -> [B, H, W, C]
  32. x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)
  33. return x

窗口划分和窗口还原,简单的维度变换

WindowAttention类

        初始化函数 

  1. class WindowAttention(nn.Module):
  2. def __init__(self, dim, window_size, num_heads, qkv_bias=True, attn_drop=0., proj_drop=0.):
  3. super().__init__()
  4. self.dim = dim
  5. self.window_size = window_size # [Mh, Mw]
  6. self.num_heads = num_heads
  7. head_dim = dim // num_heads
  8. self.scale = head_dim ** -0.5
  9. # 每一个head都有自己的relative_position_bias_table
  10. self.relative_position_bias_table = nn.Parameter(
  11. torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)) # [2*Mh-1 * 2*Mw-1, nH]
  12. # get pair-wise relative position index for each token inside the window
  13. coords_h = torch.arange(self.window_size[0])
  14. coords_w = torch.arange(self.window_size[1])
  15. # meshgrid生成网格,再通过stack方法拼接
  16. coords = torch.stack(torch.meshgrid([coords_h, coords_w], indexing="ij")) # [2, Mh, Mw]
  17. coords_flatten = torch.flatten(coords, 1) # [2, Mh*Mw]
  18. # [2, Mh*Mw, 1] - [2, 1, Mh*Mw]
  19. relative_coords = relative_coords = coords_flatten.unsqueeze(2) - coords_flatten.unsqueeze(1) # [2, Mh*Mw, Mh*Mw]
  20. relative_coords = relative_coords.permute(1, 2, 0).contiguous() # [Mh*Mw, Mh*Mw, 2]
  21. relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0
  22. relative_coords[:, :, 1] += self.window_size[1] - 1
  23. relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
  24. relative_position_index = relative_coords.sum(-1) # [Mh*Mw, Mh*Mw]
  25. # 整个训练当中,window_size大小不变,因此这个索引也不会改变
  26. self.register_buffer("relative_position_index", relative_position_index)
  27. self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
  28. self.attn_drop = nn.Dropout(attn_drop)
  29. self.proj = nn.Linear(dim, dim) # 多头融合
  30. self.proj_drop = nn.Dropout(proj_drop)
  31. nn.init.trunc_normal_(self.relative_position_bias_table, std=.02)
  32. self.softmax = nn.Softmax(dim=-1)

        这里head_dim就是dk,并且在MSA中每个头都要有自己的相对位置表,然后生成相对位置索引表 ,具体原理也在我上一篇中有非常详细说明。然后之后都与Vit相同。

        forward函数

  1. def forward(self, x, mask: Optional[torch.Tensor] = None):
  2. """
  3. Args:
  4. x: input features with shape of (num_windows*B, Mh*Mw, C)
  5. mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None
  6. """
  7. # [batch_size*num_windows, Mh*Mw, total_embed_dim]
  8. B_, N, C = x.shape
  9. # qkv(): -> [batch_size*num_windows, Mh*Mw, 3 * total_embed_dim]
  10. # reshape: -> [batch_size*num_windows, Mh*Mw, 3, num_heads, embed_dim_per_head]
  11. # permute: -> [3, batch_size*num_windows, num_heads, Mh*Mw, embed_dim_per_head]
  12. qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
  13. # [batch_size*num_windows, num_heads, Mh*Mw, embed_dim_per_head]
  14. # 通过unbind分别获得qkv
  15. q, k, v = qkv.unbind(0) # make torchscript happy (cannot use tensor as tuple)
  16. # transpose: -> [batch_size*num_windows, num_heads, embed_dim_per_head, Mh*Mw]
  17. # @: multiply -> [batch_size*num_windows, num_heads, Mh*Mw, Mh*Mw]
  18. q = q * self.scale
  19. attn = (q @ k.transpose(-2, -1))
  20. # relative_position_bias_table.view: [Mh*Mw*Mh*Mw,nH] -> [Mh*Mw,Mh*Mw,nH]
  21. relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(
  22. self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1)
  23. relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # [nH, Mh*Mw, Mh*Mw]
  24. # 通过unsqueeze加上一个batch维度
  25. attn = attn + relative_position_bias.unsqueeze(0)
  26. if mask is not None:
  27. # mask: [nW, Mh*Mw, Mh*Mw]
  28. nW = mask.shape[0] # num_windows
  29. # attn.view: [batch_size, num_windows, num_heads, Mh*Mw, Mh*Mw]
  30. # mask.unsqueeze: [1, nW, 1, Mh*Mw, Mh*Mw]
  31. attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0)
  32. attn = attn.view(-1, self.num_heads, N, N)
  33. attn = self.softmax(attn)
  34. else:
  35. attn = self.softmax(attn)
  36. attn = self.attn_drop(attn)
  37. # @: multiply -> [batch_size*num_windows, num_heads, Mh*Mw, embed_dim_per_head]
  38. # transpose: -> [batch_size*num_windows, Mh*Mw, num_heads, embed_dim_per_head]
  39. # reshape: -> [batch_size*num_windows, Mh*Mw, total_embed_dim]
  40. x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
  41. x = self.proj(x)
  42. x = self.proj_drop(x)
  43. return x

        在这里进行相对位置编码        attn = attn + relative_position_bias.unsqueeze(0)
 

PatchMerging类

  1. class PatchMerging(nn.Module):
  2. def __init__(self, dim, norm_layer=nn.LayerNorm):
  3. super().__init__()
  4. self.dim = dim
  5. self.norm = norm_layer(4 * dim)
  6. self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False) # 将通道数由4倍变为2
  7. def forward(self, x, H, W):
  8. """
  9. x: B, H*W(L), C,并不知道H和W,所以需要单独传参
  10. """
  11. B, L, C = x.shape
  12. assert L == H * W, "input feature has wrong size"
  13. x = x.view(B, H, W, C)
  14. # padding
  15. # 因为是下采样两倍,如果输入feature map的H,W不是2的整数倍,需要进行padding
  16. pad_input = (H % 2 == 1) or (W % 2 == 1)
  17. if pad_input:
  18. # 此时(B,H,W,C)依然是从后向前
  19. # (C_front, C_back, W_left, W_right, H_top, H_bottom)
  20. # 注意这里的Tensor通道是[B, H, W, C],所以会和官方文档有些不同
  21. x = F.pad(x, (0, 0, 0, W % 2, 0, H % 2))
  22. x0 = x[:, 0::2, 0::2, :] # [B, H/2, W/2, C]
  23. x1 = x[:, 1::2, 0::2, :] # [B, H/2, W/2, C]
  24. x2 = x[:, 0::2, 1::2, :] # [B, H/2, W/2, C]
  25. x3 = x[:, 1::2, 1::2, :] # [B, H/2, W/2, C]
  26. x = torch.cat([x0, x1, x2, x3], -1) # [B, H/2, W/2, 4*C],这里的-1就是在C的维度上拼接
  27. x = x.view(B, -1, 4 * C) # [B, H/2*W/2, 4*C]
  28. x = self.norm(x)
  29. x = self.reduction(x) # [B, H/2*W/2, 2*C]
  30. return x

 完整代码

  1. import torch
  2. import torch.nn as nn
  3. import torch.nn.functional as F
  4. import torch.utils.checkpoint as checkpoint
  5. import numpy as np
  6. from typing import Optional
  7. def drop_path_f(x, drop_prob: float = 0., training: bool = False):
  8. """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
  9. This is the same as the DropConnect impl I created for EfficientNet, etc networks, however,
  10. the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
  11. See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for
  12. changing the layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use
  13. 'survival rate' as the argument.
  14. """
  15. if drop_prob == 0. or not training:
  16. return x
  17. keep_prob = 1 - drop_prob
  18. shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
  19. random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device)
  20. random_tensor.floor() # binarize
  21. output = x.div(keep_prob) * random_tensor
  22. return output
  23. class DropPath(nn.Module):
  24. """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
  25. """
  26. def __init__(self, drop_prob=None):
  27. super(DropPath, self).__init__()
  28. self.drop_prob = drop_prob
  29. def forward(self, x):
  30. return drop_path_f(x, self.drop_prob, self.training)
  31. def window_partition(x, window_size: int):
  32. """
  33. 将feature map按照window_size划分成一个个没有重叠的window
  34. Args:
  35. x: (B, H, W, C)
  36. window_size (int): window size(M)
  37. Returns:
  38. windows: (num_windows*B, window_size, window_size, C)
  39. """
  40. B, H, W, C = x.shape
  41. x = x.view(B, H // window_size, window_size, W // window_size, window_size, C)
  42. # permute: [B, H//Mh, Mh, W//Mw, Mw, C] -> [B, H//Mh, W//Mh, Mw, Mw, C]
  43. # view: [B, H//Mh, W//Mw, Mh, Mw, C] -> [B*num_windows, Mh, Mw, C]
  44. windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
  45. return windows
  46. def window_reverse(windows, window_size: int, H: int, W: int):
  47. """
  48. 将一个个window还原成一个feature map
  49. Args:
  50. windows: (num_windows*B, window_size, window_size, C)
  51. window_size (int): Window size(M)
  52. H (int): Height of image
  53. W (int): Width of image
  54. Returns:
  55. x: (B, H, W, C)
  56. """
  57. B = int(windows.shape[0] / (H * W / window_size / window_size))
  58. # view: [B*num_windows, Mh, Mw, C] -> [B, H//Mh, W//Mw, Mh, Mw, C]
  59. x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1)
  60. # permute: [B, H//Mh, W//Mw, Mh, Mw, C] -> [B, H//Mh, Mh, W//Mw, Mw, C]
  61. # view: [B, H//Mh, Mh, W//Mw, Mw, C] -> [B, H, W, C]
  62. x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)
  63. return x
  64. class PatchEmbed(nn.Module):
  65. """
  66. 2D Image to Patch Embedding
  67. """
  68. def __init__(self, patch_size=4, in_c=3, embed_dim=96, norm_layer=None):
  69. super().__init__()
  70. patch_size = (patch_size, patch_size)
  71. self.patch_size = patch_size
  72. self.in_chans = in_c
  73. self.embed_dim = embed_dim
  74. self.proj = nn.Conv2d(in_c, embed_dim, kernel_size=patch_size, stride=patch_size)
  75. self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
  76. def forward(self, x):
  77. _, _, H, W = x.shape
  78. # padding
  79. # 如果输入图片的H,W不是patch_size的整数倍,需要进行padding
  80. pad_input = (H % self.patch_size[0] != 0) or (W % self.patch_size[1] != 0)
  81. if pad_input:
  82. # (W_left, W_right, H_top,H_bottom, C_front, C_back)
  83. # pad是从后往前,从左往右,从上往下,原顺序是(B,C,H,W) pad顺序就是(W,H,C)
  84. x = F.pad(x, (0, self.patch_size[1] - W % self.patch_size[1],
  85. 0, self.patch_size[0] - H % self.patch_size[0],
  86. 0, 0))
  87. # 下采样patch_size
  88. x = self.proj(x)
  89. _, _, H, W = x.shape
  90. # flatten: [B, C, H, W] -> [B, C, HW]
  91. # transpose: [B, C, HW] -> [B, HW, C]
  92. x = x.flatten(2).transpose(1, 2)
  93. x = self.norm(x)
  94. return x, H, W # 这里是经过padding的H和W
  95. class PatchMerging(nn.Module):
  96. r""" Patch Merging Layer.
  97. Args:
  98. dim (int): Number of input channels.
  99. norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
  100. """
  101. def __init__(self, dim, norm_layer=nn.LayerNorm):
  102. super().__init__()
  103. self.dim = dim
  104. self.norm = norm_layer(4 * dim)
  105. self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False) # 将通道数由4倍变为2
  106. def forward(self, x, H, W):
  107. """
  108. x: B, H*W(L), C,并不知道H和W,所以需要单独传参
  109. """
  110. B, L, C = x.shape
  111. assert L == H * W, "input feature has wrong size"
  112. x = x.view(B, H, W, C)
  113. # padding
  114. # 因为是下采样两倍,如果输入feature map的H,W不是2的整数倍,需要进行padding
  115. pad_input = (H % 2 == 1) or (W % 2 == 1)
  116. if pad_input:
  117. # 此时(B,H,W,C)依然是从后向前
  118. # (C_front, C_back, W_left, W_right, H_top, H_bottom)
  119. # 注意这里的Tensor通道是[B, H, W, C],所以会和官方文档有些不同
  120. x = F.pad(x, (0, 0, 0, W % 2, 0, H % 2))
  121. x0 = x[:, 0::2, 0::2, :] # [B, H/2, W/2, C]
  122. x1 = x[:, 1::2, 0::2, :] # [B, H/2, W/2, C]
  123. x2 = x[:, 0::2, 1::2, :] # [B, H/2, W/2, C]
  124. x3 = x[:, 1::2, 1::2, :] # [B, H/2, W/2, C]
  125. x = torch.cat([x0, x1, x2, x3], -1) # [B, H/2, W/2, 4*C],这里的-1就是在C的维度上拼接
  126. x = x.view(B, -1, 4 * C) # [B, H/2*W/2, 4*C]
  127. x = self.norm(x)
  128. x = self.reduction(x) # [B, H/2*W/2, 2*C]
  129. return x
  130. class Mlp(nn.Module):
  131. """ MLP as used in Vision Transformer, MLP-Mixer and related networks
  132. """
  133. def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
  134. super().__init__()
  135. out_features = out_features or in_features
  136. hidden_features = hidden_features or in_features
  137. self.fc1 = nn.Linear(in_features, hidden_features)
  138. self.act = act_layer()
  139. self.drop1 = nn.Dropout(drop)
  140. self.fc2 = nn.Linear(hidden_features, out_features)
  141. self.drop2 = nn.Dropout(drop)
  142. def forward(self, x):
  143. x = self.fc1(x)
  144. x = self.act(x)
  145. x = self.drop1(x)
  146. x = self.fc2(x)
  147. x = self.drop2(x)
  148. return x
  149. class WindowAttention(nn.Module):
  150. r""" Window based multi-head self attention (W-MSA) module with relative position bias.
  151. It supports both of shifted and non-shifted window.
  152. Args:
  153. dim (int): Number of input channels.
  154. window_size (tuple[int]): The height and width of the window.
  155. num_heads (int): Number of attention heads.
  156. qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
  157. attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
  158. proj_drop (float, optional): Dropout ratio of output. Default: 0.0
  159. """
  160. def __init__(self, dim, window_size, num_heads, qkv_bias=True, attn_drop=0., proj_drop=0.):
  161. super().__init__()
  162. self.dim = dim
  163. self.window_size = window_size # [Mh, Mw]
  164. self.num_heads = num_heads
  165. head_dim = dim // num_heads
  166. self.scale = head_dim ** -0.5
  167. # 每一个head都有自己的relative_position_bias_table
  168. self.relative_position_bias_table = nn.Parameter(
  169. torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)) # [2*Mh-1 * 2*Mw-1, nH]
  170. # get pair-wise relative position index for each token inside the window
  171. coords_h = torch.arange(self.window_size[0])
  172. coords_w = torch.arange(self.window_size[1])
  173. # meshgrid生成网格,再通过stack方法拼接
  174. coords = torch.stack(torch.meshgrid([coords_h, coords_w], indexing="ij")) # [2, Mh, Mw]
  175. coords_flatten = torch.flatten(coords, 1) # [2, Mh*Mw]
  176. # [2, Mh*Mw, 1] - [2, 1, Mh*Mw]
  177. relative_coords = relative_coords = coords_flatten.unsqueeze(2) - coords_flatten.unsqueeze(1) # [2, Mh*Mw, Mh*Mw]
  178. relative_coords = relative_coords.permute(1, 2, 0).contiguous() # [Mh*Mw, Mh*Mw, 2]
  179. relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0
  180. relative_coords[:, :, 1] += self.window_size[1] - 1
  181. relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
  182. relative_position_index = relative_coords.sum(-1) # [Mh*Mw, Mh*Mw]
  183. # 整个训练当中,window_size大小不变,因此这个索引也不会改变
  184. self.register_buffer("relative_position_index", relative_position_index)
  185. self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
  186. self.attn_drop = nn.Dropout(attn_drop)
  187. self.proj = nn.Linear(dim, dim) # 多头融合
  188. self.proj_drop = nn.Dropout(proj_drop)
  189. nn.init.trunc_normal_(self.relative_position_bias_table, std=.02)
  190. self.softmax = nn.Softmax(dim=-1)
  191. def forward(self, x, mask: Optional[torch.Tensor] = None):
  192. """
  193. Args:
  194. x: input features with shape of (num_windows*B, Mh*Mw, C)
  195. mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None
  196. """
  197. # [batch_size*num_windows, Mh*Mw, total_embed_dim]
  198. B_, N, C = x.shape
  199. # qkv(): -> [batch_size*num_windows, Mh*Mw, 3 * total_embed_dim]
  200. # reshape: -> [batch_size*num_windows, Mh*Mw, 3, num_heads, embed_dim_per_head]
  201. # permute: -> [3, batch_size*num_windows, num_heads, Mh*Mw, embed_dim_per_head]
  202. qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
  203. # [batch_size*num_windows, num_heads, Mh*Mw, embed_dim_per_head]
  204. # 通过unbind分别获得qkv
  205. q, k, v = qkv.unbind(0) # make torchscript happy (cannot use tensor as tuple)
  206. # transpose: -> [batch_size*num_windows, num_heads, embed_dim_per_head, Mh*Mw]
  207. # @: multiply -> [batch_size*num_windows, num_heads, Mh*Mw, Mh*Mw]
  208. q = q * self.scale
  209. attn = (q @ k.transpose(-2, -1))
  210. # relative_position_bias_table.view: [Mh*Mw*Mh*Mw,nH] -> [Mh*Mw,Mh*Mw,nH]
  211. relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(
  212. self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1)
  213. relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # [nH, Mh*Mw, Mh*Mw]
  214. # 通过unsqueeze加上一个batch维度
  215. attn = attn + relative_position_bias.unsqueeze(0)
  216. if mask is not None:
  217. # mask: [nW, Mh*Mw, Mh*Mw]
  218. nW = mask.shape[0] # num_windows
  219. # attn.view: [batch_size, num_windows, num_heads, Mh*Mw, Mh*Mw]
  220. # mask.unsqueeze: [1, nW, 1, Mh*Mw, Mh*Mw]
  221. attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0)
  222. attn = attn.view(-1, self.num_heads, N, N)
  223. attn = self.softmax(attn)
  224. else:
  225. attn = self.softmax(attn)
  226. attn = self.attn_drop(attn)
  227. # @: multiply -> [batch_size*num_windows, num_heads, Mh*Mw, embed_dim_per_head]
  228. # transpose: -> [batch_size*num_windows, Mh*Mw, num_heads, embed_dim_per_head]
  229. # reshape: -> [batch_size*num_windows, Mh*Mw, total_embed_dim]
  230. x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
  231. x = self.proj(x)
  232. x = self.proj_drop(x)
  233. return x
  234. class SwinTransformerBlock(nn.Module):
  235. r""" Swin Transformer Block.
  236. Args:
  237. dim (int): Number of input channels.
  238. num_heads (int): Number of attention heads.
  239. window_size (int): Window size.
  240. shift_size (int): Shift size for SW-MSA.
  241. mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
  242. qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
  243. drop (float, optional): Dropout rate. Default: 0.0
  244. attn_drop (float, optional): Attention dropout rate. Default: 0.0
  245. drop_path (float, optional): Stochastic depth rate. Default: 0.0
  246. act_layer (nn.Module, optional): Activation layer. Default: nn.GELU
  247. norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
  248. """
  249. # 与Vit的block结构是相同的
  250. def __init__(self, dim, num_heads, window_size=7, shift_size=0,
  251. mlp_ratio=4., qkv_bias=True, drop=0., attn_drop=0., drop_path=0.,
  252. act_layer=nn.GELU, norm_layer=nn.LayerNorm):
  253. super().__init__()
  254. self.dim = dim
  255. self.num_heads = num_heads
  256. self.window_size = window_size
  257. self.shift_size = shift_size
  258. self.mlp_ratio = mlp_ratio
  259. assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size"
  260. self.norm1 = norm_layer(dim)
  261. self.attn = WindowAttention(
  262. dim, window_size=(self.window_size, self.window_size), num_heads=num_heads, qkv_bias=qkv_bias,
  263. attn_drop=attn_drop, proj_drop=drop)
  264. self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
  265. self.norm2 = norm_layer(dim)
  266. mlp_hidden_dim = int(dim * mlp_ratio)
  267. self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
  268. def forward(self, x, attn_mask):
  269. # x(B,L,C),因此需要记录h和w
  270. H, W = self.H, self.W
  271. B, L, C = x.shape
  272. assert L == H * W, "input feature has wrong size"
  273. # 残差网络
  274. shortcut = x
  275. x = self.norm1(x)
  276. x = x.view(B, H, W, C)
  277. # pad feature maps to multiples of window size
  278. # 把feature map给pad到window size的整数倍
  279. pad_l = pad_t = 0
  280. pad_r = (self.window_size - W % self.window_size) % self.window_size
  281. pad_b = (self.window_size - H % self.window_size) % self.window_size
  282. x = F.pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b))
  283. _, Hp, Wp, _ = x.shape
  284. # cyclic shift
  285. if self.shift_size > 0:
  286. # 对窗口进行移位。从上向下移,从左往右移,因此是负的
  287. shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
  288. else:
  289. shifted_x = x
  290. attn_mask = None
  291. # partition windows
  292. x_windows = window_partition(shifted_x, self.window_size) # [nW*B, Mh, Mw, C]
  293. x_windows = x_windows.view(-1, self.window_size * self.window_size, C) # [nW*B, Mh*Mw, C]
  294. # W-MSA/SW-MSA
  295. attn_windows = self.attn(x_windows, mask=attn_mask) # [nW*B, Mh*Mw, C]
  296. # 窗口还原
  297. attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C) # [nW*B, Mh, Mw, C]
  298. shifted_x = window_reverse(attn_windows, self.window_size, Hp, Wp) # [B, H', W', C]
  299. # shift还原,如果没有shifted就不用还原
  300. if self.shift_size > 0:
  301. x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
  302. else:
  303. x = shifted_x
  304. if pad_r > 0 or pad_b > 0:
  305. # 把前面pad的数据移除掉
  306. x = x[:, :H, :W, :].contiguous()
  307. x = x.view(B, H * W, C)
  308. # FFN
  309. x = shortcut + self.drop_path(x)
  310. x = x + self.drop_path(self.mlp(self.norm2(x)))
  311. return x
  312. class BasicLayer(nn.Module):
  313. """
  314. A basic Swin Transformer layer for one stage.
  315. Args:
  316. dim (int): Number of input channels.
  317. depth (int): Number of blocks.
  318. num_heads (int): Number of attention heads.
  319. window_size (int): Local window size.
  320. mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
  321. qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
  322. drop (float, optional): Dropout rate. Default: 0.0
  323. attn_drop (float, optional): Attention dropout rate. Default: 0.0
  324. drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
  325. norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
  326. downsample (nn.Module | None, optional): 是否需要下采样,在最后一个stage不需要. Default: None
  327. use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
  328. """
  329. def __init__(self, dim, depth, num_heads, window_size,
  330. mlp_ratio=4., qkv_bias=True, drop=0., attn_drop=0.,
  331. drop_path=0., norm_layer=nn.LayerNorm, downsample=None, use_checkpoint=False):
  332. super().__init__()
  333. self.dim = dim
  334. self.depth = depth
  335. self.window_size = window_size
  336. self.use_checkpoint = use_checkpoint
  337. self.shift_size = window_size // 2 # 移动尺寸
  338. # 在当前stage之中所有的block
  339. # 注意每个block中只会有一个MSA,要么W-MSA,要么SW-MSA,所以shift_size0代表W-MSA,不为0代表SW-MSA
  340. self.blocks = nn.ModuleList([
  341. SwinTransformerBlock(
  342. dim=dim,
  343. num_heads=num_heads,
  344. window_size=window_size,
  345. shift_size=0 if (i % 2 == 0) else self.shift_size,
  346. mlp_ratio=mlp_ratio,
  347. qkv_bias=qkv_bias,
  348. drop=drop,
  349. attn_drop=attn_drop,
  350. drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,
  351. norm_layer=norm_layer)
  352. for i in range(depth)])
  353. # patch merging layer
  354. if downsample is not None:
  355. self.downsample = downsample(dim=dim, norm_layer=norm_layer)
  356. else:
  357. self.downsample = None
  358. def create_mask(self, x, H, W):
  359. # calculate attention mask for SW-MSA
  360. # 保证Hp和Wp是window_size的整数倍
  361. Hp = int(np.ceil(H / self.window_size)) * self.window_size
  362. Wp = int(np.ceil(W / self.window_size)) * self.window_size
  363. # 拥有和feature map一样的通道排列顺序,方便后续window_partition
  364. img_mask = torch.zeros((1, Hp, Wp, 1), device=x.device) # [1, Hp, Wp, 1]
  365. # 将窗口切分,然后进行标号
  366. h_slices = (slice(0, -self.window_size),
  367. slice(-self.window_size, -self.shift_size),
  368. slice(-self.shift_size, None))
  369. w_slices = (slice(0, -self.window_size),
  370. slice(-self.window_size, -self.shift_size),
  371. slice(-self.shift_size, None))
  372. cnt = 0
  373. for h in h_slices:
  374. for w in w_slices:
  375. img_mask[:, h, w, :] = cnt
  376. cnt += 1
  377. mask_windows = window_partition(img_mask, self.window_size) # [nW, Mh, Mw, 1] 划为窗口
  378. mask_windows = mask_windows.view(-1, self.window_size * self.window_size) # [nW, Mh*Mw] 窗口展平
  379. attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2) # [nW, 1, Mh*Mw] - [nW, Mh*Mw, 1]
  380. # [nW, Mh*Mw, Mh*Mw]
  381. attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0))
  382. return attn_mask
  383. def forward(self, x, H, W):
  384. # 先创建一个mask蒙版,在图像尺寸不变的情况下蒙版也不改变
  385. attn_mask = self.create_mask(x, H, W) # [nW, Mh*Mw, Mh*Mw]
  386. for blk in self.blocks:
  387. blk.H, blk.W = H, W
  388. # 默认不适用checkpoint方法
  389. if not torch.jit.is_scripting() and self.use_checkpoint:
  390. x = checkpoint.checkpoint(blk, x, attn_mask)
  391. else:
  392. x = blk(x, attn_mask)
  393. if self.downsample is not None:
  394. x = self.downsample(x, H, W)
  395. # 防止H和W是奇数。如果是奇数,在下采样中经过一次padding就变成偶数了,但如果这里不给H和W加一的话就会导致少一个,如果是偶数,加一除二取整还是不变
  396. H, W = (H + 1) // 2, (W + 1) // 2
  397. return x, H, W
  398. class SwinTransformer(nn.Module):
  399. r""" Swin Transformer
  400. A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows` -
  401. https://arxiv.org/pdf/2103.14030
  402. Args:
  403. patch_size (int | tuple(int)): Patch size. Default: 4
  404. in_chans (int): Number of input image channels. Default: 3
  405. num_classes (int): Swin Transformer可以作为一个通用骨架,在这里将其用在分类任务中,最后分为num_classes个类. Default: 1000
  406. embed_dim (int): Patch embedding dimension,就是原文中的C. Default: 96
  407. depths (tuple(int)): 每个stage中的Swin Transformer Block数.
  408. num_heads (tuple(int)): 每个stage中用的multi-head数.
  409. window_size (int): Window size. Default: 7
  410. mlp_ratio (float): mlp的隐藏层是输入层的多少倍. Default: 4
  411. qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True
  412. drop_rate (float): 在pos_drop,mlp及其他地方. Default: 0
  413. attn_drop_rate (float): Attention dropout rate. Default: 0
  414. drop_path_rate (float): 每一个Swin Transformer之中,注意它的dropout率是递增的. Default: 0.1
  415. norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm.
  416. patch_norm (bool): If True, add normalization after patch embedding. Default: True
  417. use_checkpoint (bool): 如果使用可以节省内存. Default: False
  418. """
  419. def __init__(self, patch_size=4, in_chans=3, num_classes=1000,
  420. embed_dim=96, depths=(2, 2, 6, 2), num_heads=(3, 6, 12, 24),
  421. window_size=7, mlp_ratio=4., qkv_bias=True,
  422. drop_rate=0., attn_drop_rate=0., drop_path_rate=0.1,
  423. norm_layer=nn.LayerNorm, patch_norm=True,
  424. use_checkpoint=False, **kwargs):
  425. super().__init__()
  426. self.num_classes = num_classes
  427. self.num_layers = len(depths)
  428. self.embed_dim = embed_dim
  429. self.patch_norm = patch_norm
  430. # stage4输出特征矩阵的channels
  431. self.num_features = int(embed_dim * 2 ** (self.num_layers - 1))
  432. self.mlp_ratio = mlp_ratio
  433. # 对应Patch partition和Linear Embedding
  434. self.patch_embed = PatchEmbed(
  435. patch_size=patch_size, in_c=in_chans, embed_dim=embed_dim,
  436. norm_layer=norm_layer if self.patch_norm else None)
  437. self.pos_drop = nn.Dropout(p=drop_rate)
  438. # 在每个block的dropout率,是一个递增序列
  439. dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))]
  440. # build layers
  441. self.layers = nn.ModuleList()
  442. for i_layer in range(self.num_layers):
  443. # num_layers及stage数
  444. # 与论文不同,代码中的stage包含的是下一层的Patch merging ,因此在最后一个stage中没有Patch merging
  445. # dim为当前stage的维度,depth是当前stage堆叠多少个block,drop_patch是本层所有block的drop_patch
  446. # downsample是Patch merging,并且在最后一个stage为None
  447. layers = BasicLayer(dim=int(embed_dim * 2 ** i_layer),
  448. depth=depths[i_layer],
  449. num_heads=num_heads[i_layer],
  450. window_size=window_size,
  451. mlp_ratio=self.mlp_ratio,
  452. qkv_bias=qkv_bias,
  453. drop=drop_rate,
  454. attn_drop=attn_drop_rate,
  455. drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])],
  456. norm_layer=norm_layer,
  457. downsample=PatchMerging if (i_layer < self.num_layers - 1) else None,
  458. use_checkpoint=use_checkpoint)
  459. self.layers.append(layers)
  460. self.norm = norm_layer(self.num_features)
  461. self.avgpool = nn.AdaptiveAvgPool1d(1) # 在这个分类任务中,用全局平均池化取代cls token
  462. self.head = nn.Linear(self.num_features, num_classes) if num_classes > 0 else nn.Identity()
  463. self.apply(self._init_weights)
  464. def _init_weights(self, m):
  465. if isinstance(m, nn.Linear):
  466. nn.init.trunc_normal_(m.weight, std=.02)
  467. if isinstance(m, nn.Linear) and m.bias is not None:
  468. nn.init.constant_(m.bias, 0)
  469. elif isinstance(m, nn.LayerNorm):
  470. nn.init.constant_(m.bias, 0)
  471. nn.init.constant_(m.weight, 1.0)
  472. def forward(self, x):
  473. # x: [B, L, C]
  474. x, H, W = self.patch_embed(x)
  475. x = self.pos_drop(x)
  476. # 依次通过每个stage
  477. for layer in self.layers:
  478. x, H, W = layer(x, H, W)
  479. x = self.norm(x) # [B, L, C]
  480. x = self.avgpool(x.transpose(1, 2)) # [B, C, 1]
  481. x = torch.flatten(x, 1)
  482. x = self.head(x)
  483. return x
  484. def swin_tiny_patch4_window7_224(num_classes: int = 1000, **kwargs):
  485. # trained ImageNet-1K
  486. # https://github.com/SwinTransformer/storage/releases/download/v1.0.0/swin_tiny_patch4_window7_224.pth
  487. model = SwinTransformer(in_chans=3,
  488. patch_size=4,
  489. window_size=7,
  490. embed_dim=96,
  491. depths=(2, 2, 6, 2),
  492. num_heads=(3, 6, 12, 24),
  493. num_classes=num_classes,
  494. **kwargs)
  495. return model
  496. swin_tiny_patch4_window7_224()

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

闽ICP备14008679号