引言:
Transformer 模型在自然语言处理(NLP)领域已然成为一个新范式,如今越来越多的研究在尝试将 Transformer 模型强大的建模能力应用到计算机视觉(CV)领域。那么未来,Transformer会不会代替CNN在CV领域的作用。
而swin transformer是一种包含了CNN滑窗理念的一种transformer。将注意力限制在一个窗口中,一方面能引入CNN卷积操作的局部性,另一方面能节省计算量。
整体架构
我们先看下swin transformer的整体架构:
整个模型采取层次化的设计,一共包含4个Stage,每个stage都会缩小输入特征图的分辨率,像CNN一样逐层扩大感受野。
通过Patch Partition和Linear Emdedding将将图片切成一个个图块,并嵌入到Embedding。
每个Stage中包含Patch Merging和多个Swin Transformer Block。
其中Swin Transformer Block主要由LayerNorm,MLP,Window Attention和Shifted Window Attention等组成。
接下来我将详细的介绍每一个模块。
Patch Partition 和 Linear Emdedding
在输入到Block前,我们需要将图片切成一个个patch,然后再嵌入向量。具体做法是对原始图片裁成一个个patch_size*patch_size的窗口大小,然后进行嵌入。
'''
通过patch partition将输入图片HxWx3划分为不重合的patch集合,
其中每个patch尺寸为4x4,那么每个patch的特征维度为4x4x3=48,patch块的数量为H/4 x W/4;
Linear Embedding 将输入的hw展开并且移动到第一维度
'''
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) # -> (img_size, img_size),(224,224)
patch_size = to_2tuple(patch_size) # -> (patch_size, patch_size),(4,4)
patches_resolution = [img_size[0] // patch_size[0], img_size[1] // patch_size[1]] #每一个方向有多少patch[56,56]
self.img_size = img_size
self.patch_size = patch_size
self.patches_resolution = patches_resolution
self.num_patches = patches_resolution[0] * patches_resolution[1] #一共有多少patch,56*56
self.in_chans = in_chans
self.embed_dim = embed_dim
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
if norm_layer is not None:
self.norm = norm_layer(embed_dim)
else:
self.norm = None
def forward(self, x):
# 假设采取默认参数
B, C, H, W = x.shape
# FIXME look at relaxing size constraints
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]})."
x = self.proj(x).flatten(2).transpose(1, 2) # B Ph*Pw C //出来的是(B, 96, 224/4, 224/4) 把HW维展开,(B, 96, 56*56) # 把通道维放到最后 (B, 56*56, 96)
if self.norm is not None:
x = self.norm(x)
return x
Patch Merging
该模块的作用是在每个Stage开始前做降采样,用于缩小分辨率,调整通道数 进而形成层次化的设计,同时也能节省一定运算量。(在stage1,stage2,stage3的前面使用。stage0使用了Patch Partition 和 Linear Emdedding)。
每次降采样是两倍,因此在行方向和列方向上,间隔2选取元素。然后拼接在一起作为一整个张量,最后展开。此时通道数是原先的4倍,但通过全连接层调整,使得通道数变为原来的2倍。
#该模块的作用是在每个Stage开始前做降采样,用于缩小分辨率,调整通道数 进而形成层次化的设计,同时也能节省一定运算量。
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):
"""
x: B, H*W, C
"""
H, W = self.input_resolution #56,56
B, L, C = x.shape #B,56*56,96
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) #B,56,56,96
x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C 取了2*2范围内的左上角数组成一个新矩阵 #B,28,28,96
x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C 取了2*2范围内的左下角数组成一个新矩阵 #B,28,28,96
x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C 取了2*2范围内的右上角数组成一个新矩阵 #B,28,28,96
x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C 取了2*2范围内的右下角数组成一个新矩阵 #B,28,28,96
x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C 矩阵在c维度叠加 #B,28,28,96*4
x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C 将H,W维度展平 #B,28*28,96*4
x = self.norm(x)
x = self.reduction(x) #将4C通过Linear变成2C #B,28*28,96*2
return x
下面是一个简单的示意图:
Window Partition
Window Partition函数是用于对张量划分窗口,指定窗口大小。将原本的[B,H,W,C],划分为[num_windows*B,window_size,window_size,C],其中num_windows=(H/window_size)*(W/window_size),即H,W大小图像可以划分出多少个window_size窗口。
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
简单示意图H,W=6,window_size=3:
Window Reverse
Window Reverse则是Window Partition的逆过程。这两个都将在Swin Transformer Block使用。
def window_reverse(windows, window_size, H, W):#将展开的窗口重新组装成图像
"""
Args:
windows: (num_windows*B, window_size, window_size, C) [64B,7,7,96]
window_size (int): Window size 7
H (int): Height of image 56
W (int): Width of image 56
Returns:
x: (B, H, W, C)
"""
B = int(windows.shape[0] / (H * W / window_size / window_size)) #num_windows = (H//window_size)*(W//window_size) B = windows.shape[0]/num_windows
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
简单示意图:
W-MSA
这是该文章的关键,之前使用的Transformer都是基于全局来计算注意力机制的。因此计算复杂度十分高。而Swin Transformer则将注意力的计算限制在每个窗口内,不仅减少了计算量。而且更加符合图像信息的性质。因为图像的该点像素也几乎只与附近的领域像素有关,并且此处还用到了相对位置编码。
先讲一下相对位置编码:
# define a parameter table of relative position bias
self.relative_position_bias_table = nn.Parameter(
torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)) # 设置一个形状为(2*(Wh-1) * 2*(Ww-1), nH)的可学习变量,用于后续的位置编码
# get pair-wise relative position index for each token inside the window
coords_h = torch.arange(self.window_size[0])
coords_w = torch.arange(self.window_size[1])
coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0 #为了让数值都为正
relative_coords[:, :, 1] += self.window_size[1] - 1 #为了让数值都为正
relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1 #在x方向再*(2*window_size-1)是为了后续求和后能够区分(1,2)和(2,1)这类坐标
relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
self.register_buffer("relative_position_index", relative_position_index) #反向传播不需要被optimizer更新的参数
简单示意图:
然后在w和h方向计算relative_coords。计算relative_coords第一步加(window_size-1)是为了让值都为正数,在w方向再*(2*window_size-1)是为了后续求和能区分(0,1)和(1,0)这类坐标。
接着我们附上windowsAtention代码,其中mak是为后面的shift windowsAttention准备的,此处可以忽略。
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 #其实是指q,k的维度
self.scale = qk_scale or head_dim ** -0.5 #对应Attention公式里面的分母
# define a parameter table of relative position bias
self.relative_position_bias_table = nn.Parameter(
torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)) # 设置一个形状为(2*(Wh-1) * 2*(Ww-1), nH)的可学习变量,用于后续的位置编码
# get pair-wise relative position index for each token inside the window
coords_h = torch.arange(self.window_size[0])
coords_w = torch.arange(self.window_size[1])
coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0 #为了让数值都为正
relative_coords[:, :, 1] += self.window_size[1] - 1 #为了让数值都为正
relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1 #在x方向再*(2*window_size-1)是为了后续求和后能够区分(1,2)和(2,1)这类坐标
relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
self.register_buffer("relative_position_index", relative_position_index) #反向传播不需要被optimizer更新的参数
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
self.attn_drop = nn.Dropout(attn_drop)
self.proj = nn.Linear(dim, dim)
self.proj_drop = nn.Dropout(proj_drop)
trunc_normal_(self.relative_position_bias_table, std=.02)
self.softmax = nn.Softmax(dim=-1)
def forward(self, x, mask=None): #mask只有在shift的时候才会用到
"""
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
"""
B_, N, C = x.shape
# [num_windows*B, Wh*Ww, C]--[num_windows*B, Wh*Ww, 3C]--[num_windows*B, Wh*Ww,3, num_heads, C // num_heads]--[3,num_windows*B,num_heads,Wh*Ww,C // num_heads]
qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)q = [num_windows*B,num_heads,Wh*Ww,C // num_heads][64B,3,49,32]
q = q * self.scale
attn = (q @ k.transpose(-2, -1)) #[num_windows*B,num_heads,N,N][64B,3,49,49]
relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(
self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1) # Wh*Ww,Wh*Ww,nH
relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
attn = attn + relative_position_bias.unsqueeze(0) #[num_windows*B,num_heads,N,N]
if mask is not None:
nW = mask.shape[0] #[64,49,49]
attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0) #[B,num_windows,num_heads,N,N]+[1,num_windows,1,N,N] = [B,num_windows,num_heads,N,N]
attn = attn.view(-1, self.num_heads, N, N) #[num_windows*B,num_heads,N,N] 这样就在对应的mask不应该计算的位置全部加了-100
attn = self.softmax(attn) #经过softmax之后就会被相应的忽略掉 [64B,3,49,49]
else:
attn = self.softmax(attn)
attn = self.attn_drop(attn)
x = (attn @ v).transpose(1, 2).reshape(B_, N, C) #[num_windows*B,num_heads,N,C // num_heads]--[num_windows*B,N,num_heads,C // num_heads]--[num_windows*B,N,C][64B,49,96]
x = self.proj(x)
x = self.proj_drop(x) #[num_windows*B,N,C]
return x
1.首先输入特征为[num_windows*B,window_size*window_size,C]
2.然后经过self.qkv将维度增加3倍,进行reshape,调整轴顺序,最终分配给q,k,v。(变化过程[num_windows*B, Wh*Ww, C]--[num_windows*B, Wh*Ww, 3C]--[num_windows*B, Wh*Ww,3, num_heads, C // num_heads]--[3,num_windows*B,num_heads,Wh*Ww,C // num_heads])。
3.根据公式,我们对q乘以一个scale系数,然后与k进行相乘。得到[num_windows*B,num_heads,window_size*window_size,window_size*window_size]的张量。再将相对位置编码加到attn上。
4.接着与普通的transformer一样的softmax,dropout,与v相乘,再经过一层全连接层和dropout。
SW-MSA
前面的Window Attention是在每个窗口下计算注意力的,为了更好的和其他window进行信息交互,Swin Transformer还引入了shifted window操作。
左边是没有重叠的Window Attention,而右边则是将窗口进行移位的Shift Window Attention。可以看到移位后的窗口包含了原本相邻窗口的元素。
在实际代码里,我们是通过对特征图移位,并给Attention设置mask来间接实现的。能在保持原有的window个数下,最后的计算结果等价。
特征图移位:
代码中特征移位是通过torch.roll来实现的
# cyclic shift
if self.shift_size > 0:
shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2)) #roll操作#B,56,56,96
else:
shifted_x = x #B,56,56,96
简单示意图如下所示:
Attention Mask
通过设置合理的mask,让注意力机制任然只计算原图中领域。
由于窗口重新划分,但是为了不考虑滑动过去的,不是领域的数据对结果产生影响,因此出现了mask。从而不计算那些不相关的数据。
if self.shift_size > 0:
# calculate attention mask for SW-MSA
H, W = self.input_resolution #第一次56,56
img_mask = torch.zeros((1, H, W, 1)) # 1 H W 1 [1,56,56,1]
h_slices = (slice(0, -self.window_size),
slice(-self.window_size, -self.shift_size),
slice(-self.shift_size, None)) #([0:-7],[-7:-3],[-3:0])
w_slices = (slice(0, -self.window_size),
slice(-self.window_size, -self.shift_size),
slice(-self.shift_size, None)) #([0:-7],[-7:-3],[-3:0])
cnt = 0
for h in h_slices:
for w in w_slices:
img_mask[:, h, w, :] = cnt
cnt += 1 #将区域一块块的分好[1,56,56,1]
mask_windows = window_partition(img_mask, self.window_size) # nW, window_size, window_size, 1 [64,7,7,1]
mask_windows = mask_windows.view(-1, self.window_size * self.window_size) # nW, window_size*window_size [64,49]
attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2) #nW ,window_size*window_size,window_size*window_size 这个操作mask一样的就会变成0,mask不同的就会不等于0,mask_windows.unsqueeze(1)等价于q矩阵mask,mask_windows.unsqueeze(2)等价于k矩阵mask
attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0)) #nW ,window_size*window_size,window_size*window_size [64,49,49]
else:
attn_mask = None
简单示意图:
实质上就是对应颜色的q与k要相乘,不是同一个颜色的q,k就变成了了0。因为要保证是领域的才有用,不是领域的就没什么用。
Transformer Block整体架构
两个连续的Block架构如上图所示,需要注意的是一个Stage包含的Block个数必须是偶数,因为需要交替包含一个含有Window Attention的Layer和含有Shifted Window Attention的Layer。
Block前向代码:
def forward(self, x):
H, W = self.input_resolution #假设第一次block,H,W =56,56
B, L, C = x.shape #B,56*56,96
assert L == H * W, "input feature has wrong size"
shortcut = x #B,56*56,96
x = self.norm1(x) #B,56*56,96
x = x.view(B, H, W, C) #B,56,56,96
# cyclic shift
if self.shift_size > 0:
shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2)) #roll操作#B,56,56,96
else:
shifted_x = x #B,56,56,96
# partition windows
x_windows = window_partition(shifted_x, self.window_size) # nW*B, window_size, window_size, C[B*64,7,7,96]
x_windows = x_windows.view(-1, self.window_size * self.window_size, C) # nW*B, window_size*window_size, C [B*64,49,96]
# 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) #[nW*B, window_size,window_size, C]
shifted_x = window_reverse(attn_windows, self.window_size, H, W) # B H' W' C 变回[B,56,56,96]
# reverse cyclic shift
if self.shift_size > 0:
x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2)) #将数据反向roll回去
else:
x = shifted_x
x = x.view(B, H * W, C) #[B,56*56,96]
# FFN
x = shortcut + self.drop_path(x) #[B,56*56,96]
x = x + self.drop_path(self.mlp(self.norm2(x))) #[B,56*56,96]
return x
整体的流程如下:
1.先对特征图进行LayerNorm
2.通过self.shift_size决定是否需要对特征图进行shift
3.然后将特征图切成一个个窗口
4.计算Attention,通过self.attn_mask来区分Window Attention还是Shift Window Attention
5.将各个窗口合并回来
6.如果之前有做shift操作,此时进行reverse shift,把之前的shift操作恢复
7.做dropout和残差连接
8.再通过一层LayerNorm+全连接层,以及dropout和残差连接
总结
这篇文章引入window这一个概念,将CNN的局部性引入还减少了计算量。在Shift Window Attention部分,扩大了感受野,在实现部分用mask也十分的巧妙。