Swin Transformer 论文与代码阅读
提示:论文阅读包含个人理解,如有错误请指正。
在 ViT 将 Transformer 运用到视觉领域之后,基于 Transformer 的视觉模型遍地开花,Swin Transformer 就是其中的代表,Swin Transformer 主要解决了 Transformer 在视觉领域应用的两个问题:
- 尺度问题:同一物体的尺寸不一定相同
- 维度问题:以像素点作为单位,导致序列长度非常长
Swin Transformer 提出了一种 Shifted windows 的分层 Transformer 用于解决以上问题,该方法将 Self-Attention 的计算限制在非重叠的局部窗口上,同时允许跨窗口的链接,提高了效率。
github :https://github.com/microsoft/Swin-Transformer/
1. 模型整体架构
上图为 Swin Transformer 的模型。
2. Patch Patition & Linear Embedding
可以看到在图中这两部分应该是分开的,但是代码中是在一起的,所以一起写了。
2.1 理论部分
Patch Patition
以 ImageNet 的图像尺寸为例即
224
×
224
×
3
224\times 224\times 3
224×224×3 ,与 ViT 相同首先是经过一个 Patch Patition,设置 Patch Size
P
h
=
P
w
=
4
P_h=P_w=4
Ph?=Pw?=4也就是将原始图像分为
4
×
4
4\times 4
4×4 的小块,共
56
×
56
56\times56
56×56 块的小图像。
如下图所示,Swin Transformer 在一开始使用的 Patch Size 为
4
×
4
4\times 4
4×4 ,在后续通过合并图像块的方式将 Patch Size 增大,以达到类似图像金字塔的效果。而 ViT 中使用的都是
16
×
16
16\times 16
16×16 的 Patch Size,因此难以捕捉多尺度的信息。
将图像分割后 Reshape 成
H
4
×
W
4
×
48
\frac{H}{4} \times\frac{W}{4}\times 48
4H?×4W?×48 ,这个可以理解为有
H
4
×
W
4
\frac{H}{4} \times\frac{W}{4}
4H?×4W?个小块,每个小块内包含的信息有
4
×
4
4 \times 4
4×4 个像素,每个像素包含 3 个通道。
Linear Embedding
Stage 1 中,在 Swin Transformer Block 前的是 Linear Embedding,后面的 Stage 都是 Patch Embedding。
被分为小块的图像需要通过 Linear Embedding,转换成 Transformer 能够使用的序列。
Linear Embedding 的具体做法就是使用一个线性变换到任意维度上,该维度设为
C
C
C ,在 Swin-T 中
C
=
96
C=96
C=96。则目前维度变化为
H
4
×
W
4
×
96
\frac{H}{4} \times\frac{W}{4}\times96
4H?×4W?×96。然后将长宽拉平至
(
H
4
×
W
4
)
×
96
(\frac{H}{4} \times\frac{W}{4})\times96
(4H?×4W?)×96。
2.2 代码部分
Patch Patition & Linear Embedding
class PatchEmbed(nn.Module):
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.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
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)
if self.norm is not None:
x = self.norm(x)
return x
一个卷积加一个LN完成,很优雅。
3. Swin Transformer Block
Swin Transformer Block 有以上两种模式,一种是 左半边内部为W-MSA的模式, 一种是右半边 内部是SW-MSA的模式,在代码上都由 SwinTransformerBlock 类实现,通过改变 shift_size 参数以判断是否需要进行 shift 操作,两个 Block 成对出现,并在 BasicLayer 中进行堆叠。
3.1 理论部分
非重叠窗口中的自注意力
显然更小的窗口能够捕捉更细节的信息,而随之而来的就是计算量的上升。ViT 的 Patch size 设置为 16,仅将图像分成了
14
×
14
14\times 14
14×14 个 patch,而 Swin 中有 $56\times 56 $个,因此序列长度扩大了 16 倍。以
224
×
224
×
3
224\times 224\times3
224×224×3 的图像为例,ViT 中经过 Linear Embedding 之后其序列为
196
×
768
196 \times 768
196×768 (不包括 cls token),而Swin中达到了
3136
×
96
3136\times 96
3136×96 ,计算量实在太大。
为了减少计算量,作者建议在局部的窗口中计算自注意力,并且窗口不相互重叠,作者计算了普通 MSA 和 W-MSA 的计算量:
Ω
(
M
S
A
)
=
4
h
w
C
2
+
2
(
h
w
)
2
C
,
Ω
(
W
?
M
S
A
)
=
4
h
w
C
2
+
2
M
2
h
w
C
\Omega(MSA)=4hwC^2 +2(hw)^2C, \\ \Omega(W-MSA)=4hwC^2 + 2M^2hwC
Ω(MSA)=4hwC2+2(hw)2C,Ω(W?MSA)=4hwC2+2M2hwC 咋一看好像差不多,但是由于
h
h
h 和
w
w
w 都较大,如上面例子中
h
=
w
=
56
h=w=56
h=w=56 ,而默认的
M
=
7
M=7
M=7 ,这样一看后半部分就差了 64 倍的计算量 。
具体的做法就是,将目前
56
×
56
×
96
56\times 56 \times 96
56×56×96 的序列,分为多个
M
×
M
M\times M
M×M 的小窗口,在每个小窗口上进行 Self-attention,把全局的自注意力转变为小窗口中局部的自注意力,从而减少算力消耗。如下图所示,每一个红色方框中各自进行自注意力。
这种做法在成功减少计算量的同时,也存在一个问题,就是自注意力只在小范围内进行,会限制模型的效果。并且相邻的像素理应关系更加密切,但会被分配在不同的窗口中,如黄色框所示。
因此,在 Swin Transformer 中提出了一种移动窗口的方法用于解决该问题。
在连续的小块中使用移动窗口分区
由于基于局部窗口的自注意力无法与其他窗口进行连接,限制了模型的能力,因此 Swin Transformer 中使用了移动窗口的方法处理该问题:
以文中的例子为例,这个例子中序列长度为
8
×
8
8\times 8
8×8,
M
=
4
M=4
M=4 ,基于窗口的自注意力的分割方法即为:
现在要使用移动窗口再次分割,窗口移动的距离为
(
?
M
2
?
,
?
M
2
?
)
(\lfloor \frac{M}{2}\rfloor, \lfloor \frac{M}{2}\rfloor)
(?2M??,?2M??),但是经过移动窗口,窗口会越出序列之外,那么就需要把上面的补到下面去,如下图:
并且,基于窗口的自注意力与移动窗口的自注意力都为成对出现,这也是每个 stage 中, Block 个数都为偶数的原因,如图:
计算方法:
z
^
l
=
W
?
M
S
A
(
L
N
(
z
l
?
1
)
)
+
z
l
?
1
z
l
=
M
L
P
(
L
N
(
z
^
l
)
)
+
z
^
l
z
^
l
+
1
=
S
W
?
M
S
A
(
L
N
(
z
l
)
)
+
z
l
z
l
+
1
=
M
L
P
(
L
N
(
z
^
l
+
1
)
)
+
z
^
l
+
1
\hat z ^l = W-MSA(LN(z^{l-1}))+z^{l-1}\\ z^l=MLP(LN(\hat z^l)) +\hat z^l\\ \hat z^{l+1} = SW-MSA (LN(z^l)) + z^l\\ z^{l+1} = MLP(LN(\hat z ^{l+1})) + \hat z ^{l+1}
z^l=W?MSA(LN(zl?1))+zl?1zl=MLP(LN(z^l))+z^lz^l+1=SW?MSA(LN(zl))+zlzl+1=MLP(LN(z^l+1))+z^l+1
3.2 代码部分
WindowAttention
具体代码有很多层,从里到外来看,首先是 WindowAttention,该代码实现了每个窗口中的自注意操作,该类既用于W-MSA 也用于 SW-MSA,在外部由 SwinTransformerBlock 中将 x 经过 shift 操作,并构建 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
self.num_heads = num_heads
head_dim = dim // num_heads
self.scale = qk_scale or head_dim ** -0.5
self.relative_position_bias_table = nn.Parameter(
torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads))
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]))
coords_flatten = torch.flatten(coords, 1)
relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :]
relative_coords = relative_coords.permute(1, 2, 0).contiguous()
relative_coords[:, :, 0] += self.window_size[0] - 1
relative_coords[:, :, 1] += self.window_size[1] - 1
relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
relative_position_index = relative_coords.sum(-1)
self.register_buffer("relative_position_index", relative_position_index)
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]
q = q * self.scale
attn = (q @ k.transpose(-2, -1))
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)
relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous()
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)
else:
attn = self.softmax(attn)
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
大部分都与 ViT 是相同的,不同的地方有:
- 输入的 x 的 shape 是
(num_windows*B, N, C) ,而 ViT 是 (B, N, C) 这是因为 WindowAttention 是将每个 patch 再分成 num_windows个窗口,然后在每个窗口上做自注意力。 - 用了相对位置编码
- 用了一个 mask 去屏蔽无用的自注意力
相对位置编码
相对位置编码是为了解决在做自注意力时,用于体现不同相对位置之间关系的一种方法,以加快收敛,提升模型能力,公式如下:
A
t
t
e
n
t
i
o
n
(
Q
,
K
,
V
)
=
S
o
f
t
M
a
x
(
Q
K
T
/
d
+
B
)
V
Attention(Q,K,V)=SoftMax(QK^T/\sqrt d+B)V
Attention(Q,K,V)=SoftMax(QKT/d
?+B)V 其中 B 为相对位置编码。显然
Q
K
T
QK^T
QKT 的形状为
(
n
u
m
_
w
i
n
d
o
w
s
?
B
,
n
u
m
_
h
e
a
d
s
,
N
,
N
)
(num\_windows*B, num\_heads, N, N)
(num_windows?B,num_heads,N,N),其相对位置编码与其形状相同。相对位置索引的生成方式如下,图片来源知乎 sharkD,侵删。
生成的相对位置索引的形状为
(
M
2
,
M
2
)
(M^2, M^2)
(M2,M2) ,并需要将其注册为一个不可学习的变量,用于根据索引值找到对应学习的位置编码。具体代码在这一长串:
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]))
coords_flatten = torch.flatten(coords, 1)
relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :]
relative_coords = relative_coords.permute(1, 2, 0).contiguous()
relative_coords[:, :, 0] += self.window_size[0] - 1
relative_coords[:, :, 1] += self.window_size[1] - 1
relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
relative_position_index = relative_coords.sum(-1)
self.register_buffer("relative_position_index", relative_position_index)
该索引值一共 $ (2M-1)^2$ 个,因此可以由一个
(
2
M
?
1
)
(
2
M
?
1
)
×
1
(2M-1)(2M-1) \times 1
(2M?1)(2M?1)×1 的张量来存储相对位置的偏置,由于使用了多头,每个头都需要一个相对位置编码,所以构建的相对位置编码表的形状为
(
2
M
?
1
)
(
2
M
?
1
)
×
n
u
m
_
h
e
a
d
s
(2M-1)(2M-1) \times num\_heads
(2M?1)(2M?1)×num_heads。
代码在:
self.relative_position_bias_table = nn.Parameter(
torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads))
在用的时候,就需要将索引表拉平,然后从编码表里获取对应偏置,然后再变回与 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)
relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous()
attn = attn + relative_position_bias.unsqueeze(0)
以上就是相对位置编码的操作过程。
masked MSA
也就是该部分,由于进行了 shift 操作,在自注意力的时候不希望途中白色部分与从上方移动过来的A、B、C之间,以及A、B、C之间进行自注意力,所以对其进行mask。
具体操作就是在做 SoftMax前,将 Attn 变为
(
B
,
n
W
,
h
e
a
d
s
,
N
,
N
)
(B, nW, heads, N, N)
(B,nW,heads,N,N)的形式,这是因为在使用窗口进行分割的时候,将分割的小块并入到了 Batch size 的维度。mask 的维度为
(
n
W
,
N
,
N
)
(nW, N, N)
(nW,N,N),将其 unsqueeze 至与 Attn 对应,即
(
1
,
n
W
,
N
,
N
)
(1, nW, N,N)
(1,nW,N,N)然后叠加。
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)
else:
attn = self.softmax(attn)
由于 mask 是一个 (0/-inf)的张量,因此在叠加后做 SoftMax, 就会把很小的那部分过滤掉。
SwinTransformerBlock
该类实现的即为上图这一部分(单个左半边或右半边),代码如下:
class SwinTransformerBlock(nn.Module):
r""" 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
act_layer (nn.Module, optional): Activation layer. Default: nn.GELU
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.,
act_layer=nn.GELU, 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:
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.norm2 = norm_layer(dim)
mlp_hidden_dim = int(dim * mlp_ratio)
self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
if self.shift_size > 0:
H, W = self.input_resolution
img_mask = torch.zeros((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)
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):
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)
if self.shift_size > 0:
shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
else:
shifted_x = x
x_windows = window_partition(shifted_x, self.window_size)
x_windows = x_windows.view(-1, self.window_size * self.window_size, C)
attn_windows = self.attn(x_windows, mask=self.attn_mask)
attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C)
shifted_x = window_reverse(attn_windows, self.window_size, H, W)
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)
x = x + self.drop_path(self.mlp(self.norm2(x)))
return x
流程过一遍:
- 输入 x 的 shape 为:
(
B
,
H
×
W
,
C
)
(B, H\times W, C)
(B,H×W,C)
- 记录 x 用于跳接
- x 经过 LN 并变换为
(
B
,
H
,
W
,
C
)
(B, H, W, C)
(B,H,W,C)准备进行 shift
- 判断
self.shift_size
- 如果
self.shift_size == 0 也就是目前是W-MSA,不需要移动窗口 - 如果
self.shift_size > 0 则目前为 SW-MSA ,则移动窗口 - 用小窗口分割 x,并将分割后的 shape 变为
(
n
W
×
B
,
W
h
×
W
w
,
C
)
(nW \times B, W_h\times W_w,C)
(nW×B,Wh?×Ww?,C) 。
- 传入分割后的 x 和 mask 进行 MSA。
- 将MSA结果变为
(
n
W
×
B
,
W
h
,
W
w
,
C
)
(nW \times B, W_h, W_w,C)
(nW×B,Wh?,Ww?,C),并将图像组合变回
(
B
,
H
,
W
,
C
)
(B, H, W, C)
(B,H,W,C) 的形式。
- 判断
self.shift_size
- 如果
self.shift_size == 0 也就是目前是W-MSA,则不变 - 如果
self.shift_size > 0 则目前为 SW-MSA ,则将之前移动窗口的操作回复原样 - 变回
(
B
,
H
×
W
,
C
)
(B, H\times W, C)
(B,H×W,C)
- drop_path + 跳接
- LN + MLP + drop_path +跳接
- 输出
下面对其中的几个点进行解析。
Cyclic Shift & Reverse
该部分是对图像的窗口进行 shift 操作,也就是移动窗口。使用条件是 self.shift_size > 0 ,通过调用 torch.roll 实现:
shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
其 Reverse 操作:
x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
Partition Windows & Reverse
该部分对图像用窗口进行分割,具体代码:
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
外侧又变为
(
n
W
×
B
,
W
h
×
W
w
,
C
)
(nW \times B, W_h\times W_w,C)
(nW×B,Wh?×Ww?,C) ,以下是其 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
变回 (B, H, W, C)。
MLP
class Mlp(nn.Module):
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
self.fc1 = nn.Linear(in_features, hidden_features)
self.act = act_layer()
self.fc2 = nn.Linear(hidden_features, out_features)
self.drop = nn.Dropout(drop)
def forward(self, x):
x = self.fc1(x)
x = self.act(x)
x = self.drop(x)
x = self.fc2(x)
x = self.drop(x)
return x
没啥好说的。
Mask
看一下 Mask 是怎么生成的,代码如下:
if self.shift_size > 0:
H, W = self.input_resolution
img_mask = torch.zeros((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)
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)
显然, 当 self.shift_size = 0 时是不需要 mask 的,因为当前是 W-MSA,只有 SW-MSA 需要 mask。
mask生成的原理即为矩阵乘法, 如下图:
代码很TM难看懂,但是跑一次就懂了,需要深入理解一下广播机制。
4. Stage 代码
4.1 Basic Layer
该部分在结构图上没有,实际上就是每个 Stage,如图:
包含 depth 个 SwinTransformerBlock,以及一个DownSample,也就是图里的 Patch Merging,这个Patch Merging的实现后面讲。
可以看到代码实现与图中略有差别,是先做 MSA 再进行Patch Merging,这里需要注意。
class BasicLayer(nn.Module):
""" A basic 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
self.blocks = nn.ModuleList([
SwinTransformerBlock(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)])
if downsample is not None:
self.downsample = downsample(input_resolution, dim=dim, norm_layer=norm_layer)
else:
self.downsample = None
def forward(self, x):
for blk in self.blocks:
if self.use_checkpoint:
x = checkpoint.checkpoint(blk, x)
else:
x = blk(x)
if self.downsample is not None:
x = self.downsample(x)
return x
没有什么好讲的,就是组合了一下。
4.2 Patch Merging
Patch Merging 起到的总用类似于 CNN 中的下采样,将每个小块的长宽缩小一半,并且让通道数增加一倍。即
H
4
×
W
4
×
C
→
H
8
×
W
8
×
2
C
\frac{H}{4} \times\frac{W}{4}\times C \to \frac{H}{8} \times\frac{W}{8}\times 2C
4H?×4W?×C→8H?×8W?×2C。该操作类似于 YOLO 中的 Focus 模块,即:
不同的是,Patch Merging 在完成 Focus 的操作之后,还要通过一个 LN 层和一个线性层,将通道 4C 变为 2C,实现和 CNN 的下采样相同。代码:
class PatchMerging(nn.Module):
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
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, :]
x1 = x[:, 1::2, 0::2, :]
x2 = x[:, 0::2, 1::2, :]
x3 = x[:, 1::2, 1::2, :]
x = torch.cat([x0, x1, x2, x3], -1)
x = x.view(B, -1, 4 * C)
x = self.norm(x)
x = self.reduction(x)
return x
5. SwinTransformer
终于来到了最上层,不得不说 SwinTransformer 模型的代码还是比较多的。
class SwinTransformer(nn.Module):
r""" Swin Transformer
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, 6, 2], num_heads=[3, 6, 12, 24],
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, **kwargs):
super().__init__()
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.mlp_ratio = mlp_ratio
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
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)
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))]
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)
self.norm = norm_layer(self.num_features)
self.avgpool = nn.AdaptiveAvgPool1d(1)
self.head = nn.Linear(self.num_features, num_classes) if num_classes > 0 else nn.Identity()
self.apply(self._init_weights)
def _init_weights(self, m):
if isinstance(m, 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'}
def forward_features(self, x):
x = self.patch_embed(x)
if self.ape:
x = x + self.absolute_pos_embed
x = self.pos_drop(x)
for layer in self.layers:
x = layer(x)
x = self.norm(x)
x = self.avgpool(x.transpose(1, 2))
x = torch.flatten(x, 1)
return x
def forward(self, x):
x = self.forward_features(x)
x = self.head(x)
return x
总体上就是将之前介绍的内容聚合在了一起,结构如下:
- Patch Patition & Linear Embedding
- 绝对位置编码 (
if self.ape - Dropout
- 进行每个 stage(除了最后一个stage,每个stage最后都有 patch merging
- LN + 转置 + avgpool+ flatten
- 一个输出头,结束
另外中间有个 stochastic depth 操作,这个操作是用来计算每个 stage 中 DropPath 的比率。
DropPath 是一个用于放在跳接处的一种类似与 DropOut 的模块,DropPath 是随机地失活一些卷积层,而 DropOut 是失活一些神经元。可以在 SwinTransformerBlock 的跳接部分中看到他:
x = shortcut + self.drop_path(x)
x = x + self.drop_path(self.mlp(self.norm2(x)))
其实现方式:
def drop_path(x, drop_prob: float = 0., training: bool = False, scale_by_keep: bool = True):
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
This is the same as the DropConnect impl I created for EfficientNet, etc networks, however,
the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for
changing the layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use
'survival rate' as the argument.
"""
if drop_prob == 0. or not training:
return x
keep_prob = 1 - drop_prob
shape = (x.shape[0],) + (1,) * (x.ndim - 1)
random_tensor = x.new_empty(shape).bernoulli_(keep_prob)
if keep_prob > 0.0 and scale_by_keep:
random_tensor.div_(keep_prob)
return x * random_tensor
class DropPath(nn.Module):
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
"""
def __init__(self, drop_prob=None, scale_by_keep=True):
super(DropPath, self).__init__()
self.drop_prob = drop_prob
self.scale_by_keep = scale_by_keep
def forward(self, x):
return drop_path(x, self.drop_prob, self.training, self.scale_by_keep)
看起来就是按比例将 Batch 维度至 0, 然后将剩余的扩大至原来尺度。至于为啥用这种奇怪的方式,暂时还不明白。
|