SwinIR 讀原始碼心得

SwinIR 讀原始碼心得

Github 連結:https://github.com/JingyunLiang/SwinIR

keywords: ## 網路架構

SwinIR

網路主進入點

參數

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
img_size              輸入圖片的大小
patch_size
in_chans 輸入時的 channel 為 3
embed_dim Patch embedding 的大小,為 96
depths 每一個階段由幾個 Swin Transformer 組今,為 (6, 6, 6, 6)
num_heads Attention 中的 head 數量,為 (6, 6, 6, 6)
window_size window 的大小,為 7
mlp_ratio Transformer 中的 MLP 層放大倍率 (invert bottleneck),為 4
qkv_bias 在 Attention 中加入 B Bias,目的是加入 relevent positional encoding
qk_scale 把 QK 後的結果縮小二倍
drop_rate dropout 設定比率
attn_drop_rate Attention 也可設 dropout 比率
drop_path_rate
norm_layer normalization 層設定,為 Layer Normalization
ape 加入決對位置資訊
patch_norm 在 patch embedding 後加一層 normalization
use_checkpoint 把訓練到一半的網路參數存起來
upscale 要把圖片放大幾倍 (2/3/4/8)
img_range 圖片的「範圍」,1. or 255.
upsampler 使用什麼方法上採樣,為 pixelshuffle
resi_connection 在一個 RSTB 中,會有一個 residual connection,設定要加上一個 3x3 conv 還是一個 inverted-bottleneck 的 3x3 conv

第 0 步 - 初始變數

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
def __init__(self, img_size=64, patch_size=1, in_chans=3,
embed_dim=96, depths=[6, 6, 6, 6], num_heads=[6, 6, 6, 6],
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, upscale=2, img_range=1., upsampler='', resi_connection='1conv',
**kwargs):
super(SwinIR, self).__init__()
num_in_ch = in_chans
num_out_ch = in_chans
num_feat = 64
self.img_range = img_range

# 做 Mean Shift 處理,方法從 EDSR 這篇論文開始的
if in_chans == 3:
rgb_mean = (0.4488, 0.4371, 0.4040)
self.mean = torch.Tensor(rgb_mean).view(1, 3, 1, 1)
else:
self.mean = torch.zeros(1, 1, 1, 1)
self.upscale = upscale
self.upsampler = upsampler
self.window_size = window_size

第 1 步 - 淺層特徵提取

1
2
3
# in channel 為 3
# out channel 為 96
self.conv_first = nn.Conv2d(num_in_ch, embed_dim, 3, 1, 1)

第 2 步 - 深層特徵提取

1
2
3
4
5
6
7
8
# 圖片轉 Patch
# split image into non-overlapping patches
self.patch_embed = PatchEmbed( #TODO:
img_size=img_size, patch_size=patch_size, in_chans=embed_dim, 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
1
2
3
4
5
# Patch 轉圖片
# merge non-overlapping patches into image
self.patch_unembed = PatchUnEmbed(
img_size=img_size, patch_size=patch_size, in_chans=embed_dim, embed_dim=embed_dim,
norm_layer=norm_layer if self.patch_norm else None)
1
2
3
4
5
6
# 加入絕對資訊 (可選擇)
# 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)
1
2
3
# 隨機深度
# stochastic depth
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# 建立超多的 RSTB 層
# build Residual Swin Transformer blocks (RSTB)
self.layers = nn.ModuleList()
# depth 為 [6, 6, 6, 6]
# 4 個 num_layers
# 每一個 num_layers 有 6 個 SwinIR Layer
for i_layer in range(self.num_layers):
layer = RSTB(dim=embed_dim,
input_resolution=(patches_resolution[0],
patches_resolution[1]),
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])], # no impact on SR results
norm_layer=norm_layer,
downsample=None,
use_checkpoint=use_checkpoint,
img_size=img_size,
patch_size=patch_size,
resi_connection=resi_connection
)
self.layers.append(layer)
self.norm = norm_layer(self.num_features)
1
2
3
4
5
6
7
8
9
10
11
# 建立最後一個 CNN 特徵提取層
# build the last conv layer in deep feature extraction
if resi_connection == '1conv':
self.conv_after_body = nn.Conv2d(embed_dim, embed_dim, 3, 1, 1)
elif resi_connection == '3conv':
# to save parameters and memory
self.conv_after_body = nn.Sequential(nn.Conv2d(embed_dim, embed_dim // 4, 3, 1, 1),
nn.LeakyReLU(negative_slope=0.2, inplace=True),
nn.Conv2d(embed_dim // 4, embed_dim // 4, 1, 1, 0),
nn.LeakyReLU(negative_slope=0.2, inplace=True),
nn.Conv2d(embed_dim // 4, embed_dim, 3, 1, 1))

PatchEmbed

把影像轉換成 Patch Embedding

參數

1
2
3
4
5
img_size              圖片大小,為 224
patch_size patch 的大小,為 4
in_chans 輸入 channel,為 3
embed_dim 輸出 channel,為 96
norm_layer 做完 patch embedding 後要不要做 normalization,為 None

程式

直接用 flatten 的方式把圖片從 \(B\times H\times W\times C\) 變成 \(B\times P^2\times C\) 並且生出 patches_resolution (PxP 的大小) 還有 num_patches (patch 數量) (為什麼沒有 conv,stride=kernel_size)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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
if norm_layer is not None:
self.norm = norm_layer(embed_dim)
else:
self.norm = None

def forward(self, x):
x = x.flatten(2).transpose(1, 2) # B Ph*Pw C # 就這裡,為什麼沒有用 conv?
if self.norm is not None:
x = self.norm(x)
return x

# 還有計算 flops 的 function 呢!
def flops(self):
flops = 0
H, W = self.img_size
if self.norm is not None:
flops += H * W * self.embed_dim
return flops

PatchUnEmbed

把 patch embedding 改回原圖 個人覺得意義不明

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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

def forward(self, x, x_size):
B, HW, C = x.shape
# 在這裡把二維向量轉回三維影像
x = x.transpose(1, 2).view(B, self.embed_dim, x_size[0], x_size[1]) # B Ph*Pw C
return x

def flops(self):
flops = 0
return flops

RSTB

負責深層特徵的提取 由 BasicLayer (一堆 Swin Transformer) 以及一層 CNN 所組成

參數

1
2
dim    輸入維度
與 SwinIR 差不多,大都份都是直接傳下來的

程式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 設
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,
img_size=224, patch_size=4, resi_connection='1conv'):
super(RSTB, self).__init__()
self.dim = dim
self.input_resolution = input_resolution
self.residual_group = BasicLayer(dim=dim,
input_resolution=input_resolution,
depth=depth,
num_heads=num_heads,
window_size=window_size,
mlp_ratio=mlp_ratio,
qkv_bias=qkv_bias, qk_scale=qk_scale,
drop=drop, attn_drop=attn_drop,
drop_path=drop_path,
norm_layer=norm_layer,
downsample=downsample,
use_checkpoint=use_checkpoint)
1
2
3
4
5
6
7
8
9
# 選擇一個 3x3 還是 bottlenect 3x3
if resi_connection == '1conv':
self.conv = nn.Conv2d(dim, dim, 3, 1, 1)
elif resi_connection == '3conv':
# to save parameters and memory
self.conv = nn.Sequential(nn.Conv2d(dim, dim // 4, 3, 1, 1), nn.LeakyReLU(negative_slope=0.2, inplace=True),
nn.Conv2d(dim // 4, dim // 4, 1, 1, 0),
nn.LeakyReLU(negative_slope=0.2, inplace=True),
nn.Conv2d(dim // 4, dim, 3, 1, 1))
1
2
3
4
5
6
7
8
9
# 變 patch 以及變回圖片的方法
# 迷之 in_chans = 0,class 內跟本沒有用到這個參數…
self.patch_embed = PatchEmbed(
img_size=img_size, patch_size=patch_size, in_chans=0, embed_dim=dim,
norm_layer=None)
# 這個也同理,也沒有用到 in_chans…
self.patch_unembed = PatchUnEmbed(
img_size=img_size, patch_size=patch_size, in_chans=0, embed_dim=dim,
norm_layer=None)
1
2
3
4
5
# forward 函數
# 流程:
# Swin Transformer 群 -> 變回三維影像 -> 做一層卷積 -> 變回二維向量 -> 加上 Residual connection (identity)
def forward(self, x, x_size):
return self.patch_embed(self.conv(self.patch_unembed(self.residual_group(x, x_size), x_size))) + x
1
2
3
4
5
6
7
8
9
# 貼心的計算 flops !
def flops(self):
flops = 0
flops += self.residual_group.flops()
H, W = self.input_resolution
flops += H * W * self.dim * self.dim * 9
flops += self.patch_embed.flops()
flops += self.patch_unembed.flops()
return flops

BasicLayer

在此建立 6 層 Swin Transformer #### 參數

1
與 RSTB 差不多

程式

1
2
3
4
5
6
7
8
9
# 定義一些變數
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 堆疊 Swin Transformer Block
# build blocks
self.blocks = nn.ModuleList([
SwinTransformerBlock(dim=dim, input_resolution=input_resolution,
num_heads=num_heads, window_size=window_size,
# shift size 為 0 表示不動
# 當到下一個 Swin Block 時,移動 window size 的一半 (7 // 2 = 3)
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)])
1
2
3
4
5
6
# 這裡做 patch merging,把 H/4 W/4 C 轉變成 H/8 W/8 2C
# patch merging layer
if downsample is not None:
self.downsample = downsample(input_resolution, dim=dim, norm_layer=norm_layer)
else:
self.downsample = None
1
2
3
4
5
6
7
8
9
10
# 定義 forward 函數
def forward(self, x, x_size):
for blk in self.blocks:
if self.use_checkpoint:
x = checkpoint.checkpoint(blk, x, x_size)
else:
x = blk(x, x_size)
if self.downsample is not None:
x = self.downsample(x)
return x
1
2
3
# 印出變數用的
def extra_repr(self) -> str:
return f"dim={self.dim}, input_resolution={self.input_resolution}, depth={self.depth}"
1
2
3
4
5
6
7
8
# 貼心算 flop !
def flops(self):
flops = 0
for blk in self.blocks:
flops += blk.flops()
if self.downsample is not None:
flops += self.downsample.flops()
return flops

Swin Transformer Block

Swin Transformer 的主流程

參數

1
2
比較不一樣的是:
shift_block window 下一個位置要移動幾格

程式

1
2
3
4
5
6
7
8
9
10
11
# 定義一些初始變數
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
1
2
3
4
5
6
# 如果輸入影像的大小小於 window size 的話,就不會分割 windows 了
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"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# Attention 中的第一個 Norm
self.norm1 = norm_layer(dim)
# 這裡傳入 window attention
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)
# 如果有使用 Schotistic depth 的話,就用 dropPath
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
# Attention 中的第二個 Norm
self.norm2 = norm_layer(dim)
# bottleneck 的 MLP,放大四倍
mlp_hidden_dim = int(dim * mlp_ratio)
self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)

# 加入不會隨著網路更新的參數 (buffer) attention mask,用來蓋住 cyclic cycle 後的計算
if self.shift_size > 0:
attn_mask = self.calculate_mask(self.input_resolution)
else:
attn_mask = None
self.register_buffer("attn_mask", attn_mask)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 產生給 SW-MSA 的 Mask (有點複雜 XD)
def calculate_mask(self, x_size):
# calculate attention mask for SW-MSA
H, W = x_size
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))
return attn_mask
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def forward(self, x, x_size):
H, W = x_size
B, L, C = x.shape
# assert L == H * W, "input feature has wrong size"
shortcut = x

# 第一步:先過一個 LN
x = self.norm1(x)

# 第二步:轉成三維影像做 如果 window 有移動過 -> 做 cyclic shift,把影像拼回正常 windows 分佈
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 第三步:
# 把影像又從三維 N*H*W*C 轉變成,有 N 個 window,長寬為 M 的一堆 windows
# partition windows
x_windows = window_partition(shifted_x, self.window_size) # nW*B, window_size, window_size, C
# 再把它轉回二維向量 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 層
# 因為 window 的特性,只要圖片大小是 window size 的倍數,都可以放進網路中訓練 / 測試
# W-MSA/SW-MSA (to be compatible for testing on images whose shapes are the multiple of window size
if self.input_resolution == x_size:
attn_windows = self.attn(x_windows, mask=self.attn_mask) # nW*B, window_size*window_size, C
else:
attn_windows = self.attn(x_windows, mask=self.calculate_mask(x_size).to(x.device))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 第五步:
# 把二維向量轉回三維影像
# 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
# 第六步:
# 把剛剛 cyclic shift 給拼回去
# 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)

# 第七步:
# 首先是 Attention 的 shortcut
x = shortcut + self.drop_path(x)
# 再來是 FFN (LN + MLP) + shortcut
x = x + self.drop_path(self.mlp(self.norm2(x)))
return x
1
2
3
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}"
1
2
3
4
5
6
7
8
9
10
11
12
13
def flops(self):
flops = 0
H, W = self.input_resolution
# norm1
flops += self.dim * H * W
# W-MSA/SW-MSA
nW = H * W / self.window_size / self.window_size
flops += nW * self.attn.flops(self.window_size * self.window_size)
# mlp
flops += 2 * H * W * self.dim * self.dim * self.mlp_ratio
# norm2
flops += self.dim * H * W
return flops

WindowAttention

定義 Attenion 的部份

參數

1
都差不多

程式

1
2
3
4
5
6
7
8
9
10
11
# 初始化變數
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

# 我現在才知道…,原來 Attention 中的特徵數要除上 head 的數量,才是一個 head 的特徵數
# 為了要與其它 head 特徵相加時維持數量相等
head_dim = dim // num_heads
self.scale = qk_scale or head_dim ** -0.5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 定義相對位置表 (Parameter),等等會用來做對應用
# 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)) #

# 定義論文中提到的 relative position bias
# 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*
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
relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww

# 稱作 relative_position_index,會用這個當 index 去對應上面的表
self.register_buffer("relative_position_index", relative_position_index)
1
2
3
4
5
6
7
8
9
10
11
12
13
# 以下為定義 Self-Attention 的變數們

# 一口氣用 Linear 生出三倍的特徵量,分別代表 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)

# Truncated normal distribution 截斷常態分佈
# 簡單來說就是根據一個範圍,只選擇一定範圍的常態分佈
# ex 標準差為 2
trunc_normal_(self.relative_position_bias_table, std=.02)
self.softmax = nn.Softmax(dim=-1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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
"""

# 在這裡把 QKV 分家
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)

# QK^T
q = q * self.scale
attn = (q @ k.transpose(-2, -1))

# QK^T + B
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)

# SoftMax(QK^T + B)
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)

# SoftMax(QK^T + B) V
x = (attn @ v).transpose(1, 2).reshape(B_, N, C)

# SoftMax(QK^T + B) V W^V
x = self.proj(x)
x = self.proj_drop(x)
return x

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

def flops(self, N):
# calculate flops for 1 window with token length of N
flops = 0
# qkv = self.qkv(x)
flops += N * self.dim * 3 * self.dim
# attn = (q @ k.transpose(-2, -1))
flops += self.num_heads * N * (self.dim // self.num_heads) * N
# x = (attn @ v)
flops += self.num_heads * N * N * (self.dim // self.num_heads)
# x = self.proj(x)
flops += N * self.dim * self.dim
return flops

window_partition

把 BxHxWxC 變成

(Bx window 數量) x window 長 x window 寬 x C

1
2
3
4
5
6
7
8
9
10
11
12
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

window_reverse

(Bx window 數量) x window 長 x window 寬 x C

變成 BxHxWxC

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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