CSWin Transformer:A General Vision Transformer Backbone with Cross-Shaped Windows

论文地址:https://arxiv.org/abs/2107.00652https://arxiv.org/abs/2107.00652代码地址: GitHub - microsoft/CSWin-Transformer: CSWin Transformer: A General Vision Transformer Backbone with Cross-Shapedhttps://github.com/microsoft/CSWin-Transformer

CSWin Transformer:A General Vision Transformer Backbone with Cross-Shaped Windows_第1张图片

 Abstract

本文提出了CSWin Transformer,一个用于通用计算机视觉的高效有效的Transformer-based backbone。Transformer 的一个具有挑战性的问题是,全局自注意(global attention)的计算代价非常昂贵,而局部自注意(local attention)往往限制了每个token感受野的交互,减缓感受野的增长。为了解决这个问题,提出了Cross-Shaped Window self-attention机制,可以并行计算水平(horizontal)和竖直(vertical)方向的self-attention,可以在更小的计算量条件下获得更好的效果。作者对Transformer网络不同层的条状(stripe)宽度的影响进行了详细的数学分析,在限制了计算成本的同时实现了较强的建模能力。还引入了(LePE)Locally-enhanced Positional Encoding局部增强的位置编码,它比现有的编码方案更能更好地处理局部信息。LePE自然的支持任意的输入分辨率,因此对于下游任务特别有效和友好。结合这些设计和层次结构,CSWin Transformer在公共视觉任务上展示了具有竞争力的性能。

CSWin Transformer:A General Vision Transformer Backbone with Cross-Shaped Windows_第2张图片


模型结构

CSWin Transformer:A General Vision Transformer Backbone with Cross-Shaped Windows_第3张图片

CSWin Transformer和Swin Transformer【参考:Swin Transformer (ICCV 2021 best paper)_乐亦亦乐的博客-CSDN博客】一样采用金字塔结构,共包括4个stage,各个stage的特征图大小分别是原图的1/4,1/8,1/16和1/32。CSWin Transformer主要有三个重要的改进:Overlapping Patch EmbeddingCross-Shaped Window Self-AttentionLocally-Enhanced Positional Encoding

模块细节

Convolutional Token Embeeding

用convolution来做embeeding,为了减少计算量,本文直接采用了7x7的卷积核,stride为4的卷积来直接对输入进行embeeding,假设输入为H \times W \times 3,那么输出为\frac{H}{4} \times \frac{W}{4} \times C

# patch embedding
stage1_conv_embed = nn.Sequential(
    nn.Conv2d(in_chans, embed_dim, 7, 4, 2),
    Rearrange('b c h w -> b (h w) c', h = img_size//4, w = img_size//4),
    nn.LayerNorm(embed_dim)
)

为了产生层级表示,整个网络由4个阶段组成。各个stage间的patch merging采用stride为2的3x3卷积来减少tokens 的数量,并扩大通道数为2倍。因此构建的特征图在第i阶段有\frac{H}{2^{i+1}} \times \frac{W}{2^{i+1}}个tokens,类似于传统的CNN backbone。每个阶段由N i 个顺序的CSWin Transformer Blocks 组成。

CSWin Transformer 的整体拓扑结构与普通的multi-head self-attention Transformer 结构相似,但有两个区别:

  1. 使用提出的Cross-Shaped Window  Self-attention 代替 注意力机制
  2. Locally-enchanced Positional Encoding

Cross-Shaped Window Self-Attention

尽管有很强的长距离上下文建模能力,但原始的global self-attention的计算复杂度与特征图大小平方(H==W的情况)成正比的。因此,对于以高分辨率特征图为输入的视觉任务,如物体检测和分割,计算成本会非常大。为了缓解这个问题,现有的工作Swin等建议使用local windows self-attention,通过shift窗口来扩大感受野。然而,每个Transformer块内的token依旧是有限的注意区域,需要堆叠更多的block来实现全局感受野。为了更有效地扩大注意力区域和实现全局性的自我注意,有了Cross-shaped Window Self-attention。

如下所示,首先将self-attention的mutil-heads均分成两组,一组做horizontal stripes self-attention,另外一组做vertical stripes self-attention。

CSWin Transformer:A General Vision Transformer Backbone with Cross-Shaped Windows_第4张图片

horizontal stripes self-attention就是沿着H维度将tokens分成水平条状windows,对于输入为HxW的tokens,记每个水平条状window的宽度为sw,那么共产生 H/sw 个windows,每个window共包含sw X W个tokens;而vertical stripes self-attention就是沿着W维度将tokens分成竖直条状windows,同样地会产生W/sw 个windows,每个window的tokens量为sw X H。具体的划分窗口代码和Swin transformer一样,通过设定window的宽度和长度来实现两组attention.

# 对于水平attention,H_sp=sw, W_sp=W
# 对于竖直attention,H_sp=H, W_sp=sw
def img2windows(img, H_sp, W_sp):
    """
    img: B C H W
    """
    B, C, H, W = img.shape
    img_reshape = img.view(B, C, H // H_sp, H_sp, W // W_sp, W_sp)
    img_perm = img_reshape.permute(0, 2, 4, 3, 5, 1).contiguous().reshape(-1, H_sp* W_sp, C)
    return img_perm

def windows2img(img_splits_hw, H_sp, W_sp, H, W):
    """
    img_splits_hw: B' H W C
    """
    B = int(img_splits_hw.shape[0] / (H * W / H_sp / W_sp))

    img = img_splits_hw.view(B, H // H_sp, W // W_sp, H_sp, W_sp, -1)
    img = img.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)
    return img

两组self-attention是并行的,完成后将tokens的特征concat在一起,这样就构成了CSW self-attention,最终效果就是在十字形窗口内做attention,CSW self-attention的感受野要比常规的window attention的感受野更大。

CSWin Transformer:A General Vision Transformer Backbone with Cross-Shaped Windows_第5张图片

 CSWin Transformer:A General Vision Transformer Backbone with Cross-Shaped Windows_第6张图片

CSWin Attention 计算复杂度:

CSWin Transformer:A General Vision Transformer Backbone with Cross-Shaped Windows_第7张图片

其中,窗口大小为(sw,H), 相比于标准的self-attention,区别在于H,或者W是部分的而不是全部的,如下图所示。 

标准self-attention:

CSWin Transformer:A General Vision Transformer Backbone with Cross-Shaped Windows_第8张图片

 (行or列)self-attention

CSWin Transformer:A General Vision Transformer Backbone with Cross-Shaped Windows_第9张图片

代码实现:

class CSWinBlock(nn.Module):

    def __init__(self, dim, reso, num_heads,
                 split_size=7, mlp_ratio=4., qkv_bias=False, qk_scale=None,
                 drop=0., attn_drop=0., drop_path=0.,
                 act_layer=nn.GELU, norm_layer=nn.LayerNorm,
                 last_stage=False):
        super().__init__()
        self.dim = dim
        self.num_heads = num_heads
        self.patches_resolution = reso
        self.split_size = split_size # sw
        self.mlp_ratio = mlp_ratio
        self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
        self.norm1 = norm_layer(dim)
  
        # 最后一个阶段,实际上执行的是global attention
        if self.patches_resolution == split_size:
            last_stage = True
        if last_stage:
            self.branch_num = 1 # 只有一个分支
        else:
            self.branch_num = 2 # 两个分支,分别执行两组attention
        self.proj = nn.Linear(dim, dim)
        self.proj_drop = nn.Dropout(drop)
        # 最后一个阶段,就只有一个window,不需要再分成两组
        if last_stage:
            self.attns = nn.ModuleList([
                LePEAttention(
                    dim, resolution=self.patches_resolution, idx = -1,
                    split_size=split_size, num_heads=num_heads, dim_out=dim,
                    qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
                for i in range(self.branch_num)])
        else:
            self.attns = nn.ModuleList([
                LePEAttention(
                    dim//2, resolution=self.patches_resolution, idx = i,
                    split_size=split_size, num_heads=num_heads//2, dim_out=dim//2,
                    qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
                for i in range(self.branch_num)]) # idx区分两组attention
        

        mlp_hidden_dim = int(dim * mlp_ratio)

        self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
        self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, out_features=dim, act_layer=act_layer, drop=drop)
        self.norm2 = norm_layer(dim)

    def forward(self, x):
        """
        x: B, H*W, C
        """

        H = W = self.patches_resolution
        B, L, C = x.shape
        assert L == H * W, "flatten img_tokens has wrong size"
        img = self.norm1(x)
        qkv = self.qkv(img).reshape(B, -1, 3, C).permute(2, 0, 1, 3)
        if self.branch_num == 2:
            x1 = self.attns[0](qkv[:,:,:,:C//2]) # 一半heads执行水平attention
            x2 = self.attns[1](qkv[:,:,:,C//2:]) # 另外一半heads执行竖直attention
            attened_x = torch.cat([x1,x2], dim=2) # concat在一起
        else:
            attened_x = self.attns[0](qkv)
        attened_x = self.proj(attened_x)
        x = x + self.drop_path(attened_x)
        x = x + self.drop_path(self.mlp(self.norm2(x)))

        return x

 Locally-Enhanced Positional Encoding(LePE)

CSWin Transformer:A General Vision Transformer Backbone with Cross-Shaped Windows_第10张图片

 上图所示,左边为VIT模型的PE,使用的绝对位置编码或者是条件位置编码,只在embeeding的时候与token一起进入transformer,中间的是Swin,CrossFormer等模型的PE,使用相对位置编码偏差,不再和输入的embeeding一起进入transformer,通过引入token图的权重,来和attention一起计算,灵活度更好相对APE效果更好。最后就是本文所提出的LePE,相比于RPE,本文的方法更加直接,直接作用在value上,公式如下:

 考虑到的计算量较大,这里用一个depth-wise convolution(3x3卷积)来替换,这其实就主要考虑局部位置信息了,论文称这种位置编码为locally-enhanced positional encoding (LePE):

CSWin Transformer:A General Vision Transformer Backbone with Cross-Shaped Windows_第11张图片

 代码实现:

class LePEAttention(nn.Module):
    def __init__(self, dim, resolution, idx, split_size=7, dim_out=None, num_heads=8, attn_drop=0., proj_drop=0., qk_scale=None):
        super().__init__()
        self.dim = dim
        self.dim_out = dim_out or dim
        self.resolution = resolution
        self.split_size = split_size
        self.num_heads = num_heads
        head_dim = dim // num_heads
        # NOTE scale factor was wrong in my original version, can set manually to be compat with prev weights
        self.scale = qk_scale or head_dim ** -0.5
        # 最后一个stage
        if idx == -1:
            H_sp, W_sp = self.resolution, self.resolution
        elif idx == 0: # 水平attention
            H_sp, W_sp = self.resolution, self.split_size
        elif idx == 1: # 竖直attention
            W_sp, H_sp = self.resolution, self.split_size
        else:
            print ("ERROR MODE", idx)
            exit(0)
        self.H_sp = H_sp
        self.W_sp = W_sp
       
        # LePE
        self.get_v = nn.Conv2d(dim, dim, kernel_size=3, stride=1, padding=1,groups=dim)

        self.attn_drop = nn.Dropout(attn_drop)

    def im2cswin(self, x):
        B, N, C = x.shape
        H = W = int(np.sqrt(N))
        x = x.transpose(-2,-1).contiguous().view(B, C, H, W)
        x = img2windows(x, self.H_sp, self.W_sp)
        x = x.reshape(-1, self.H_sp* self.W_sp, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3).contiguous()
        return x

    def get_lepe(self, x, func):
        B, N, C = x.shape
        H = W = int(np.sqrt(N))
        x = x.transpose(-2,-1).contiguous().view(B, C, H, W)

        H_sp, W_sp = self.H_sp, self.W_sp
        x = x.view(B, C, H // H_sp, H_sp, W // W_sp, W_sp)
        x = x.permute(0, 2, 4, 1, 3, 5).contiguous().reshape(-1, C, H_sp, W_sp) ### B', C, H', W'

        lepe = func(x) ### B', C, H', W'
        lepe = lepe.reshape(-1, self.num_heads, C // self.num_heads, H_sp * W_sp).permute(0, 1, 3, 2).contiguous()

        x = x.reshape(-1, self.num_heads, C // self.num_heads, self.H_sp* self.W_sp).permute(0, 1, 3, 2).contiguous()
        return x, lepe

    def forward(self, qkv):
        """
        x: B L C
        """
        q,k,v = qkv[0], qkv[1], qkv[2]

        ### Img2Window
        H = W = self.resolution
        B, L, C = q.shape
        assert L == H * W, "flatten img_tokens has wrong size"
        
        q = self.im2cswin(q)
        k = self.im2cswin(k)
        v, lepe = self.get_lepe(v, self.get_v)

        q = q * self.scale
        attn = (q @ k.transpose(-2, -1))  # B head N C @ B head C N --> B head N N
        attn = nn.functional.softmax(attn, dim=-1, dtype=attn.dtype)
        attn = self.attn_drop(attn)

        x = (attn @ v) + lepe
        x = x.transpose(1, 2).reshape(-1, self.H_sp* self.W_sp, C)  # B head N N @ B head N C

        ### Window2Img
        x = windows2img(x, self.H_sp, self.W_sp, H, W).view(B, -1, C)  # B H' W' C

        return x

CSWin Transformer Block

CSWin Transformer:A General Vision Transformer Backbone with Cross-Shaped Windows_第12张图片

CSWin Transformer:A General Vision Transformer Backbone with Cross-Shaped Windows_第13张图片

不同变体的详细结构:

CSWin Transformer:A General Vision Transformer Backbone with Cross-Shaped Windows_第14张图片

CSWin Transformer:A General Vision Transformer Backbone with Cross-Shaped Windows_第15张图片

 实验

CSWin Transformer:A General Vision Transformer Backbone with Cross-Shaped Windows_第16张图片

CSWin Transformer:A General Vision Transformer Backbone with Cross-Shaped Windows_第17张图片 CSWin Transformer:A General Vision Transformer Backbone with Cross-Shaped Windows_第18张图片

 CSWin Transformer:A General Vision Transformer Backbone with Cross-Shaped Windows_第19张图片

CSWin Transformer:A General Vision Transformer Backbone with Cross-Shaped Windows_第20张图片

 CSWin Transformer:A General Vision Transformer Backbone with Cross-Shaped Windows_第21张图片

 CSWin Transformer:A General Vision Transformer Backbone with Cross-Shaped Windows_第22张图片

参考:

CSWin Transfomer:超越Swin Transformer的网络来了究竟谁更强?https://mp.weixin.qq.com/s/0m7a4EC-vfBGd61fva3ujg

浅谈CSwin-Transformers提出了局部增强位置编码模块https://mp.weixin.qq.com/s/Vl4ICUTaeahqPblPDKy0jQ 

你可能感兴趣的:(论文阅读,transformer,深度学习)