【代码复现】(Swin-Transformer)CS-UNet模型解读

文章目录

  • 1. 模型输入
  • 2. 进入模型:class CS_Unet
    • 2.1. class ConvSwinTransformerSys()
    • 2.2. class ConvSwinTransformerSys()
      • 2.2.1. 类PatchEmbed()
    • 2.2.(1)
      • 2.2.2. class BasicLayer()
        • 2.2.2.1. class ConvSwinTransformerBlock()
          • 2.2.2.1.1. class WindowAttention()
        • 2.2.2.1.(1)
          • 2.2.2.1.2. class Mlp()
        • 2.2.2.1.(2)
      • 2.2.2.(1)
          • 2.2.2.1.1.(1)
        • 2.2.2.1.(3)
      • 2.2.2.(2)
        • 2.2.2.2. class PatchMerging()
      • 2.2.2.(3)
    • 2.2.(2)
    • 2.3. class ConvSwinTransformerSys()
      • 2.3.1. class PatchExpand()
    • 2.3.(1)
      • 2.3.2. class BasicLayer_up()
        • 2.3.2.1. class PatchExpand()
      • 2.3.2.(1)
    • 2.3.(2)
    • 2.4. class ConvSwinTransformerSys()
      • 2.4.1. def up_x4()
        • 2.4.1.1. class FinalPatchExpand_X4()
      • 2.4.1.(1)
  • 2.(1) class CS_Unet()
  • 附录. 模型框架图


摘要:对CS-UNet模型进行单步调试,含swin-transformer结构,梳理其实现流程。

1. 模型输入

image_batch是每批次的图片,shape为 ( B , 3 , H , W ) (B,3,H,W) (B,3,H,W),B为 batch_size,3表示图片是三通道的(如rgb图片), H H H W W W分别为图片的

outputs = model(image_batch)   

然后,进入CS_Unet模型(类class CS_Unet

2. 进入模型:class CS_Unet

首先从forward开始:

class CS_Unet(nn.Module):
    def __init__(self, config, img_size=224, num_classes=21843, zero_head=False, vis=False):
        super(CS_Unet, self).__init__()
        self.num_classes = num_classes
        self.zero_head = zero_head
        self.config = config

        self.CS_Unet = ConvSwinTransformerSys(img_size=config.DATA.IMG_SIZE,
                                patch_size=config.MODEL.SWIN.PATCH_SIZE,
                                in_chans=config.MODEL.SWIN.IN_CHANS,
                                num_classes=self.num_classes,
                                embed_dim=config.MODEL.SWIN.EMBED_DIM,
                                depths=config.MODEL.SWIN.DEPTHS,
                                num_heads=config.MODEL.SWIN.NUM_HEADS,
                                window_size=config.MODEL.SWIN.WINDOW_SIZE,
                                mlp_ratio=config.MODEL.SWIN.MLP_RATIO,
                                qkv_bias=config.MODEL.SWIN.QKV_BIAS,
                                qk_scale=config.MODEL.SWIN.QK_SCALE,
                                drop_rate=config.MODEL.DROP_RATE,
                                drop_path_rate=config.MODEL.DROP_PATH_RATE,
                                ape=config.MODEL.SWIN.APE,
                                patch_norm=config.MODEL.SWIN.PATCH_NORM,
                                use_checkpoint=config.TRAIN.USE_CHECKPOINT)

    def forward(self, x):
        # 判断图片的channel是否为1, 如果为1就在通道方向上复制3次,使其变成三通道的图片。
        if x.size()[1] == 1: 
            x = x.repeat(1,3,1,1)   # (B,3,H,W)

        # 进入 类ConvSwinTransformerSys,转到2.1小节
        logits = self.CS_Unet(x)
        return logits


    # 下面是载入预训练权重要用到的,训练阶段可以不考虑
    def load_from(self, config):
        pretrained_path = config.MODEL.PRETRAIN_CKPT
        if pretrained_path is not None:
            print("pretrained_path:{}".format(pretrained_path))
            device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
            pretrained_dict = torch.load(pretrained_path, map_location=device)
            if "model" not in pretrained_dict:
                print("---start load pretrained modle by splitting---")
                pretrained_dict = {k[17:]:v for k,v in pretrained_dict.items()}
                print(k)
                for k in list(pretrained_dict.keys()):
                    if "output" in k:
                        print("delete key:{}".format(k))
                        del pretrained_dict[k]
                msg = self.CS_Unet.load_state_dict(pretrained_dict,strict=False)
                print(msg)
                return
            pretrained_dict = pretrained_dict['model']
            print("---start load pretrained modle of swin encoder---")

            model_dict = self.CS_Unet.state_dict()
            # print(self.swin_unet)
            full_dict = copy.deepcopy(pretrained_dict)
            for k, v in pretrained_dict.items():
                if "layers." in k:
                    current_layer_num = 3-int(k[7:8])
                    current_k = "layers_up." + str(current_layer_num) + k[8:]
                    full_dict.update({current_k:v})
            for k in list(full_dict.keys()):
                if k in model_dict:
                    if full_dict[k].shape != model_dict[k].shape:
                        print("delete:{};shape pretrain:{};shape model:{}".format(k,v.shape,model_dict[k].shape))
                        del full_dict[k]

            msg = self.CS_Unet.load_state_dict(full_dict, strict=False)
            # print(msg)
        else:
            print("none pretrain")
 

2.1. class ConvSwinTransformerSys()

类ConvSwinTransformerSys()
forwardx, x_downsample = self.forward_features(x)开始看

class ConvSwinTransformerSys(nn.Module):
    """
    Args:
        img_size (int | tuple(int)): Input image size. Default 224
        patch_size (int | tuple(int)): Patch size. Default: 4
        in_chans (int): Number of input image channels. Default: 3
        num_classes (int): Number of classes for classification head. Default: 1000
        embed_dim (int): Patch embedding dimension. Default: 96
        depths (tuple(int)): Depth of each Swin Transformer layer.
        num_heads (tuple(int)): Number of attention heads in different layers.
        window_size (int): Window size. Default: 7
        mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4
        qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True
        qk_scale (float): Override default qk scale of head_dim ** -0.5 if set. Default: None
        drop_rate (float): Dropout rate. Default: 0
        attn_drop_rate (float): Attention dropout rate. Default: 0
        drop_path_rate (float): Stochastic depth rate. Default: 0.1
        norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm.
        ape (bool): If True, add absolute position embedding to the patch embedding. Default: False
        patch_norm (bool): If True, add normalization after patch embedding. Default: True
        use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False
    """

    def __init__(self, img_size=224, patch_size=4, in_chans=3, num_classes=1000,
                 embed_dim=96, depths=[2, 2, 2, 2], depths_decoder=[1, 2, 2, 2], num_heads=[3, 3, 3, 3],
                 window_size=7, mlp_ratio=4., qkv_bias=True, qk_scale=None,
                 drop_rate=0., attn_drop_rate=0., drop_path_rate=0.1,
                 norm_layer=nn.LayerNorm, ape=False, patch_norm=True,
                 use_checkpoint=False, final_upsample="expand_first", **kwargs):
        super().__init__()

        print(
            "ConvSwinTransformerSys expand initial----depths:{};depths_decoder:{};num_heads=:{};drop_path_rate:{};num_classes:{}".format(
                depths,
                depths_decoder, num_heads, drop_path_rate, num_classes))

        self.num_classes = num_classes
        self.num_layers = len(depths)
        self.embed_dim = embed_dim
        self.ape = ape
        self.patch_norm = patch_norm
        self.num_features = int(embed_dim * 2 ** (self.num_layers - 1))
        self.num_features_up = int(embed_dim * 2)
        self.mlp_ratio = mlp_ratio
        self.final_upsample = final_upsample

        # split image into overlapping patches
        self.patch_embed = PatchEmbed(
            img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim,
            norm_layer=norm_layer if self.patch_norm else None)
        num_patches = self.patch_embed.num_patches
        patches_resolution = self.patch_embed.patches_resolution
        self.patches_resolution = patches_resolution

        # absolute position embedding
        if self.ape:
            self.absolute_pos_embed = nn.Parameter(torch.zeros(1, num_patches, embed_dim))
            trunc_normal_(self.absolute_pos_embed, std=.02)

        self.pos_drop = nn.Dropout(p=drop_rate)

        # stochastic depth
        dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))]  # stochastic depth decay rule

        # build encoder and bottleneck layers
        self.layers = nn.ModuleList()
        for i_layer in range(self.num_layers):
            layer = BasicLayer(dim=int(embed_dim * 2 ** i_layer),
                               input_resolution=(patches_resolution[0] // (2 ** i_layer),
                                                 patches_resolution[1] // (2 ** i_layer)),
                               depth=depths[i_layer],
                               num_heads=num_heads[i_layer],
                               window_size=window_size,
                               mlp_ratio=self.mlp_ratio,
                               qkv_bias=qkv_bias, qk_scale=qk_scale,
                               drop=drop_rate, attn_drop=attn_drop_rate,
                               drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])],
                               norm_layer=norm_layer,
                               downsample=PatchMerging if (i_layer < self.num_layers - 1) else None,
                               use_checkpoint=use_checkpoint)
            self.layers.append(layer)

        # build decoder layers
        self.layers_up = nn.ModuleList()
        self.concat_back_dim = nn.ModuleList()
        for i_layer in range(self.num_layers):
            concat_cov = self.up = nn.Sequential(Rearrange('b (h w) c -> b c h w', h=patches_resolution[0] // (2 ** (self.num_layers - 1 - i_layer)), w=patches_resolution[1] // (2 ** (self.num_layers - 1 - i_layer))),
                                                 nn.Conv2d(2 * int(embed_dim * 2 ** (self.num_layers - 1 - i_layer)),
                                                           int(embed_dim * 2 ** (self.num_layers - 1 - i_layer)),
                                                           kernel_size=3, stride=1, padding=1), nn.GELU(),
                                                 nn.Conv2d(int(embed_dim * 2 ** (self.num_layers - 1 - i_layer)),
                                                           int(embed_dim * 2 ** (self.num_layers - 1 - i_layer)),
                                                           kernel_size=3, stride=1, padding=1), nn.GELU(),
                                                 nn.Dropout(p=0.2),
                                                 Rearrange('b c h w -> b (h w) c', h=patches_resolution[0] // (
                                                             2 ** (self.num_layers - 1 - i_layer)),
                                                           w=patches_resolution[1] // (
                                                                       2 ** (self.num_layers - 1 - i_layer))))
            if i_layer == 0:
                layer_up = PatchExpand(
                    input_resolution=(patches_resolution[0] // (2 ** (self.num_layers - 1 - i_layer)),
                                      patches_resolution[1] // (2 ** (self.num_layers - 1 - i_layer))),
                    dim=int(embed_dim * 2 ** (self.num_layers - 1 - i_layer)), dim_scale=2, norm_layer=norm_layer)
            else:
                layer_up = BasicLayer_up(dim=int(embed_dim * 2 ** (self.num_layers - 1 - i_layer)),
                                         input_resolution=(
                                         patches_resolution[0] // (2 ** (self.num_layers - 1 - i_layer)),
                                         patches_resolution[1] // (2 ** (self.num_layers - 1 - i_layer))),
                                         depth=depths[(self.num_layers - 1 - i_layer)],
                                         num_heads=num_heads[(self.num_layers - 1 - i_layer)],
                                         window_size=window_size,
                                         mlp_ratio=self.mlp_ratio,
                                         qkv_bias=qkv_bias, qk_scale=qk_scale,
                                         drop=drop_rate, attn_drop=attn_drop_rate,
                                         drop_path=dpr[sum(depths[:(self.num_layers - 1 - i_layer)]):sum(
                                             depths[:(self.num_layers - 1 - i_layer) + 1])],
                                         norm_layer=norm_layer,
                                         upsample=PatchExpand if (i_layer < self.num_layers - 1) else None,
                                         use_checkpoint=use_checkpoint)
            self.layers_up.append(layer_up)
            self.concat_back_dim.append(concat_cov)

        self.norm = norm_layer(self.num_features)
        self.norm_up = norm_layer(self.embed_dim)

        if self.final_upsample == "expand_first":
            print("---final upsample expand_first---")
            self.up = FinalPatchExpand_X4(input_resolution=(img_size // patch_size, img_size // patch_size),
                                          dim_scale=4, dim=embed_dim)
            self.output = nn.Conv2d(in_channels=embed_dim, out_channels=self.num_classes, kernel_size=1, bias=False)

        self.apply(self._init_weights)

    def _init_weights(self, m):
        if isinstance(m, (nn.Conv2d, nn.Linear)):
            trunc_normal_(m.weight, std=.02)
            if isinstance(m, nn.Linear) and m.bias is not None:
                nn.init.constant_(m.bias, 0)
        elif isinstance(m, nn.LayerNorm):
            nn.init.constant_(m.bias, 0)
            nn.init.constant_(m.weight, 1.0)

    @torch.jit.ignore
    def no_weight_decay(self):
        return {'absolute_pos_embed'}

    @torch.jit.ignore
    def no_weight_decay_keywords(self):
        return {'relative_position_bias_table'}

    # Encoder and Bottleneck
    def forward_features(self, x):
        x = self.patch_embed(x)      # (B,3,H,W)
        if self.ape:
            x = x + self.absolute_pos_embed
        x = self.pos_drop(x)
        x_downsample = []

        for layer in self.layers:
            x_downsample.append(x)
            x = layer(x)

        x = self.norm(x)  # B L C

        return x, x_downsample

    # Dencoder and Skip connection
    def forward_up_features(self, x, x_downsample):
        for inx, layer_up in enumerate(self.layers_up):
            if inx == 0:
                x = layer_up(x)
            else:
                x = torch.cat([x, x_downsample[3 - inx]], -1)
                x = self.concat_back_dim[inx](x)
                x = layer_up(x)

        x = self.norm_up(x)  # B L C
        return x

    def up_x4(self, x):
        H, W = self.patches_resolution
        B, L, C = x.shape
        assert L == H * W, "input features has wrong size"

        if self.final_upsample == "expand_first":
            x = self.up(x)
            x = x.view(B, 4 * H, 4 * W, -1)
            x = x.permute(0, 3, 1, 2)  # B,C,H,W
            x = self.output(x)

        return x

    def forward(self, x):
        # 跳到self.forward_features部分, 转到2.2小节
        x, x_downsample = self.forward_features(x)   # (B,3,H,W)
        x = self.forward_up_features(x, x_downsample)
        x = self.up_x4(x)

        return x


2.2. class ConvSwinTransformerSys()

类ConvSwinTransformerSys()与2.1小节相同,在这里只展示要用到的代码段
forward_featuresx = self.patch_embed(x)开始看

class ConvSwinTransformerSys(nn.Module):
  
    def __init__(self, img_size=224, patch_size=4, in_chans=3, num_classes=1000,
                 embed_dim=96, depths=[2, 2, 2, 2], depths_decoder=[1, 2, 2, 2], num_heads=[3, 3, 3, 3],
                 window_size=7, mlp_ratio=4., qkv_bias=True, qk_scale=None,
                 drop_rate=0., attn_drop_rate=0., drop_path_rate=0.1,
                 norm_layer=nn.LayerNorm, ape=False, patch_norm=True,
                 use_checkpoint=False, final_upsample="expand_first", **kwargs):
        super().__init__()

        print(
            "ConvSwinTransformerSys expand initial----depths:{};depths_decoder:{};num_heads=:{};drop_path_rate:{};num_classes:{}".format(
                depths,
                depths_decoder, num_heads, drop_path_rate, num_classes))

        self.num_classes = num_classes
        self.num_layers = len(depths)
        self.embed_dim = embed_dim
        self.ape = ape
        self.patch_norm = patch_norm
        self.num_features = int(embed_dim * 2 ** (self.num_layers - 1))
        self.num_features_up = int(embed_dim * 2)
        self.mlp_ratio = mlp_ratio
        self.final_upsample = final_upsample

        # split image into overlapping patches
        self.patch_embed = PatchEmbed(
            img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim,
            norm_layer=norm_layer if self.patch_norm else None)

    # Encoder and Bottleneck
    def forward_features(self, x):
        # 这里 x 还是在原始batch图片上进行三通道扩展后的数据
        # 转到2.2.1小节 PatchEmbed
        x = self.patch_embed(x)      # (B,3,H,W)
        if self.ape:
            x = x + self.absolute_pos_embed
        x = self.pos_drop(x)
        x_downsample = []

        for layer in self.layers:
            x_downsample.append(x)
            x = layer(x)

        x = self.norm(x)  # B L C

        return x, x_downsample

2.2.1. 类PatchEmbed()

类PatchEmbed()
forwardB, C, H, W = x.shape开始看

class PatchEmbed(nn.Module):
    r""" Image to Patch Embedding

    Args:
        img_size (int): Image size.  Default: 224.
        patch_size (int): Patch token size. Default: 4.
        in_chans (int): Number of input image channels. Default: 3.
        embed_dim (int): Number of linear projection output channels. Default: 96.
        norm_layer (nn.Module, optional): Normalization layer. Default: None
    """

    def __init__(self, img_size=224, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None):
        super().__init__()
        img_size = to_2tuple(img_size)
        patch_size = to_2tuple(patch_size)
        patches_resolution = [img_size[0] // patch_size[0], img_size[1] // patch_size[1]]
        self.img_size = img_size
        self.patch_size = patch_size
        self.patches_resolution = patches_resolution
        self.num_patches = patches_resolution[0] * patches_resolution[1]

        self.in_chans = in_chans
        self.embed_dim = embed_dim

        self.proj = nn.Sequential(nn.Conv2d(in_chans, embed_dim // 2, kernel_size=3, stride=1, padding=1), nn.GELU(),
                                  nn.Conv2d(embed_dim // 2, embed_dim // 2, kernel_size=3, stride=2, padding=1),
                                  nn.GELU(),
                                  Rearrange('b c h w -> b h w c'),
                                  norm_layer(embed_dim // 2),
                                  Rearrange('b h w c -> b c h w'),
                                  nn.Conv2d(embed_dim // 2, embed_dim, kernel_size=3, stride=1, padding=1), nn.GELU(),
                                  nn.Conv2d(embed_dim, embed_dim, kernel_size=3, stride=2, padding=1), nn.GELU())
        if norm_layer is not None:
            self.norm = norm_layer(in_chans)
            self.norm2 = norm_layer(embed_dim)
        else:
            self.norm = None
        self.drop = nn.Dropout(p=0.2)

    def forward(self, x):
        B, C, H, W = x.shape          # (B,3,H,W)
        # 判断图片的H和W是否和我们设置的img_size相同,如果不相同就中断程序运行
        assert H == self.img_size[0] and W == self.img_size[1], \
            f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."

        '''
         proj中含有四层卷积,每层卷积实现的效果如下:
         (1):(B,3,H,W)->(B,48,H,W)
         (2):(B,48,H,W)->(B,48,H/2,W/2)
         (3):(B,48,H/2,W/2)->(B,96,H/2,W/2)
         (4):(B,96,H/2,W/2)->(B,96,H/4,W/4)
         '''
        x = self.proj(x)                             # (B, 3, H, W)->(B, 96, H/4, W/4)
        x = self.drop(x).flatten(2).transpose(1, 2)  # (B, 96, H/4, W/4)->(B, H/4 * W/4, 96)
        if self.norm is not None:                    # True
            x = self.norm2(x)                        # (B, H/4 * W/4, 96)
        return x   # (B, H/4 * W/4, 96)
        # PatchEmbed执行结束,下面转到2.2小节

2.2.(1)

类ConvSwinTransformerSys()与2.1小节相同,在这里只展示要用到的代码段
forward_featuresif self.ape:开始看

class ConvSwinTransformerSys(nn.Module):
  
    def __init__(self, img_size=224, patch_size=4, in_chans=3, num_classes=1000,
                 embed_dim=96, depths=[2, 2, 2, 2], depths_decoder=[1, 2, 2, 2], num_heads=[3, 3, 3, 3],
                 window_size=7, mlp_ratio=4., qkv_bias=True, qk_scale=None,
                 drop_rate=0., attn_drop_rate=0., drop_path_rate=0.1,
                 norm_layer=nn.LayerNorm, ape=False, patch_norm=True,
                 use_checkpoint=False, final_upsample="expand_first", **kwargs):
        super().__init__()

        print(
            "ConvSwinTransformerSys expand initial----depths:{};depths_decoder:{};num_heads=:{};drop_path_rate:{};num_classes:{}".format(
                depths,
                depths_decoder, num_heads, drop_path_rate, num_classes))

        self.num_classes = num_classes
        self.num_layers = len(depths)
        self.embed_dim = embed_dim
        self.ape = ape
        self.patch_norm = patch_norm
        self.num_features = int(embed_dim * 2 ** (self.num_layers - 1))
        self.num_features_up = int(embed_dim * 2)
        self.mlp_ratio = mlp_ratio
        self.final_upsample = final_upsample

        # split image into overlapping patches
        self.patch_embed = PatchEmbed(
            img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim,
            norm_layer=norm_layer if self.patch_norm else None)
        num_patches = self.patch_embed.num_patches
        patches_resolution = self.patch_embed.patches_resolution
        self.patches_resolution = patches_resolution

        # absolute position embedding
        if self.ape:
            self.absolute_pos_embed = nn.Parameter(torch.zeros(1, num_patches, embed_dim))
            trunc_normal_(self.absolute_pos_embed, std=.02)

        self.pos_drop = nn.Dropout(p=drop_rate)
        
        # stochastic depth
        dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))]  # stochastic depth decay rule

        # build encoder and bottleneck layers
        self.layers = nn.ModuleList()
        for i_layer in range(self.num_layers):
            layer = BasicLayer(dim=int(embed_dim * 2 ** i_layer),
                               input_resolution=(patches_resolution[0] // (2 ** i_layer),
                                                 patches_resolution[1] // (2 ** i_layer)),
                               depth=depths[i_layer],
                               num_heads=num_heads[i_layer],
                               window_size=window_size,
                               mlp_ratio=self.mlp_ratio,
                               qkv_bias=qkv_bias, qk_scale=qk_scale,
                               drop=drop_rate, attn_drop=attn_drop_rate,
                               drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])],
                               norm_layer=norm_layer,
                               downsample=PatchMerging if (i_layer < self.num_layers - 1) else None,
                               use_checkpoint=use_checkpoint)
            self.layers.append(layer)
            

    # Encoder and Bottleneck
    def forward_features(self, x):
        # 这里 x 还是在原始batch图片上进行三通道扩展后的数据
        # 转到2.2.1小节 PatchEmbed
        x = self.patch_embed(x)      # (B,3,H,W)->(B, H/4 * W/4, 96)

        # 是否加入绝对位置索引
        if self.ape:       # Flase
            x = x + self.absolute_pos_embed

        x = self.pos_drop(x)  # 减少过拟合
        x_downsample = []

        '''
        self.layer总共有4层:前三层含 CST_Block×2 和 Patch_merging×1,第四层只含有 CST_Block×2;
        '''
        for layer in self.layers:   
            x_downsample.append(x)  # (B, H*W/16, 96)
            
            # 跳转到 BasicLayer,见2.2.2小节
            x = layer(x)

        x = self.norm(x)  # B L C

        return x, x_downsample

2.2.2. class BasicLayer()

类BasicLayer:实现CST_BlockPatch_merging
forward中的for blk in self.blocks:开始看:

class BasicLayer(nn.Module):
    """ A basic convolutional Swin Transformer layer for one stage.

    Args:
        dim (int): Number of input channels.
        input_resolution (tuple[int]): Input resolution.
        depth (int): Number of blocks.
        num_heads (int): Number of attention heads.
        window_size (int): Local window size.
        mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
        qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
        qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
        drop (float, optional): Dropout rate. Default: 0.0
        attn_drop (float, optional): Attention dropout rate. Default: 0.0
        drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
        norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
        downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
        use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
    """

    def __init__(self, dim, input_resolution, depth, num_heads, window_size,
                 mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0.,
                 drop_path=0., norm_layer=nn.LayerNorm, downsample=None, use_checkpoint=False):

        super().__init__()
        self.dim = dim
        self.input_resolution = input_resolution
        self.depth = depth
        self.use_checkpoint = use_checkpoint

        # build blocks
        self.blocks = nn.ModuleList([
            ConvSwinTransformerBlock(dim=dim, input_resolution=input_resolution,
                                 num_heads=num_heads, window_size=window_size,
                                 shift_size=0 if (i % 2 == 0) else window_size // 2,
                                 mlp_ratio=mlp_ratio,
                                 qkv_bias=qkv_bias, qk_scale=qk_scale,
                                 drop=drop, attn_drop=attn_drop,
                                 drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,
                                 norm_layer=norm_layer)
            for i in range(depth)])

        # patch merging layer
        if downsample is not None:
            self.downsample = downsample(input_resolution, dim=dim, norm_layer=norm_layer)
        else:
            self.downsample = None

    def forward(self, x):   #  (B, H*W/16, 96)
    
        # self.blocks有2个ConvSwinTransformerBlock,即for循环执行 2 次
        for blk in self.blocks:
        
            if self.use_checkpoint:  # False
                x = checkpoint.checkpoint(blk, x)
            else:

                # 跳转到2.2.2.1小节,执行ConvSwinTransformerBlock
                x = blk(x)
        if self.downsample is not None:
            x = self.downsample(x)
        return x

    def extra_repr(self) -> str:
        return f"dim={self.dim}, input_resolution={self.input_resolution}, depth={self.depth}"

2.2.2.1. class ConvSwinTransformerBlock()

类ConvSwinTransformerBlock()
forward中的H, W = self.input_resolution开始看:

class ConvSwinTransformerBlock(nn.Module):
    r""" Conv Swin Transformer Block.

    Args:
        dim (int): Number of input channels.
        input_resolution (tuple[int]): Input resulotion.
        num_heads (int): Number of attention heads.
        window_size (int): Window size.
        shift_size (int): Shift size for SW-MSA.
        mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
        qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
        qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
        drop (float, optional): Dropout rate. Default: 0.0
        attn_drop (float, optional): Attention dropout rate. Default: 0.0
        drop_path (float, optional): Stochastic depth rate. Default: 0.0
        norm_layer (nn.Module, optional): Normalization layer.  Default: nn.LayerNorm
    """

    def __init__(self, dim, input_resolution, num_heads, window_size=7, shift_size=0,
                 mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0.,
                 norm_layer=nn.LayerNorm):
        super().__init__()
        self.dim = dim
        self.input_resolution = input_resolution
        self.num_heads = num_heads
        self.window_size = window_size
        self.shift_size = shift_size
        self.mlp_ratio = mlp_ratio
        if min(self.input_resolution) <= self.window_size:
            # if window size is larger than input resolution, we don't partition windows
            self.shift_size = 0
            self.window_size = min(self.input_resolution)
        assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size"

        self.norm1 = norm_layer(dim)
        self.attn = WindowAttention(
            dim, window_size=to_2tuple(self.window_size), num_heads=num_heads,
            qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)

        self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
        self.mlp = Mlp(dim=dim, drop_path=drop)

        if self.shift_size > 0:
            # calculate attention mask for SW-CMSA
            H, W = self.input_resolution
            img_mask = torch.zeros((1, H, W, 1))  # 1 H W 1
            h_slices = (slice(0, -self.window_size),
                        slice(-self.window_size, -self.shift_size),
                        slice(-self.shift_size, None))
            w_slices = (slice(0, -self.window_size),
                        slice(-self.window_size, -self.shift_size),
                        slice(-self.shift_size, None))
            cnt = 0
            for h in h_slices:
                for w in w_slices:
                    img_mask[:, h, w, :] = cnt
                    cnt += 1

            mask_windows = window_partition(img_mask, self.window_size)  # nW, window_size, window_size, 1
            mask_windows = mask_windows.view(-1, self.window_size * self.window_size)
            attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
            attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0))
        else:
            attn_mask = None

        self.register_buffer("attn_mask", attn_mask)

    def forward(self, x):
 
        '''
        这里self.input_resolution在ConvSwinTransformerSys中定义:
        input_resolution[0]=H/(2^i_layer);input_resolution[1]=W/(2^i_layer)
        其中, i_layer=2
        '''
        H, W = self.input_resolution   # H/4, W/4
        B, L, C = x.shape              # (B, H*W/16, 96)
        assert L == H * W, "input feature has wrong size"  # 判断数据是否正确

        shortcut = x                  # (B, H*W/16, 96)
        
        x = self.norm1(x)             # (B, H*W/16, 96)
        x = x.view(B, H, W, C)        # (B, H/4, W/4, 96)

        # cyclic shift
        if self.shift_size > 0:    # 0
            shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
        else:
            shifted_x = x         # (B, H/4, W/4, 96)

        '''
        分割窗口:
        shifted_x=(B, H/4, W/4, 96); self.window_size=7
        具体算法:
        (1)将shifted_x的H和W分别除以window_size得到张量得shape为:
           (B, H/4/window_size, window_size, w/4/window_size, window_size, 96)
        (2)改变上面新张量的shape为: windows=(B * H/4/window_size * w/4/window_size, window_size, window_size, 96)
        其中,H/4/window_size * w/4/window_size为窗口数量,下面用nW表示窗口数量。即上式=(nW*B,window_size, window_size, 96)
        '''  # window_partition函数的实现在这段代码后面给出
        x_windows = window_partition(shifted_x, self.window_size)  # nW*B, window_size, window_size, C
        # 改变shape,第1、2维相乘
        x_windows = x_windows.view(-1, self.window_size * self.window_size, C)  # nW*B, window_size*window_size, C

        # W-MSA/SW-MSA
        # self.attn = WindowAttention(),跳转到2.2.2.1.1小节
        attn_windows = self.attn(x_windows, mask=self.attn_mask)  # nW*B, window_size*window_size, C

        # merge windows
        attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C)
        shifted_x = window_reverse(attn_windows, self.window_size, H, W)  # B H' W' C

        # reverse cyclic shift
        if self.shift_size > 0:
            x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
        else:
            x = shifted_x
        x = x.view(B, H * W, C)
        x = shortcut + self.drop_path(x)

        # FFN
        x = x.view(B, H, W, C)
        x = self.mlp(x)
        x = x.view(B, H * W, C)
        return x

    def extra_repr(self) -> str:
        return f"dim={self.dim}, input_resolution={self.input_resolution}, num_heads={self.num_heads}, " \
               f"window_size={self.window_size}, shift_size={self.shift_size}, mlp_ratio={self.mlp_ratio}"

函数window_partition的实现:

def window_partition(x, window_size):
    """
    Args:
        x: (B, H, W, C)
        window_size (int): window size

    Returns:
        windows: (num_windows*B, window_size, window_size, C)
    """
    B, H, W, C = x.shape
    x = x.view(B, H // window_size, window_size, W // window_size, window_size, C)
    windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
    return windows


2.2.2.1.1. class WindowAttention()

类class WindowAttention()
forward中的B_, N, C = x.shape开始看:

class WindowAttention(nn.Module):
    r""" Window based multi-head self attention (W-MSA) module with relative position bias.
    It supports both of shifted and non-shifted window.

    Args:
        dim (int): Number of input channels.
        window_size (tuple[int]): The height and width of the window.
        num_heads (int): Number of attention heads.
        qkv_bias (bool, optional):  If True, add a learnable bias to query, key, value. Default: True
        qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set
        attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
        proj_drop (float, optional): Dropout ratio of output. Default: 0.0
    """

    def __init__(self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0., proj_drop=0.):

        super().__init__()
        self.dim = dim
        self.window_size = window_size  # Wh, Ww
        self.num_heads = num_heads
        head_dim = dim // num_heads
        self.scale = qk_scale or head_dim ** -0.5

        self.conv_proj_q = self._build_projection(dim, kernel_size=3, stride=1, padding=1)
        self.conv_proj_k = self._build_projection(dim, kernel_size=3, stride=1, padding=1)
        self.conv_proj_v = self._build_projection(dim, kernel_size=3, stride=1, padding=1)

        self.attn_drop = nn.Dropout(attn_drop)
        self.proj = nn.Sequential(nn.Conv2d(dim, dim, kernel_size=3, padding=1, stride=1, bias=False, groups=dim), nn.GELU())
        self.proj_drop = nn.Dropout(proj_drop)

        self.softmax = nn.Softmax(dim=-1)

    def _build_projection(self, dim_in, kernel_size=3, stride=1, padding=1):
        proj = nn.Sequential(
            nn.Conv2d(dim_in, dim_in, kernel_size, padding=padding, stride=stride, bias=False, groups=dim_in),
            Rearrange('b c h w -> b (h w) c'),
            nn.LayerNorm(dim_in))
        return proj

    def forward(self, x, mask=None):
        """
        Args:
            x: input features with shape of (num_windows*B, N, C)
            mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None
        """
        # [batch_size*num_windows, Mh*Mw, total_embed_dim]
        B_, N, C = x.shape                # nW*B, window_size*window_size, C
        Mh = int(N ** .5)                 # Mh = window_size
        x = x.view(B_, Mh, Mh, C).permute(0, 3, 1, 2)  # [nW*B, Mh, Mw, C]->[nW*B, C, Mh, Mw]
        
        # when we use conv the shape should be B, C, H, W. so use permute,其中num_heads=3
        # self.conv_proj_q具体实现在这段代码后面说明
        '''
        q、k、v的生成:分 3 步
        (1)conv_proj_q的功能: 经过一个3×3的卷积核(但不改变尺寸和通道数) ,然后经过Rearrange:[nW*B, C, Mh, Mw]->[nW*B, Mh*Mw, C],最后经过一个LayerNorm层
        (2)reshape:[nW*B, Mh*Mw, C]->[nW*B, Mh*Mw, num_heads, C/num_heads]=[nW*B, Mh*Mw, 3, C/3]
        (3)permute: [nW*B, 3, Mh*Mw, C/3]
        '''
        q = self.conv_proj_q(x).reshape(B_, N, self.num_heads, C // self.num_heads).permute(0, 2, 1,3)  # [batch_size*num_windows, num_heads, Mh*Mw, embed_dim_per_head]
        k = self.conv_proj_k(x).reshape(B_, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
        v = self.conv_proj_v(x).reshape(B_, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)

        '''self.scale的计算过程:
        (1)head_dim = dim // num_heads    # 96/3 = 32
        (2)self.scale = head_dim ** -0.5   # 1/√32 ≈ 0.1768
        '''
        q = q * self.scale                        # [nW*B, num_heads, Mh*Mw, C/num_heads]=[nW*B, 3, Mh*Mw, C/3]
        attn = (q @ k.transpose(-2, -1))          # [nW*B, num_heads, Mh*Mw, Mh*Mw]
        # transpose: -> [batch_size*num_windows, num_heads, embed_dim_per_head, Mh*Mw]
        # @:multiply -> [batch_size*num_windows, num_heads, Mh*Mw, Mh*Mw]


        if mask is not None:   # None
            # mask: [nW, Mh*Mw, Mh*Mw]
            nW = mask.shape[0]  # num_windows
            # attn.view: [batch_size, num_windows, num_heads, Mh*Mw, Mh*Mw]
            # mask.unsqueeze: [1, nW, 1, Mh*Mw, Mh*Mw]
            attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0)
            attn = attn.view(-1, self.num_heads, N, N)
            attn = self.softmax(attn)
            
        else:
            attn = self.softmax(attn)   # [nW*B, num_heads, Mh*Mw, Mh*Mw]
        attn = self.attn_drop(attn)     # [nW*B, num_heads, Mh*Mw, Mh*Mw]

        '''Mh = Mw
        (1)[nW*B, num_heads, Mh*Mw, Mh*Mw] @ [nW*B, num_heads, Mh*Mw, C/num_heads]=[nW*B, num_heads, Mh*Mw, C/num_heads]
        (2)transpose(2, 3): [nW*B, num_heads, C/num_heads, Mh*Mw]
        (3)reshape(B_, C, Mh, Mh): [nW*B, C, Mh, Mw]
        '''
        x = (attn @ v).transpose(2, 3).reshape(B_, C, Mh, Mh)     # [nW*B, C, Mh, Mw]
        
        x = self.proj(x)     # 3×3的卷积和Relu层,特征图shape不变。 # [nW*B, C, Mh, Mw] = [nW*B, 96, 7, 7]
        x = x.reshape(B_, C, N).transpose(1, 2)  # [nW*B, C, Mh, Mw]->[nW*B, C, Mh*Mw]->[nW*B, Mh*Mw, C]
        x = self.proj_drop(x)                    # [nW*B, Mh*Mw, C]

        return x          # [nW*B, Mh*Mw, C]
        # 到这里class WindowAttention()执行结束,下面跳到2.2.2.1.(1)小节

    def extra_repr(self) -> str:
        return f'dim={self.dim}, window_size={self.window_size}, num_heads={self.num_heads}'

self.conv_proj_q的实现:

self.conv_proj_k = self._build_projection(dim, kernel_size=3, stride=1, padding=1) 
# 跳到self._build_projection, 见下面
    def _build_projection(self, dim_in, kernel_size=3, stride=1, padding=1):
        proj = nn.Sequential(
            nn.Conv2d(dim_in, dim_in, kernel_size, padding=padding, stride=stride, bias=False, groups=dim_in),
            Rearrange('b c h w -> b (h w) c'),    # [nW*B, C, Mh, Mw]->[nW*B, Mh, Mw,C]
            nn.LayerNorm(dim_in))
        return proj
2.2.2.1.(1)

类ConvSwinTransformerBlock():简洁起见,只显示forward部分
forward中的attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C)开始看:

    def forward(self, x):
        H, W = self.input_resolution
        B, L, C = x.shape
        assert L == H * W, "input feature has wrong size"

        shortcut = x
        x = self.norm1(x)
        x = x.view(B, H, W, C)

        # cyclic shift
        if self.shift_size > 0:
            shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
        else:
            shifted_x = x

        # partition windows
        x_windows = window_partition(shifted_x, self.window_size)  # nW*B, window_size, window_size, C
        x_windows = x_windows.view(-1, self.window_size * self.window_size, C)  # nW*B, window_size*window_size, C

        # W-MSA/SW-MSA: WindowAttention
        attn_windows = self.attn(x_windows, mask=self.attn_mask)  # nW*B, window_size*window_size, C

        # merge windows
        attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C) # [nW*B, Mh*Mw, C]->[nW*B, Mh, Mw, C]

        '''window_reverse: 还原特征图[B, H, W, C],这里的H和W为原尺寸的1/4
        其中attn_windows=[nW*B, Mh, Mw, C],window_size=7, H=W=img_size/4(56)
        (1)B = int(windows.shape[0] / (H * W / window_size / window_size)):得到batch_size
        (2)x = windows.view: [B, H/window_size, W/window_size,Mh, Mw, C]
        (3) [B, H/window_size, W/window_size,Mh, Mw, C]-> [B, H/window_size*Mh, W/window_size*Mw, C]->[B, H, W, C]
        '''# window_reverse的实现在这段代码的下面
        shifted_x = window_reverse(attn_windows, self.window_size, H, W)  # [B, H, W, C]

        # reverse cyclic shift
        if self.shift_size > 0:   # 0
            x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
            
        else:
            x = shifted_x                 # [B, H, W, C]
        x = x.view(B, H * W, C)           # [B, H*W, C]
        x = shortcut + self.drop_path(x)  # [B, H*W, C]+drop([B, H*W, C])=[B, H*W, C]

        # FFN
        x = x.view(B, H, W, C)      # [B, H, W, C]

        # 类Mlp,接下来跳转到2.2.2.1.2.小节 
        x = self.mlp(x)           # [B, H, W, C]->
        x = x.view(B, H * W, C)
        return x

    def extra_repr(self) -> str:
        return f"dim={self.dim}, input_resolution={self.input_resolution}, num_heads={self.num_heads}, " \
               f"window_size={self.window_size}, shift_size={self.shift_size}, mlp_ratio={self.mlp_ratio}"

函数window_reverse

def window_reverse(windows, window_size, H, W):
    """
    Args:
        windows: (num_windows*B, window_size, window_size, C)
        window_size (int): Window size
        H (int): Height of image
        W (int): Width of image

    Returns:
        x: (B, H, W, C)
    """
    B = int(windows.shape[0] / (H * W / window_size / window_size))
    x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1)
    x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)
    return x

2.2.2.1.2. class Mlp()

类Mlp
forward中的input = x 开始看

class Mlp(nn.Module):
    def __init__(self, dim, drop_path=0.2, layer_scale_init_value=0.7):
        super().__init__()
        self.dwconv = nn.Conv2d(dim, dim, kernel_size=7, padding=3, groups=dim)  # depthwise conv 7,3  5,2  3,1
        self.norm = nn.LayerNorm(dim, eps=1e-6)
        self.pwconv1 = nn.Conv2d(dim, 4 * dim, kernel_size=1)
        self.act = nn.GELU()
        self.pwconv2 = nn.Conv2d(4 * dim, dim, kernel_size=1)  # nn.Linear(4 * dim, dim)
        self.gamma = nn.Parameter(layer_scale_init_value * torch.ones((dim)),
                                  requires_grad=True) if layer_scale_init_value > 0 else None
        self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()

    def forward(self, x):   # 这里的H和W为原尺寸的1/4
        input = x  # [B, H, W, C]
        x = x.permute(0, 3, 1, 2)  # [B, H, W, C] -> [B, C, H, W]

        # 7×7的卷积核,图像尺寸和channels不变
        x = self.dwconv(x)         # [B, C, H, W]
        x = x.permute(0, 2, 3, 1)  # [B, H, W, C]
        x = self.norm(x)
        x = x.permute(0, 3, 1, 2)  # [B, C, H, W]

        # 1×1的pointwise卷积:channels -> channels×4
        x = self.pwconv1(x)        # [B, 4C, H, W]
        x = self.act(x)            # GELU层

        # 1×1的pointwise卷积:channels×4 -> channels
        x = self.pwconv2(x)        # [B, C, H, W]
        x = x.permute(0, 2, 3, 1)  # [B, C, H, W] -> [B, H, W, C]

        # gamma在上面声明不为None
        if self.gamma is not None:     # 
            x = self.gamma * x         # [B, H, W, C]
        x = input + self.drop_path(x)  # [B, H, W, C]
        return x        # [B, H, W, C]
        # Mlp执行结束,接下来跳到2.2.2.1.(2)小节

2.2.2.1.(2)

类ConvSwinTransformerBlock():简洁起见,只显示forward部分
forward中的x = x.view(B, H * W, C)开始看:

    def forward(self, x):
        H, W = self.input_resolution
        B, L, C = x.shape
        assert L == H * W, "input feature has wrong size"

        shortcut = x
        x = self.norm1(x)
        x = x.view(B, H, W, C)

        # cyclic shift
        if self.shift_size > 0:
            shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
        else:
            shifted_x = x

        # partition windows
        x_windows = window_partition(shifted_x, self.window_size)  # nW*B, window_size, window_size, C
        x_windows = x_windows.view(-1, self.window_size * self.window_size, C)  # nW*B, window_size*window_size, C

        # W-MSA/SW-MSA
        attn_windows = self.attn(x_windows, mask=self.attn_mask)  # nW*B, window_size*window_size, C

        # merge windows
        attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C)
        shifted_x = window_reverse(attn_windows, self.window_size, H, W)  # B H' W' C

        # reverse cyclic shift
        if self.shift_size > 0:
            x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
        else:
            x = shifted_x
        x = x.view(B, H * W, C)
        x = shortcut + self.drop_path(x)

        # FFN
        x = x.view(B, H, W, C)
        x = self.mlp(x)          # [B, H, W, C]
        x = x.view(B, H * W, C)  # [B, H*W, C]
        return x                 # [B, H*W, C]
        # 到这里 类ConvSwinTransformerBlock()执行结束,接下来跳转到2.2.2.(1) class BasicLayer()

2.2.2.(1)

类BasicLayer:实现CST_BlockPatch_merging
forward中的for blk in self.blocks:开始看:到这blk开始执行第2次

    def forward(self, x):   #  (B, H*W/16, 96)
    
        # self.blocks有2个ConvSwinTransformerBlock,即for循环执行 2 次
        for blk in self.blocks:
        
            if self.use_checkpoint:  # False
                x = checkpoint.checkpoint(blk, x)
            else:

                # 跳转到2.2.2.1小节,执行ConvSwinTransformerBlock
                '''循环的第二次和第一次基本一样,但是在class WindowAttention()中mask不为None,接下来从2.2.2.1.1.(1)这里开始
                '''
                x = blk(x)
        if self.downsample is not None:
            x = self.downsample(x)
        return x

    def extra_repr(self) -> str:
        return f"dim={self.dim}, input_resolution={self.input_resolution}, depth={self.depth}"

2.2.2.1.1.(1)

类class WindowAttention():简洁起见,只看forward过程
forward中的B_, N, C = x.shape开始看:

    def forward(self, x, mask=None):
        """
        Args:
            x: input features with shape of (num_windows*B, N, C)
            mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None
        """
        # [batch_size*num_windows, Mh*Mw, total_embed_dim]
        B_, N, C = x.shape                # nW*B, window_size*window_size, C
        Mh = int(N ** .5)                 # Mh = window_size
        x = x.view(B_, Mh, Mh, C).permute(0, 3, 1, 2)  # [nW*B, Mh, Mw, C]->[nW*B, C, Mh, Mw]
        
        # when we use conv the shape should be B, C, H, W. so use permute,其中num_heads=3
        # self.conv_proj_q具体实现在这段代码后面说明
        '''
        q、k、v的生成:分 3 步
        (1)conv_proj_q的功能: 经过一个3×3的卷积核(但不改变尺寸和通道数) ,然后经过Rearrange:[nW*B, C, Mh, Mw]->[nW*B, Mh*Mw, C],最后经过一个LayerNorm层
        (2)reshape:[nW*B, Mh*Mw, C]->[nW*B, Mh*Mw, num_heads, C/num_heads]=[nW*B, Mh*Mw, 3, C/3]
        (3)permute: [nW*B, 3, Mh*Mw, C/3]
        '''
        q = self.conv_proj_q(x).reshape(B_, N, self.num_heads, C // self.num_heads).permute(0, 2, 1,3)  # [batch_size*num_windows, num_heads, Mh*Mw, embed_dim_per_head]
        k = self.conv_proj_k(x).reshape(B_, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
        v = self.conv_proj_v(x).reshape(B_, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)

        '''self.scale的计算过程:
        (1)head_dim = dim // num_heads    # 96/3 = 32
        (2)self.scale = head_dim ** -0.5   # 1/√32 ≈ 0.1768
        '''
        q = q * self.scale                        # [nW*B, num_heads, Mh*Mw, C/num_heads]=[nW*B, 3, Mh*Mw, C/3]
        attn = (q @ k.transpose(-2, -1))          # [nW*B, num_heads, Mh*Mw, Mh*Mw]
        # transpose: -> [batch_size*num_windows, num_heads, embed_dim_per_head, Mh*Mw]
        # @:multiply -> [batch_size*num_windows, num_heads, Mh*Mw, Mh*Mw]


        if mask is not None:   # mask: [nW, Mh*Mw, Mh*Mw], N = Mh*Mw, B_ = nW*B
            nW = mask.shape[0]  # num_windows
            
            '''
            attn.view: [B, nW, num_heads, Mh*Mw, Mh*Mw]
            mask.unsqueeze: [1, nW, 1, Mh*Mw, Mh*Mw]
            attn.view + mask.unsqueeze: [B, nW, num_heads, Mh*Mw, Mh*Mw]
            '''
            attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0)
            
            attn = attn.view(-1, self.num_heads, N, N) # [B_, num_heads, Mh*Mw, Mh*Mw]
            attn = self.softmax(attn)                  # [B_, num_heads, Mh*Mw, Mh*Mw]
            # 到这里,后面和blk循环的第一次基本相同,但是在ConvSwinTransformerBlock中shift_size≠0,接下来跳转到2.2.2.1.(1)
            
            
        else:
            attn = self.softmax(attn)   
            
        attn = self.attn_drop(attn)                    # [nW*B, num_heads, Mh*Mw, Mh*Mw]

        '''Mh = Mw
        (1)[nW*B, num_heads, Mh*Mw, Mh*Mw] @ [nW*B, num_heads, Mh*Mw, C/num_heads]=[nW*B, num_heads, Mh*Mw, C/num_heads]
        (2)transpose(2, 3): [nW*B, num_heads, C/num_heads, Mh*Mw]
        (3)reshape(B_, C, Mh, Mh): [nW*B, C, Mh, Mw]
        '''
        x = (attn @ v).transpose(2, 3).reshape(B_, C, Mh, Mh)     # [nW*B, C, Mh, Mw]
        
        x = self.proj(x)     # 3×3的卷积和Relu层,特征图shape不变。 # [nW*B, C, Mh, Mw] = [nW*B, 96, 7, 7]
        x = x.reshape(B_, C, N).transpose(1, 2)  # [nW*B, C, Mh, Mw]->[nW*B, C, Mh*Mw]->[nW*B, Mh*Mw, C]
        x = self.proj_drop(x)                    # [nW*B, Mh*Mw, C]

        return x          # [nW*B, Mh*Mw, C]
        # 到这里class WindowAttention()执行结束,下面跳到2.2.2.1.(3)小节

    def extra_repr(self) -> str:
        return f'dim={self.dim}, window_size={self.window_size}, num_heads={self.num_heads}'

2.2.2.1.(3)

类ConvSwinTransformerBlock()
forward中的# cyclic shift开始看:

    def forward(self, x):
 
        '''
        这里self.input_resolution在ConvSwinTransformerSys中定义:
        input_resolution[0]=H/(2^i_layer);input_resolution[1]=W/(2^i_layer)
        其中, i_layer=2
        '''
        H, W = self.input_resolution   # H/4, W/4
        B, L, C = x.shape              # (B, H*W/16, 96)
        assert L == H * W, "input feature has wrong size"  # 判断数据是否正确

        shortcut = x                  # (B, H*W/16, 96)
        
        x = self.norm1(x)             # (B, H*W/16, 96)
        x = x.view(B, H, W, C)        # (B, H/4, W/4, 96)

        # cyclic shift
        '''
        torch.roll 函数接受两个参数:输入张量和滚动的偏移量。在这里,shifts=(-self.shift_size, -self.shift_size) 表示向左
        上方滚动 self.shift_size 个位置。这意味着 x 中的元素将被沿着第一个维度(dim=1)和第二个维度(dim=2)同时向左移动
        self.shift_size 个位置。
        注意: 滚动操作不会改变张量的形状和元素的顺序,只是将元素按照指定的偏移量进行重新排列。
        '''
        if self.shift_size > 0:    # 3
            shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
        # 这里采用滚动,后面还要反滚动(reverse cyclic shift)复原窗口

        else:
            shifted_x = x         # (B, H/4, W/4, 96)

        '''
        分割窗口:
        shifted_x=(B, H/4, W/4, 96); self.window_size=7
        具体算法:
        (1)将shifted_x的H和W分别除以window_size得到张量得shape为:
           (B, H/4/window_size, window_size, w/4/window_size, window_size, 96)
        (2)改变上面新张量的shape为: windows=(B * H/4/window_size * w/4/window_size, window_size, window_size, 96)
        其中,H/4/window_size * w/4/window_size为窗口数量,下面用nW表示窗口数量。即上式=(nW*B,window_size, window_size, 96)
        '''  # window_partition函数的实现在这段代码后面给出
        x_windows = window_partition(shifted_x, self.window_size)  # nW*B, window_size, window_size, C
        # 改变shape,第1、2维相乘
        x_windows = x_windows.view(-1, self.window_size * self.window_size, C)  # nW*B, window_size*window_size, C

        # W-MSA/SW-MSA
        # self.attn = WindowAttention(),跳转到2.2.2.1.1小节
        attn_windows = self.attn(x_windows, mask=self.attn_mask)  # nW*B, window_size*window_size, C

        # merge windows
        attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C)
        shifted_x = window_reverse(attn_windows, self.window_size, H, W)  # B H' W' C

        # reverse cyclic shift
        if self.shift_size > 0:
            x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
        else:
            x = shifted_x
            
        x = x.view(B, H * W, C)           # [B, H*W, C]
        x = shortcut + self.drop_path(x)  # [B, H*W, C]+drop([B, H*W, C])=[B, H*W, C]

        # FFN
        x = x.view(B, H, W, C)
        x = self.mlp(x)          # [B, H, W, C]
        x = x.view(B, H * W, C)  # [B, H*W, C]
        return x                 # [B, H*W, C]
        # 到这里blk的循环就结束了, 跳转到2.2.2.(2)小节


2.2.2.(2)

类BasicLayer:实现CST_BlockPatch_merging
forward中的if self.downsample is not None:开始看:

    def forward(self, x):   #  (B, H*W/16, 96)
    
        # self.blocks有2个ConvSwinTransformerBlock,即for循环执行 2 次
        for blk in self.blocks:
        
            if self.use_checkpoint:  # False
                x = checkpoint.checkpoint(blk, x)
            else:
                x = blk(x)     # [B, H*W, C]

        
        if self.downsample is not None:   # Patch_Merging
            # downsample=PatchMerging, 接下来跳转到类PatchMerging
            x = self.downsample(x)      # [B, H*W, C]->[B,]
        return x

    def extra_repr(self) -> str:
        return f"dim={self.dim}, input_resolution={self.input_resolution}, depth={self.depth}"

2.2.2.2. class PatchMerging()

类PatchMerging()
forward中的H, W = self.input_resolution开始看

class PatchMerging(nn.Module):
    r""" Patch Merging Layer.

    Args:
        input_resolution (tuple[int]): Resolution of input feature.
        dim (int): Number of input channels.
        norm_layer (nn.Module, optional): Normalization layer.  Default: nn.LayerNorm
    """
    def __init__(self, input_resolution, dim, norm_layer=nn.LayerNorm):
        super().__init__()
        self.input_resolution = input_resolution
        self.dim = dim
        self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
        self.norm = norm_layer(4 * dim)

    def forward(self, x):  # [B, H*W, C]
        H, W = self.input_resolution
        B, L, C = x.shape             # L = H*W
        assert L == H * W, "input feature has wrong size"
        assert H % 2 == 0 and W % 2 == 0, f"x size ({H}*{W}) are not even."

        x = x.view(B, H, W, C)

        '''
        解释一下操作符 "::" 的含义:
        在 Python 中,start:stop:step 表示从索引 start 开始,到索引 stop-1 结束,每隔 step 个元素取
        一个。如果不指定 start 和 stop,则默认从头开始或者到末尾结束。
        举个例子解释代码:
        x0 = x[:, 0::2, 0::2, :]:这行代码从输入张量 x 中按照步长为 2 在第一个维度、第二个维度进行子采样。
        它选择了索引为偶数的行和列,得到的结果是原张量的一半高度和一半宽度,形状为 B (batch size) × H/2 × W/2 × C。
        '''
        x0 = x[:, 0::2, 0::2, :]  # B H/2 W/2 C
        x1 = x[:, 1::2, 0::2, :]  # B H/2 W/2 C
        x2 = x[:, 0::2, 1::2, :]  # B H/2 W/2 C
        x3 = x[:, 1::2, 1::2, :]  # B H/2 W/2 C

        # 
        x = torch.cat([x0, x1, x2, x3], -1)  # [B, H/2, W/2, 4*C]
        x = x.view(B, -1, 4 * C)  # [B, H/2*W/2, 4*C]
        x = self.norm(x)          # [B, H/2*W/2, 4*C]
        x = self.reduction(x)     # [B, H/2*W/2, 4*C]->[B, H/2*W/2, 2*C]
        return x      # [B, H/2*W/2, 2*C]
        # 到这里PatchMerging执行结束, 接下来跳转到2.2.2.(3)小节类BasicLayer

2.2.2.(3)

类BasicLayer:实现CST_BlockPatch_merging
forward中的return x开始看:到这里其实类BasicLayer也执行结束了,返回的张量shape为 [B, H/2 * W/2, 2 * C]。

    def forward(self, x):   #  (B, H*W/16, 96)
    
        # self.blocks有2个ConvSwinTransformerBlock,即for循环执行 2 次
        for blk in self.blocks:
        
            if self.use_checkpoint:  # False
                x = checkpoint.checkpoint(blk, x)
            else:
                x = blk(x)     # [B, H*W, C]

        
        if self.downsample is not None:   # Patch_Merging
            # downsample=PatchMerging, 接下来跳转到类PatchMerging
            x = self.downsample(x)      # [B, H*W, C]->[B, H/2*W/2, 2*C]
        return x       # [B, H/2*W/2, 2*C]
        # 执行结束, 跳转到2.2.(2)小节 class ConvSwinTransformerSys()


2.2.(2)

类ConvSwinTransformerSys()与2.1小节相同,为简洁起见,在这里只展示要用到的代码段
forward_featuresfor layer in self.layers:开始看

    # Encoder and Bottleneck
    def forward_features(self, x):
        # 这里 x 还是在原始batch图片上进行三通道扩展后的数据
        # 转到2.2.1小节 PatchEmbed
        x = self.patch_embed(x)      # (B,3,H,W)->(B, H/4 * W/4, 96)

        # 是否加入绝对位置索引
        if self.ape:       # Flase
            x = x + self.absolute_pos_embed

        x = self.pos_drop(x)  # 减少过拟合
        x_downsample = []

        '''
        self.layer总共有4层:前三层含 CST_Block×2 和 Patch_merging×1,第四层只含有 CST_Block×2;
        这里的 H 和 W 是图像原尺寸的高和宽
        '''# 总共执行4次
        for layer in self.layers:   
            x_downsample.append(x)  # (B, H*W/16, C);(B, H*W/64, 2*C);(B, H*W/256, 4*C);(B, H*W/1024, 8*C)
            
            # 跳转到 BasicLayer,见2.2.2小节
            x = layer(x)      

        '''
        上面layer循环结束后,得到两个参数:
        (1)x_downsample[0]: (B, H*W/16, C);(B, H*W/64, 2*C);(B, H*W/256, 4*C);(B, H*W/1024, 8*C)
           x_downsample[1]: (B, H*W/64, 2*C);(B, H*W/256, 4*C);(B, H*W/1024, 8*C)
           x_downsample[2]: (B, H*W/256, 4*C);(B, H*W/1024, 8*C)
           x_downsample[3]: (B, H*W/1024, 8*C)
        (2)x:(B, H*W/1024, 8*C)
        '''
        x = self.norm(x)  # (B, H*W/1024, 8*C) :B L C

        return x, x_downsample
        # 到这里类ConvSwinTransformerSys()中的forward_features执行结束,接下来跳转到2.3小节class ConvSwinTransformerSys()的forward部分

2.3. class ConvSwinTransformerSys()

类ConvSwinTransformerSys()与2.1小节相同,在这里只展示要用到的代码段
forwardx = self.forward_up_features(x, x_downsample)开始看

    def forward(self, x):
        x, x_downsample = self.forward_features(x)   # (B,3,H,W)

        '''
        (1)x_downsample[0]: (B, H*W/16, C)
           x_downsample[1]: (B, H*W/64, 2*C)
           x_downsample[2]: (B, H*W/256, 4*C)
           x_downsample[3]: (B, H*W/1024, 8*C)
        (2)x:(B, H*W/1024, 8*C)
        '''# 跳转到forward_up_features,见下面代码
        x = self.forward_up_features(x, x_downsample) 
        x = self.up_x4(x)
        return x

函数forward_up_features:从for inx, layer_up in enumerate(self.layers_up):开始看

    def forward_up_features(self, x, x_downsample):

        '''
        layers_up共有4层,详细结构在这段代码的后面
        其中,
        PatchExpand:
        '''
        for inx, layer_up in enumerate(self.layers_up):
            if inx == 0:
                # layer_up=PatchExpand, 接下来跳转到2.3.1小节class PatchExpand
                x = layer_up(x)   # (B, H*W/1024, 8*C)
            else:
                x = torch.cat([x, x_downsample[3 - inx]], -1)
                x = self.concat_back_dim[inx](x)
                x = layer_up(x)

        x = self.norm_up(x)  # B L C
        return x

self.layers_up的结构:

ModuleList(
  (0): PatchExpand(
    (up): Sequential(
      (0): ConvTranspose2d(768, 384, kernel_size=(2, 2), stride=(2, 2))
      (1): GELU()
    )
    (norm): LayerNorm((768,), eps=1e-05, elementwise_affine=True)
    (drop): Dropout(p=0.2, inplace=False)
  )
  (1): BasicLayer_up(
    (blocks): ModuleList(
      (0): ConvSwinTransformerBlock(
        dim=384, input_resolution=(14, 14), num_heads=12, window_size=7, shift_size=0, mlp_ratio=4.0
        (norm1): LayerNorm((384,), eps=1e-05, elementwise_affine=True)
        (attn): WindowAttention(
          dim=384, window_size=(7, 7), num_heads=12
          (conv_proj_q): Sequential(
            (0): Conv2d(384, 384, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), groups=384, bias=False)
            (1): Rearrange('b c h w -> b (h w) c')
            (2): LayerNorm((384,), eps=1e-05, elementwise_affine=True)
          )
          (conv_proj_k): Sequential(
            (0): Conv2d(384, 384, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), groups=384, bias=False)
            (1): Rearrange('b c h w -> b (h w) c')
            (2): LayerNorm((384,), eps=1e-05, elementwise_affine=True)
          )
          (conv_proj_v): Sequential(
            (0): Conv2d(384, 384, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), groups=384, bias=False)
            (1): Rearrange('b c h w -> b (h w) c')
            (2): LayerNorm((384,), eps=1e-05, elementwise_affine=True)
          )
          (attn_drop): Dropout(p=0.0, inplace=False)
          (proj): Sequential(
            (0): Conv2d(384, 384, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), groups=384, bias=False)
            (1): GELU()
          )
          (proj_drop): Dropout(p=0.0, inplace=False)
          (softmax): Softmax(dim=-1)
        )
        (drop_path): DropPath()
        (mlp): Mlp(
          (dwconv): Conv2d(384, 384, kernel_size=(7, 7), stride=(1, 1), padding=(3, 3), groups=384)
          (norm): LayerNorm((384,), eps=1e-06, elementwise_affine=True)
          (pwconv1): Conv2d(384, 1536, kernel_size=(1, 1), stride=(1, 1))
          (act): GELU()
          (pwconv2): Conv2d(1536, 384, kernel_size=(1, 1), stride=(1, 1))
          (drop_path): Identity()
        )
      )
      (1): ConvSwinTransformerBlock(
        dim=384, input_resolution=(14, 14), num_heads=12, window_size=7, shift_size=3, mlp_ratio=4.0
        (norm1): LayerNorm((384,), eps=1e-05, elementwise_affine=True)
        (attn): WindowAttention(
          dim=384, window_size=(7, 7), num_heads=12
          (conv_proj_q): Sequential(
            (0): Conv2d(384, 384, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), groups=384, bias=False)
            (1): Rearrange('b c h w -> b (h w) c')
            (2): LayerNorm((384,), eps=1e-05, elementwise_affine=True)
          )
          (conv_proj_k): Sequential(
            (0): Conv2d(384, 384, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), groups=384, bias=False)
            (1): Rearrange('b c h w -> b (h w) c')
            (2): LayerNorm((384,), eps=1e-05, elementwise_affine=True)
          )
          (conv_proj_v): Sequential(
            (0): Conv2d(384, 384, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), groups=384, bias=False)
            (1): Rearrange('b c h w -> b (h w) c')
            (2): LayerNorm((384,), eps=1e-05, elementwise_affine=True)
          )
          (attn_drop): Dropout(p=0.0, inplace=False)
          (proj): Sequential(
            (0): Conv2d(384, 384, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), groups=384, bias=False)
            (1): GELU()
          )
          (proj_drop): Dropout(p=0.0, inplace=False)
          (softmax): Softmax(dim=-1)
        )
        (drop_path): DropPath()
        (mlp): Mlp(
          (dwconv): Conv2d(384, 384, kernel_size=(7, 7), stride=(1, 1), padding=(3, 3), groups=384)
          (norm): LayerNorm((384,), eps=1e-06, elementwise_affine=True)
          (pwconv1): Conv2d(384, 1536, kernel_size=(1, 1), stride=(1, 1))
          (act): GELU()
          (pwconv2): Conv2d(1536, 384, kernel_size=(1, 1), stride=(1, 1))
          (drop_path): Identity()
        )
      )
    )
    (upsample): PatchExpand(
      (up): Sequential(
        (0): ConvTranspose2d(384, 192, kernel_size=(2, 2), stride=(2, 2))
        (1): GELU()
      )
      (norm): LayerNorm((384,), eps=1e-05, elementwise_affine=True)
      (drop): Dropout(p=0.2, inplace=False)
    )
  )
  (2): BasicLayer_up(
    (blocks): ModuleList(
      (0): ConvSwinTransformerBlock(
        dim=192, input_resolution=(28, 28), num_heads=6, window_size=7, shift_size=0, mlp_ratio=4.0
        (norm1): LayerNorm((192,), eps=1e-05, elementwise_affine=True)
        (attn): WindowAttention(
          dim=192, window_size=(7, 7), num_heads=6
          (conv_proj_q): Sequential(
            (0): Conv2d(192, 192, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), groups=192, bias=False)
            (1): Rearrange('b c h w -> b (h w) c')
            (2): LayerNorm((192,), eps=1e-05, elementwise_affine=True)
          )
          (conv_proj_k): Sequential(
            (0): Conv2d(192, 192, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), groups=192, bias=False)
            (1): Rearrange('b c h w -> b (h w) c')
            (2): LayerNorm((192,), eps=1e-05, elementwise_affine=True)
          )
          (conv_proj_v): Sequential(
            (0): Conv2d(192, 192, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), groups=192, bias=False)
            (1): Rearrange('b c h w -> b (h w) c')
            (2): LayerNorm((192,), eps=1e-05, elementwise_affine=True)
          )
          (attn_drop): Dropout(p=0.0, inplace=False)
          (proj): Sequential(
            (0): Conv2d(192, 192, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), groups=192, bias=False)
            (1): GELU()
          )
          (proj_drop): Dropout(p=0.0, inplace=False)
          (softmax): Softmax(dim=-1)
        )
        (drop_path): DropPath()
        (mlp): Mlp(
          (dwconv): Conv2d(192, 192, kernel_size=(7, 7), stride=(1, 1), padding=(3, 3), groups=192)
          (norm): LayerNorm((192,), eps=1e-06, elementwise_affine=True)
          (pwconv1): Conv2d(192, 768, kernel_size=(1, 1), stride=(1, 1))
          (act): GELU()
          (pwconv2): Conv2d(768, 192, kernel_size=(1, 1), stride=(1, 1))
          (drop_path): Identity()
        )
      )
      (1): ConvSwinTransformerBlock(
        dim=192, input_resolution=(28, 28), num_heads=6, window_size=7, shift_size=3, mlp_ratio=4.0
        (norm1): LayerNorm((192,), eps=1e-05, elementwise_affine=True)
        (attn): WindowAttention(
          dim=192, window_size=(7, 7), num_heads=6
          (conv_proj_q): Sequential(
            (0): Conv2d(192, 192, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), groups=192, bias=False)
            (1): Rearrange('b c h w -> b (h w) c')
            (2): LayerNorm((192,), eps=1e-05, elementwise_affine=True)
          )
          (conv_proj_k): Sequential(
            (0): Conv2d(192, 192, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), groups=192, bias=False)
            (1): Rearrange('b c h w -> b (h w) c')
            (2): LayerNorm((192,), eps=1e-05, elementwise_affine=True)
          )
          (conv_proj_v): Sequential(
            (0): Conv2d(192, 192, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), groups=192, bias=False)
            (1): Rearrange('b c h w -> b (h w) c')
            (2): LayerNorm((192,), eps=1e-05, elementwise_affine=True)
          )
          (attn_drop): Dropout(p=0.0, inplace=False)
          (proj): Sequential(
            (0): Conv2d(192, 192, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), groups=192, bias=False)
            (1): GELU()
          )
          (proj_drop): Dropout(p=0.0, inplace=False)
          (softmax): Softmax(dim=-1)
        )
        (drop_path): DropPath()
        (mlp): Mlp(
          (dwconv): Conv2d(192, 192, kernel_size=(7, 7), stride=(1, 1), padding=(3, 3), groups=192)
          (norm): LayerNorm((192,), eps=1e-06, elementwise_affine=True)
          (pwconv1): Conv2d(192, 768, kernel_size=(1, 1), stride=(1, 1))
          (act): GELU()
          (pwconv2): Conv2d(768, 192, kernel_size=(1, 1), stride=(1, 1))
          (drop_path): Identity()
        )
      )
    )
    (upsample): PatchExpand(
      (up): Sequential(
        (0): ConvTranspose2d(192, 96, kernel_size=(2, 2), stride=(2, 2))
        (1): GELU()
      )
      (norm): LayerNorm((192,), eps=1e-05, elementwise_affine=True)
      (drop): Dropout(p=0.2, inplace=False)
    )
  )
  (3): BasicLayer_up(
    (blocks): ModuleList(
      (0): ConvSwinTransformerBlock(
        dim=96, input_resolution=(56, 56), num_heads=3, window_size=7, shift_size=0, mlp_ratio=4.0
        (norm1): LayerNorm((96,), eps=1e-05, elementwise_affine=True)
        (attn): WindowAttention(
          dim=96, window_size=(7, 7), num_heads=3
          (conv_proj_q): Sequential(
            (0): Conv2d(96, 96, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), groups=96, bias=False)
            (1): Rearrange('b c h w -> b (h w) c')
            (2): LayerNorm((96,), eps=1e-05, elementwise_affine=True)
          )
          (conv_proj_k): Sequential(
            (0): Conv2d(96, 96, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), groups=96, bias=False)
            (1): Rearrange('b c h w -> b (h w) c')
            (2): LayerNorm((96,), eps=1e-05, elementwise_affine=True)
          )
          (conv_proj_v): Sequential(
            (0): Conv2d(96, 96, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), groups=96, bias=False)
            (1): Rearrange('b c h w -> b (h w) c')
            (2): LayerNorm((96,), eps=1e-05, elementwise_affine=True)
          )
          (attn_drop): Dropout(p=0.0, inplace=False)
          (proj): Sequential(
            (0): Conv2d(96, 96, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), groups=96, bias=False)
            (1): GELU()
          )
          (proj_drop): Dropout(p=0.0, inplace=False)
          (softmax): Softmax(dim=-1)
        )
        (drop_path): Identity()
        (mlp): Mlp(
          (dwconv): Conv2d(96, 96, kernel_size=(7, 7), stride=(1, 1), padding=(3, 3), groups=96)
          (norm): LayerNorm((96,), eps=1e-06, elementwise_affine=True)
          (pwconv1): Conv2d(96, 384, kernel_size=(1, 1), stride=(1, 1))
          (act): GELU()
          (pwconv2): Conv2d(384, 96, kernel_size=(1, 1), stride=(1, 1))
          (drop_path): Identity()
        )
      )
      (1): ConvSwinTransformerBlock(
        dim=96, input_resolution=(56, 56), num_heads=3, window_size=7, shift_size=3, mlp_ratio=4.0
        (norm1): LayerNorm((96,), eps=1e-05, elementwise_affine=True)
        (attn): WindowAttention(
          dim=96, window_size=(7, 7), num_heads=3
          (conv_proj_q): Sequential(
            (0): Conv2d(96, 96, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), groups=96, bias=False)
            (1): Rearrange('b c h w -> b (h w) c')
            (2): LayerNorm((96,), eps=1e-05, elementwise_affine=True)
          )
          (conv_proj_k): Sequential(
            (0): Conv2d(96, 96, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), groups=96, bias=False)
            (1): Rearrange('b c h w -> b (h w) c')
            (2): LayerNorm((96,), eps=1e-05, elementwise_affine=True)
          )
          (conv_proj_v): Sequential(
            (0): Conv2d(96, 96, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), groups=96, bias=False)
            (1): Rearrange('b c h w -> b (h w) c')
            (2): LayerNorm((96,), eps=1e-05, elementwise_affine=True)
          )
          (attn_drop): Dropout(p=0.0, inplace=False)
          (proj): Sequential(
            (0): Conv2d(96, 96, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), groups=96, bias=False)
            (1): GELU()
          )
          (proj_drop): Dropout(p=0.0, inplace=False)
          (softmax): Softmax(dim=-1)
        )
        (drop_path): DropPath()
        (mlp): Mlp(
          (dwconv): Conv2d(96, 96, kernel_size=(7, 7), stride=(1, 1), padding=(3, 3), groups=96)
          (norm): LayerNorm((96,), eps=1e-06, elementwise_affine=True)
          (pwconv1): Conv2d(96, 384, kernel_size=(1, 1), stride=(1, 1))
          (act): GELU()
          (pwconv2): Conv2d(384, 96, kernel_size=(1, 1), stride=(1, 1))
          (drop_path): Identity()
        )
      )
    )
  )
)

2.3.1. class PatchExpand()

类PatchExpand
forward中的H, W = self.input_resolution开始看

class PatchExpand(nn.Module):
    def __init__(self, input_resolution, dim, dim_scale=2, norm_layer=nn.LayerNorm):
        super().__init__()
        self.input_resolution = input_resolution
        self.dim = dim
        self.up = nn.Sequential(nn.ConvTranspose2d(dim, dim // dim_scale, kernel_size=2, stride=2), nn.GELU())
        self.norm = norm_layer(dim)
        self.drop = nn.Dropout(p=0.2)
      

    def forward(self, x):
        """
        x: B, H*W, C → B, H*2*W*2, C/2
        """
        H, W = self.input_resolution   # H/32, W/32
        B, L, C = x.shape              # (B, H*W/1024, 8*C)
        assert L == H * W, "input feature has wrong size"

        x = x.view(B, H, W, C)         # (B, H/32, W/32, 8*C)
        x = self.norm(x)
        x = x.permute(0, 3, 1, 2)  # (B, H/32, W/32, 8*C) -> (B, 8*C, H/32, W/32)

        '''self.up:
         (1)转置卷积ConvTranspose2d(8*C, 4*C, kernel_size=(2,2), stride=(2,2))
         (2)GELU()
         '''
        x = self.up(x)     # (B, 8*C, H/32, W/32)->(B, 4*C, H/16, W/16)

        x = self.drop(x)   # (B, 4*C, H/16, W/16)

        # 代码里的C是x中的8*C
        x = x.permute(0, 2, 3, 1).contiguous().view(B, -1, C // 2)   # (B, H/16 * W/16, 4*C)
        return x      # (B, H/16 * W/16, 4*C)
        # 到这里执行结束,接下来跳转到2.3.(1)

2.3.(1)

函数forward_up_features
forward_up_featuresfor inx, layer_up in enumerate(self.layers_up):开始看

    def forward_up_features(self, x, x_downsample):
        '''
        layers_up共有4层,详细结构在这段代码的后面
        其中,
        PatchExpand:
        '''
        # inx=1的情况
        for inx, layer_up in enumerate(self.layers_up):
            if inx == 0:
                x = layer_up(x)   # (B, H*W/1024, 8*C)
                
            '''inx=1
           (1)x_downsample[0]: (B, H*W/16, C)
              x_downsample[1]: (B, H*W/64, 2*C)
              x_downsample[2]: (B, H*W/256, 4*C)
              x_downsample[3]: (B, H*W/1024, 8*C)
           (2)x:(B, H/16 * W/16, 4*C)
            '''    
            else: 
                x = torch.cat([x, x_downsample[3 - inx]], -1)  # (B, H/16 * W/16, 8*C)

                '''concat_back_dim的结构在该代码下面展示
                concat_back_dim[1]: (B, H/16 * W/16, 8*C)->(B, H/16 * W/16, 4*C)
                '''
                x = self.concat_back_dim[inx](x)

                # 跳转到2.3.2小节的class BasicLayer_up
                x = layer_up(x)

        x = self.norm_up(x)  # B L C
        return x

concat_back_dim结构:

ModuleList(
  (0): Sequential(
    (0): Rearrange('b (h w) c -> b c h w', h=7, w=7)
    (1): Conv2d(1536, 768, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (2): GELU()
    (3): Conv2d(768, 768, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (4): GELU()
    (5): Dropout(p=0.2, inplace=False)
    (6): Rearrange('b c h w -> b (h w) c', h=7, w=7)
  )
  (1): Sequential(
    (0): Rearrange('b (h w) c -> b c h w', h=14, w=14)
    (1): Conv2d(768, 384, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (2): GELU()
    (3): Conv2d(384, 384, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (4): GELU()
    (5): Dropout(p=0.2, inplace=False)
    (6): Rearrange('b c h w -> b (h w) c', h=14, w=14)
  )
  (2): Sequential(
    (0): Rearrange('b (h w) c -> b c h w', h=28, w=28)
    (1): Conv2d(384, 192, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (2): GELU()
    (3): Conv2d(192, 192, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (4): GELU()
    (5): Dropout(p=0.2, inplace=False)
    (6): Rearrange('b c h w -> b (h w) c', h=28, w=28)
  )
  (3): Sequential(
    (0): Rearrange('b (h w) c -> b c h w', h=56, w=56)
    (1): Conv2d(192, 96, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (2): GELU()
    (3): Conv2d(96, 96, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (4): GELU()
    (5): Dropout(p=0.2, inplace=False)
    (6): Rearrange('b c h w -> b (h w) c', h=56, w=56)
  )
)

2.3.2. class BasicLayer_up()

类BasicLayer_up:进入Decoder阶段
forward中的for blk in self.blocks:开始看

class BasicLayer_up(nn.Module):
    """ A basic Convolutional Swin Transformer layer for one stage.
    Args:
        dim (int): Number of input channels.
        input_resolution (tuple[int]): Input resolution.
        depth (int): Number of blocks.
        num_heads (int): Number of attention heads.
        window_size (int): Local window size.
        mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
        qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
        qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
        drop (float, optional): Dropout rate. Default: 0.0
        attn_drop (float, optional): Attention dropout rate. Default: 0.0
        drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
        norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
        downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
        use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
    """

    def __init__(self, dim, input_resolution, depth, num_heads, window_size,
                 mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0.,
                 drop_path=0., norm_layer=nn.LayerNorm, upsample=None, use_checkpoint=False):

        super().__init__()
        self.dim = dim
        self.input_resolution = input_resolution
        self.depth = depth
        self.use_checkpoint = use_checkpoint

        # build blocks
        self.blocks = nn.ModuleList([
            ConvSwinTransformerBlock(dim=dim, input_resolution=input_resolution,
                                 num_heads=num_heads, window_size=window_size,
                                 shift_size=0 if (i % 2 == 0) else window_size // 2,
                                 mlp_ratio=mlp_ratio,
                                 qkv_bias=qkv_bias, qk_scale=qk_scale,
                                 drop=drop, attn_drop=attn_drop,
                                 drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,
                                 norm_layer=norm_layer)
            for i in range(depth)])

        # patch merging layer
        if upsample is not None:
            self.upsample = PatchExpand(input_resolution, dim=dim, dim_scale=2, norm_layer=norm_layer)
        else:
            self.upsample = None

    def forward(self, x):   #(B, H/16 * W/16, 4*C)
        for blk in self.blocks:
            if self.use_checkpoint:
                x = checkpoint.checkpoint(blk, x)
            
            '''blk:class ConvSwinTransformerBlock,即CST×2
            这里是解码器阶段的CST,后面跟着一个上采样
            '''    
            else:
                x = blk(x)            # (B, H/16 * W/16, 4*C)

        # upsample = PatchExpand, 跳转到2.3.2.1小节
        if self.upsample is not None:
            x = self.upsample(x)
        return x
2.3.2.1. class PatchExpand()

类PatchExpand:作为解码器的上采样
forward中的H, W = self.input_resolution开始

class PatchExpand(nn.Module):
    def __init__(self, input_resolution, dim, dim_scale=2, norm_layer=nn.LayerNorm):
        super().__init__()
        self.input_resolution = input_resolution
        self.dim = dim
        self.up = nn.Sequential(nn.ConvTranspose2d(dim, dim // dim_scale, kernel_size=2, stride=2), nn.GELU())
        self.norm = norm_layer(dim)
        self.drop = nn.Dropout(p=0.2)
      

    def forward(self, x):
        """这里的H、W不是图像的原尺寸
        x: B, H*W, C → B, H*2*W*2, C/2
        """
        H, W = self.input_resolution   # H/16, W/16
        B, L, C = x.shape              # B, H/16 * W/16, 4C   # C是原C
        assert L == H * W, "input feature has wrong size"

        x = x.view(B, H, W, C)   # (B, H/16, W/16, 4*C)
        x = self.norm(x)
        x = x.permute(0, 3, 1, 2)  # (B, 4*C, H/16, W/16)

        # 实现上采样
        x = self.up(x)     # (B, 2*C, H/8, W/8)=(16,192,28,28)
        x = self.drop(x)
        x = x.permute(0, 2, 3, 1).contiguous().view(B, -1, C // 2) # (B, H/8 * W/8, 2C)=(16,28*28,192)
        return x   # (B, H/8 * W/8, 2C)
        # 到这里,类BasicLayer_up中的self.upsample执行结束,接下来跳转到2.3.2.(1)节,即回到类BasicLayer_up中

2.3.2.(1)

类BasicLayer_upDecoder阶段
forward中的return x开始看,即BasicLayer_up也执行结束了

    def forward(self, x):   #(B, H/16 * W/16, 4*C)
        for blk in self.blocks:
            if self.use_checkpoint:
                x = checkpoint.checkpoint(blk, x)
            
            '''blk:class ConvSwinTransformerBlock,即CST×2
            这里是解码器阶段的CST,后面跟着一个上采样
            '''    
            else:
                x = blk(x)            # (B, H/16 * W/16, 4*C)

        # upsample = PatchExpand, 跳转到2.3.2.1小节
        if self.upsample is not None:
            x = self.upsample(x)
        return x    # (B, H/8 * W/8, 2C)
        # 执行结束,接下来跳转到2.3.(2)小节

2.3.(2)

函数forward_up_features
forward_up_featuresfor inx, layer_up in enumerate(self.layers_up):开始看,到这inx=2

    def forward_up_features(self, x, x_downsample):
        '''
        layers_up共有4层,详细结构在这段代码的后面
        其中,
        PatchExpand:
        '''
        # inx=1的情况
        for inx, layer_up in enumerate(self.layers_up):
            if inx == 0:
                x = layer_up(x)   # (B, H/32 * W/32, 8*C)
                
            '''inx=2
           (1)x_downsample[0]: (B, H*W/16, C)
              x_downsample[1]: (B, H*W/64, 2*C)
              x_downsample[2]: (B, H*W/256, 4*C)
              x_downsample[3]: (B, H*W/1024, 8*C)
           (2)x:(B, H/16 * W/16, 2*C)
            '''    
            else:   # 下面注释中的三个张量shape分别对应inx=1,inx=2,inx=3
                x = torch.cat([x, x_downsample[3 - inx]], -1)  # (B, H/16 * W/16, 8C); (B, H/8 * W/8, 4C);(B, H/4 * W/4, 2C)

                '''concat_back_dim的结构在该代码下面展示
                concat_back_dim[1]: (B, H/16 * W/16, 8*C)->(B, H/16 * W/16, 4*C)
                concat_back_dim[2]: (B, H/8 * W/8, 4*C)->(B, H/8 * W/8, 2*C)
                concat_back_dim[3]: (B, H/4 * W/4, 2*C)->(B, H/4 * W/4, C)
                '''
                x = self.concat_back_dim[inx](x)  # (B, H/8 * W/8, 4*C)->(B, H/8 * W/8, 2*C)

                # 跳转到class BasicLayer_up,再次进行CST×2,操作与上个阶段相同
                x = layer_up(x)       # inx=3后的结果: (B, H/4 * W/4, C),跳出循环

        # (B, H/4 * W/4, C)
        x = self.norm_up(x)  # B L C: (B, H/4 * W/4, C)
        return x
        # 到这里forward_up_features执行结束,接下来跳转到2.4小节

2.4. class ConvSwinTransformerSys()

类ConvSwinTransformerSys()与2.1小节相同,在这里只展示要用到的代码段
forwardx = self.up_x4(x)开始看

    def forward(self, x):
        x, x_downsample = self.forward_features(x)   # (B,3,H,W)

        '''
        (1)x_downsample[0]: (B, H*W/16, C)
           x_downsample[1]: (B, H*W/64, 2*C)
           x_downsample[2]: (B, H*W/256, 4*C)
           x_downsample[3]: (B, H*W/1024, 8*C)
        (2)x:(B, H*W/1024, 8*C)
        '''# 跳转到forward_up_features,见下面代码
        x = self.forward_up_features(x, x_downsample) 

        # 函数up_x4,接下来跳转到2.4.1小节
        x = self.up_x4(x)  # (B, H/4 * W/4, C)
        return x

2.4.1. def up_x4()

函数up_x4

    def up_x4(self, x):   # (B, H/4 * W/4, C)
        H, W = self.patches_resolution  # H/4 * W/4
        B, L, C = x.shape               # B, H/4 * W/4, C
        assert L == H * W, "input features has wrong size"

        if self.final_upsample == "expand_first": # True

            # up=FinalPatchExpand_X4,接下来跳转到2.4.1.1小节
            x = self.up(x)
            x = x.view(B, 4 * H, 4 * W, -1)
            x = x.permute(0, 3, 1, 2)  # B,C,H,W
            x = self.output(x)

        return x
2.4.1.1. class FinalPatchExpand_X4()

类FinalPatchExpand_X4

class FinalPatchExpand_X4(nn.Module):
    def __init__(self, input_resolution, dim, dim_scale=4, norm_layer=nn.LayerNorm):
        super().__init__()
        self.input_resolution = input_resolution
        self.dim = dim
        self.dim_scale = dim_scale
        self.expand = nn.Linear(dim, 16 * dim, bias=False)
        self.output_dim = dim
        self.norm = norm_layer(self.output_dim)

    def forward(self, x):   # (B, H/4 * W/4, C):(16,3136,96)
        """
        x: B, H*W, C → B, H*4*W*4, C
        """
        H, W = self.input_resolution  # H/4 , W/4
        x = self.expand(x)            # (B, H/4 * W/4, C)->(B, H/4 * W/4, 16*C)
        B, L, C = x.shape             # B, H/4 * W/4, 16C
        assert L == H * W, "input feature has wrong size"

        x = x.view(B, H, W, C)        # (B, H/4, W/4, 16C)

        '''rearrange:
        p1=4; p2=4; c=96:即原C
        b h w (p1 p2 c): B H/4 W/4 16C
        b (h p1) (w p2) c: B H W C
        '''
        x = rearrange(x, 'b h w (p1 p2 c)-> b (h p1) (w p2) c', p1=self.dim_scale, p2=self.dim_scale,
                      c=C // (self.dim_scale ** 2))     # (B,H,W,C):(B,224,224,96)
        x = x.view(B, -1, self.output_dim)              # (B,H*W,C):(B,224*224,96)
        x = self.norm(x)

        return x    # (B,H*W,C)
        # 到这里FinalPatchExpand_X4执行结束,接下来跳转到2.4.1.(1)小节 def up_x4()

2.4.1.(1)

函数up_x4
x = x.view(B, 4 * H, 4 * W, -1)开始看

    def up_x4(self, x):   # (B, H/4 * W/4, C)
        H, W = self.patches_resolution  # H/4 * W/4
        B, L, C = x.shape               # B, H/4 * W/4, C
        assert L == H * W, "input features has wrong size"

        if self.final_upsample == "expand_first": # True

            # up=FinalPatchExpand_X4,接下来跳转到2.4.1.1小节
            x = self.up(x)                    # (B, H/4 * W/4, C)->(B,H*W,C)

            # 这里的H和W是原尺寸的1/4
            x = x.view(B, 4 * H, 4 * W, -1)   # (B,H,W,C)
            x = x.permute(0, 3, 1, 2)  # (B,C,H,W)
            x = self.output(x)

        return x     # (B,C,H,W)
        # 到这里up_×4结束,然后跳转到class ConvSwinTransformerSys中forward结束部分,如下代码

class ConvSwinTransformerSys结束:
return x开始,即已经执行结束了

    def forward(self, x):
        x, x_downsample = self.forward_features(x)   # (B,3,H,W)
        x = self.forward_up_features(x, x_downsample)
        x = self.up_x4(x)     #  (B, H/4 * W/4, C)->(B,C,H,W)

        return x  # (B,C,H,W)
        # 类class ConvSwinTransformerSys执行结束,接下来跳转到2.1小节

2.(1) class CS_Unet()

类CS_Unet
forward中的return logits开始,即执行结束


    def forward(self, x):
        # 判断图片的channel是否为1, 如果为1就在通道方向上复制3次,使其变成三通道的图片。
        if x.size()[1] == 1: 
            x = x.repeat(1,3,1,1)   # (B,3,H,W)

        # 进入 类ConvSwinTransformerSys,转到2.1小节
        logits = self.CS_Unet(x)     # (B,C,H,W)
        return logits  # (B,C,H,W)
        # 终于,整个model流程完成

最后跳出outputs = model(image_batch)语句!
到这里,model实现完成!!!!

附录. 模型框架图

【代码复现】(Swin-Transformer)CS-UNet模型解读_第1张图片

你可能感兴趣的:(模型代码解读,transformer,python,人工智能)