Swin_Transformer源码解读

网友投稿 298 2022-11-18

Swin_Transformer源码解读

文章目录

​​前言​​​​1、模型总体结构​​​​2、Patch Partion + Linear Embedding​​​​3. Patch Merging​​​​4. window attention​​

​​4.1 划分window​​​​4.2. 相对位置编码​​​​4.3. window_attn​​

​​5. shift window attn​​​​网络​​​​总结​​

前言

本文记录下swin_transformer的令我比较困惑的部分:相对位置编码和滑动窗口自注意力。非常感谢大佬的解析:​​知乎链接​​。本篇博客只是在该知乎链接基础上分析下源代码,建议读者先理解上述链接解析。

1、模型总体结构

2、Patch Partion + Linear Embedding

假设输入特征图大小为(224,224,3),则Patch Partion操作将特征图划分成443大小的patch,即(56,56,4,4,3)然后将后三个维度整合,即得到(56,56,48);然后经过Linear Embedding将最后一个维度48映射成96。  但实际在编写代码时,上述过程可以直接用96个核大小为4,步长为4的卷积操作实现:

patch_size = 4proj = nn.Conv2d(in_chans=3, embed_dim=96, kernel_size=patch_size, stride=patch_size)# forwardx = torch.randn(1,3,224,224)x = proj(x).flatten(2).transpose(1, 2) # [1,96,56,56] --> [1,96,3136] --> [1,3136,96]

通过上述操作便得到3136个tokens,其中每个token含有96维数据。

3. Patch Merging

继续按照流程图所示,在得到 [1,3136,96] 的特征后,便经过若干个stage,每个stage内部的block后续会讲,只需知道经过block后输入输出尺寸一致即可。为了后续示意图方便,假设出了stage2后,便得到[1,28*28,192]的特征,现在需要进行第三个stage,但前提得经过一步Patch Merging的操作:将特征图尺寸降倍,同时将通道数翻倍。 看代码是如何实现该过程的:

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) # 定义一个降采样倍的linear层 self.norm = norm_layer(4 * dim) def forward(self, x): """ x: B, H*W, C """ H, W = self.input_resolution B, L, C = x.shape 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) # 横纵两个方向奇偶不重叠切片 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 # 采样后则宽和高下采样两倍,通道数增加了4倍 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) x = self.reduction(x) # 利用线性层将通道数压缩2倍 return xif __name__ == '__main__': x = torch.randn(1,784,192) patch_merge = PatchMerging(input_resolution=(28,28), dim = 192) x = patch_merge(x) # [1,196,384],特征图tokens下采样四倍,通道数翻倍

4. window attention

4.1 划分window

在经过patch merging之后,便得到了[1,14*14,384]的特征图。swin transformer的一大优势就是克服了自注意力高额计算量的缺点,而实现手段就是将特征图划分成小的window,然后在每个window内部的tokens之间计算自注意力。 因此,首先看下如何将特征图划分成大小为 7*7的window的。

def window_partion(x, window_size): ''' input: x: [b,h,w,c] window_size:论文指定为7 return: window:[num_widows * 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) # [b, h// window, w//window_size, window_size, window_size, c] windows = windows.contiguous().view(-1,window_size,window_size,c) return windows

为了更加直观的看出切出来的window,我这里简单写了一个demo:假设特征图尺寸为14*14,window_size = 7,打印如下:

# 创建一个14*14的特征图,则能够划分成4个7*7的window# 为了方便展示,将每个window内部的value分别设为0,1,2,3x = torch.zeros((14,14))x[0:7,0:7] = 0x[0:7,7:] = 1x[7:, 0:7] = 2x[7:, 7:] = 3# 划分windowx = x.view( 14//7,7, 14//7, 7)x = x.permute(0,2,1,3).contiguous().view(-1,7,7)print(x)

4.2. 相对位置编码

现在假如已经将[1,14*14,384]的特征图划分成4个7*7*384的window了,在给每个window计算self-attn之前,根据transformer的思想,需要给每个window内部的位置进行位置编码,swin transformer采用的是相对位置编码,简单说下流程:一个window的大小为7*7,则左上角坐标(0,0)和右下角坐标(6,6)的相对位置编码为(-6,-6)和(6,6)。即每个window内部的位置取值为[-6,6]共13个数值即可;若采用2d位置编码,则总共需要13*13即可。 用公式表示就是:假设window_size = M,则相对位置编码的值域为 [-2M+1,2M-1]。 然后看下这部分实现的源码,创建了一个表:

# 用nn.Parameter对(2M-1,2M-1)进行了封装,这部分参数是可学习的self.relative_position_bias_table = nn.Parameter( torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads))

在创建完相对位置编码表之后,便需要对特征图的每个位置进行相对位置的编码。这里我首先贴下代码:

# get pair-wise relative position index for each token inside the windowcoords_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, Wwcoords_flatten = torch.flatten(coords, 1) # 2, Wh*Wwrelative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Wwrelative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0relative_coords[:, :, 1] += self.window_size[1] - 1relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Wwself.register_buffer("relative_position_index", relative_position_index)

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

4.3. window_attn

其实window atten和自注意力的代码一致,仅仅多了一个window的维度,看下代码:输入是经过window_partion函数的特征图x。mask先暂时不管。

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 # 创建三个qkv的全连接层 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): """ 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 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 = q * self.scale attn = (q @ k.transpose(-2, -1)) # 获取相对位置编码并加到attn上 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) if mask is not None: nW = mask.shape[0] 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) # 经过softmax else: attn = self.softmax(attn) # 经过dropout attn = self.attn_drop(attn) x = (attn @ v).transpose(1, 2).reshape(B_, N, C) x = self.proj(x) x = self.proj_drop(x) return x

5. shift window attn

x = torch.tensor([[[[1],[2],[3],[4]],[[5],[6],[7],[8]],[[9],[10],[11],[12]],[[13],[14],[15],[16]]]])x = x.squeeze(-1)print(x)shift_size = 1 # 移动的距离是window_size的一半,即2//2=1shifted_x = torch.roll( x, shifts=(-shift_size, -shift_size), dims=(1, 2))print(shifted_x)

Hp = Wp = 4img_mask = torch.zeros((1, Hp, Wp, 1)) # 创建一个和原始特征图同样大小的全0maskwindow_size = 2shift_size = 2 // 2# 切片h_slices = (slice(0, -window_size), slice(-window_size, -shift_size), slice(-shift_size, None))w_slices = (slice(0, -window_size), slice(-window_size, -shift_size), slice(-shift_size, None))cnt = 0for h in h_slices: for w in w_slices: img_mask[:, h, w, :] = cnt cnt += 1# [1,4,4,1] --> [4,2,2,1] # num_window*b, 2,2,1,总共有四个window,每个window的坐标[2,2,1]mask_windows = window_partition(img_mask, window_size) # nW, window_size, # [4,2,2,1] --> [4,4]mask_windows = mask_windows.view(-1, window_size * window_size) '''拉平tensor([[0., 0., 0., 0.], [1., 2., 1., 2.], [3., 3., 6., 6.], [4., 5., 7., 8.]])'''# [4,1,4] - [4,4,1] --> broadcast [4,4,4] - [4,4,4] = [4,4,4]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))register_buffer("attn_mask", attn_mask)

x2 = torch.tensor([[8],[5],[12],[9]]) # [4,1]attn2 = x2 @ x2.transpose(-1,-2)'''tensor([[64, 40, 96, 72], [40, 25, 60, 45], [96, 60, 144, 108], [72, 45, 108, 81]])'''

在原始特征图中,元素8和5属于同一个window,不应该和12和9计算自注意力,因为二者相隔太远。比如天空和大地两个语义就很远,没必要产生信息交互。于是需要用mask2来遮挡住这两部分元素的自注意力。后续经过softmax后-100的位置会变为0。  最终在计算完注意力之后,然后在将特征图roll回去即可。

if self.shift_size > 0: x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))

网络

总结

后续会出swinV2的解读,若有问题,欢迎+vx: wulele2541612007,拉进群讨论。

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Java 动态模拟操作系统进程调度算法
下一篇:采用FPGA与USB芯片实现智能仪器远程控制系统的设计与仿真分析
相关文章

 发表评论

暂时没有评论,来抢沙发吧~