52Hz commited on
Commit
e83d1da
1 Parent(s): 68652db

Create util_calculate_psnr_ssim.py

Browse files
Files changed (1) hide show
  1. utils/util_calculate_psnr_ssim.py +841 -0
utils/util_calculate_psnr_ssim.py ADDED
@@ -0,0 +1,841 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -----------------------------------------------------------------------------------
2
+ # SwinIR: Image Restoration Using Swin Transformer, https://arxiv.org/abs/2108.10257
3
+ # Originally Written by Ze Liu, Modified by Jingyun Liang.
4
+ # -----------------------------------------------------------------------------------
5
+
6
+ import math
7
+ import torch
8
+ import torch.nn as nn
9
+ import torch.utils.checkpoint as checkpoint
10
+ from timm.models.layers import DropPath, to_2tuple, trunc_normal_
11
+
12
+
13
+ class Mlp(nn.Module):
14
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
15
+ super().__init__()
16
+ out_features = out_features or in_features
17
+ hidden_features = hidden_features or in_features
18
+ self.fc1 = nn.Linear(in_features, hidden_features)
19
+ self.act = act_layer()
20
+ self.fc2 = nn.Linear(hidden_features, out_features)
21
+ self.drop = nn.Dropout(drop)
22
+
23
+ def forward(self, x):
24
+ x = self.fc1(x)
25
+ x = self.act(x)
26
+ x = self.drop(x)
27
+ x = self.fc2(x)
28
+ x = self.drop(x)
29
+ return x
30
+
31
+
32
+ def window_partition(x, window_size):
33
+ """
34
+ Args:
35
+ x: (B, H, W, C)
36
+ window_size (int): window size
37
+ Returns:
38
+ windows: (num_windows*B, window_size, window_size, C)
39
+ """
40
+ B, H, W, C = x.shape
41
+ x = x.view(B, H // window_size, window_size, W // window_size, window_size, C)
42
+ windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
43
+ return windows
44
+
45
+
46
+ def window_reverse(windows, window_size, H, W):
47
+ """
48
+ Args:
49
+ windows: (num_windows*B, window_size, window_size, C)
50
+ window_size (int): Window size
51
+ H (int): Height of image
52
+ W (int): Width of image
53
+ Returns:
54
+ x: (B, H, W, C)
55
+ """
56
+ B = int(windows.shape[0] / (H * W / window_size / window_size))
57
+ x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1)
58
+ x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)
59
+ return x
60
+
61
+
62
+ class WindowAttention(nn.Module):
63
+ r""" Window based multi-head self attention (W-MSA) module with relative position bias.
64
+ It supports both of shifted and non-shifted window.
65
+ Args:
66
+ dim (int): Number of input channels.
67
+ window_size (tuple[int]): The height and width of the window.
68
+ num_heads (int): Number of attention heads.
69
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
70
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set
71
+ attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
72
+ proj_drop (float, optional): Dropout ratio of output. Default: 0.0
73
+ """
74
+
75
+ def __init__(self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0., proj_drop=0.):
76
+
77
+ super().__init__()
78
+ self.dim = dim
79
+ self.window_size = window_size # Wh, Ww
80
+ self.num_heads = num_heads
81
+ head_dim = dim // num_heads
82
+ self.scale = qk_scale or head_dim ** -0.5
83
+
84
+ # define a parameter table of relative position bias
85
+ self.relative_position_bias_table = nn.Parameter(
86
+ torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)) # 2*Wh-1 * 2*Ww-1, nH
87
+
88
+ # get pair-wise relative position index for each token inside the window
89
+ coords_h = torch.arange(self.window_size[0])
90
+ coords_w = torch.arange(self.window_size[1])
91
+ coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
92
+ coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
93
+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
94
+ relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
95
+ relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0
96
+ relative_coords[:, :, 1] += self.window_size[1] - 1
97
+ relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
98
+ relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
99
+ self.register_buffer("relative_position_index", relative_position_index)
100
+
101
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
102
+ self.attn_drop = nn.Dropout(attn_drop)
103
+ self.proj = nn.Linear(dim, dim)
104
+
105
+ self.proj_drop = nn.Dropout(proj_drop)
106
+
107
+ trunc_normal_(self.relative_position_bias_table, std=.02)
108
+ self.softmax = nn.Softmax(dim=-1)
109
+
110
+ def forward(self, x, mask=None):
111
+ """
112
+ Args:
113
+ x: input features with shape of (num_windows*B, N, C)
114
+ mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None
115
+ """
116
+ B_, N, C = x.shape
117
+ qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
118
+ q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
119
+
120
+ q = q * self.scale
121
+ attn = (q @ k.transpose(-2, -1))
122
+
123
+ relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(
124
+ self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1) # Wh*Ww,Wh*Ww,nH
125
+ relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
126
+ attn = attn + relative_position_bias.unsqueeze(0)
127
+
128
+ if mask is not None:
129
+ nW = mask.shape[0]
130
+ attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0)
131
+ attn = attn.view(-1, self.num_heads, N, N)
132
+ attn = self.softmax(attn)
133
+ else:
134
+ attn = self.softmax(attn)
135
+
136
+ attn = self.attn_drop(attn)
137
+
138
+ x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
139
+ x = self.proj(x)
140
+ x = self.proj_drop(x)
141
+ return x
142
+
143
+ def extra_repr(self) -> str:
144
+ return f'dim={self.dim}, window_size={self.window_size}, num_heads={self.num_heads}'
145
+
146
+ def flops(self, N):
147
+ # calculate flops for 1 window with token length of N
148
+ flops = 0
149
+ # qkv = self.qkv(x)
150
+ flops += N * self.dim * 3 * self.dim
151
+ # attn = (q @ k.transpose(-2, -1))
152
+ flops += self.num_heads * N * (self.dim // self.num_heads) * N
153
+ # x = (attn @ v)
154
+ flops += self.num_heads * N * N * (self.dim // self.num_heads)
155
+ # x = self.proj(x)
156
+ flops += N * self.dim * self.dim
157
+ return flops
158
+
159
+
160
+ class SwinTransformerBlock(nn.Module):
161
+ r""" Swin Transformer Block.
162
+ Args:
163
+ dim (int): Number of input channels.
164
+ input_resolution (tuple[int]): Input resulotion.
165
+ num_heads (int): Number of attention heads.
166
+ window_size (int): Window size.
167
+ shift_size (int): Shift size for SW-MSA.
168
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
169
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
170
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
171
+ drop (float, optional): Dropout rate. Default: 0.0
172
+ attn_drop (float, optional): Attention dropout rate. Default: 0.0
173
+ drop_path (float, optional): Stochastic depth rate. Default: 0.0
174
+ act_layer (nn.Module, optional): Activation layer. Default: nn.GELU
175
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
176
+ """
177
+
178
+ def __init__(self, dim, input_resolution, num_heads, window_size=7, shift_size=0,
179
+ mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0.,
180
+ act_layer=nn.GELU, norm_layer=nn.LayerNorm):
181
+ super().__init__()
182
+ self.dim = dim
183
+ self.input_resolution = input_resolution
184
+ self.num_heads = num_heads
185
+ self.window_size = window_size
186
+ self.shift_size = shift_size
187
+ self.mlp_ratio = mlp_ratio
188
+ if min(self.input_resolution) <= self.window_size:
189
+ # if window size is larger than input resolution, we don't partition windows
190
+ self.shift_size = 0
191
+ self.window_size = min(self.input_resolution)
192
+ assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size"
193
+
194
+ self.norm1 = norm_layer(dim)
195
+ self.attn = WindowAttention(
196
+ dim, window_size=to_2tuple(self.window_size), num_heads=num_heads,
197
+ qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
198
+
199
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
200
+ self.norm2 = norm_layer(dim)
201
+ mlp_hidden_dim = int(dim * mlp_ratio)
202
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
203
+
204
+ if self.shift_size > 0:
205
+ attn_mask = self.calculate_mask(self.input_resolution)
206
+ else:
207
+ attn_mask = None
208
+
209
+ self.register_buffer("attn_mask", attn_mask)
210
+
211
+ def calculate_mask(self, x_size):
212
+ # calculate attention mask for SW-MSA
213
+ H, W = x_size
214
+ img_mask = torch.zeros((1, H, W, 1)) # 1 H W 1
215
+ h_slices = (slice(0, -self.window_size),
216
+ slice(-self.window_size, -self.shift_size),
217
+ slice(-self.shift_size, None))
218
+ w_slices = (slice(0, -self.window_size),
219
+ slice(-self.window_size, -self.shift_size),
220
+ slice(-self.shift_size, None))
221
+ cnt = 0
222
+ for h in h_slices:
223
+ for w in w_slices:
224
+ img_mask[:, h, w, :] = cnt
225
+ cnt += 1
226
+
227
+ mask_windows = window_partition(img_mask, self.window_size) # nW, window_size, window_size, 1
228
+ mask_windows = mask_windows.view(-1, self.window_size * self.window_size)
229
+ attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
230
+ attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0))
231
+
232
+ return attn_mask
233
+
234
+ def forward(self, x, x_size):
235
+ H, W = x_size
236
+ B, L, C = x.shape
237
+ # assert L == H * W, "input feature has wrong size"
238
+
239
+ shortcut = x
240
+ x = self.norm1(x)
241
+ x = x.view(B, H, W, C)
242
+
243
+ # cyclic shift
244
+ if self.shift_size > 0:
245
+ shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
246
+ else:
247
+ shifted_x = x
248
+
249
+ # partition windows
250
+ x_windows = window_partition(shifted_x, self.window_size) # nW*B, window_size, window_size, C
251
+ x_windows = x_windows.view(-1, self.window_size * self.window_size, C) # nW*B, window_size*window_size, C
252
+
253
+ # W-MSA/SW-MSA (to be compatible for testing on images whose shapes are the multiple of window size
254
+ if self.input_resolution == x_size:
255
+ attn_windows = self.attn(x_windows, mask=self.attn_mask) # nW*B, window_size*window_size, C
256
+ else:
257
+ attn_windows = self.attn(x_windows, mask=self.calculate_mask(x_size).to(x.device))
258
+
259
+ # merge windows
260
+ attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C)
261
+ shifted_x = window_reverse(attn_windows, self.window_size, H, W) # B H' W' C
262
+
263
+ # reverse cyclic shift
264
+ if self.shift_size > 0:
265
+ x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
266
+ else:
267
+ x = shifted_x
268
+ x = x.view(B, H * W, C)
269
+
270
+ # FFN
271
+ x = shortcut + self.drop_path(x)
272
+ x = x + self.drop_path(self.mlp(self.norm2(x)))
273
+
274
+ return x
275
+
276
+ def extra_repr(self) -> str:
277
+ return f"dim={self.dim}, input_resolution={self.input_resolution}, num_heads={self.num_heads}, " \
278
+ f"window_size={self.window_size}, shift_size={self.shift_size}, mlp_ratio={self.mlp_ratio}"
279
+
280
+ def flops(self):
281
+ flops = 0
282
+ H, W = self.input_resolution
283
+ # norm1
284
+ flops += self.dim * H * W
285
+ # W-MSA/SW-MSA
286
+ nW = H * W / self.window_size / self.window_size
287
+ flops += nW * self.attn.flops(self.window_size * self.window_size)
288
+ # mlp
289
+ flops += 2 * H * W * self.dim * self.dim * self.mlp_ratio
290
+ # norm2
291
+ flops += self.dim * H * W
292
+ return flops
293
+
294
+
295
+ class PatchMerging(nn.Module):
296
+ r""" Patch Merging Layer.
297
+ Args:
298
+ input_resolution (tuple[int]): Resolution of input feature.
299
+ dim (int): Number of input channels.
300
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
301
+ """
302
+
303
+ def __init__(self, input_resolution, dim, norm_layer=nn.LayerNorm):
304
+ super().__init__()
305
+ self.input_resolution = input_resolution
306
+ self.dim = dim
307
+ self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
308
+ self.norm = norm_layer(4 * dim)
309
+
310
+ def forward(self, x):
311
+ """
312
+ x: B, H*W, C
313
+ """
314
+ H, W = self.input_resolution
315
+ B, L, C = x.shape
316
+ assert L == H * W, "input feature has wrong size"
317
+ assert H % 2 == 0 and W % 2 == 0, f"x size ({H}*{W}) are not even."
318
+
319
+ x = x.view(B, H, W, C)
320
+
321
+ x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C
322
+ x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C
323
+ x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C
324
+ x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C
325
+ x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C
326
+ x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C
327
+
328
+ x = self.norm(x)
329
+ x = self.reduction(x)
330
+
331
+ return x
332
+
333
+ def extra_repr(self) -> str:
334
+ return f"input_resolution={self.input_resolution}, dim={self.dim}"
335
+
336
+ def flops(self):
337
+ H, W = self.input_resolution
338
+ flops = H * W * self.dim
339
+ flops += (H // 2) * (W // 2) * 4 * self.dim * 2 * self.dim
340
+ return flops
341
+
342
+
343
+ class BasicLayer(nn.Module):
344
+ """ A basic Swin Transformer layer for one stage.
345
+ Args:
346
+ dim (int): Number of input channels.
347
+ input_resolution (tuple[int]): Input resolution.
348
+ depth (int): Number of blocks.
349
+ num_heads (int): Number of attention heads.
350
+ window_size (int): Local window size.
351
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
352
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
353
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
354
+ drop (float, optional): Dropout rate. Default: 0.0
355
+ attn_drop (float, optional): Attention dropout rate. Default: 0.0
356
+ drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
357
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
358
+ downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
359
+ use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
360
+ """
361
+
362
+ def __init__(self, dim, input_resolution, depth, num_heads, window_size,
363
+ mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0.,
364
+ drop_path=0., norm_layer=nn.LayerNorm, downsample=None, use_checkpoint=False):
365
+
366
+ super().__init__()
367
+ self.dim = dim
368
+ self.input_resolution = input_resolution
369
+ self.depth = depth
370
+ self.use_checkpoint = use_checkpoint
371
+
372
+ # build blocks
373
+ self.blocks = nn.ModuleList([
374
+ SwinTransformerBlock(dim=dim, input_resolution=input_resolution,
375
+ num_heads=num_heads, window_size=window_size,
376
+ shift_size=0 if (i % 2 == 0) else window_size // 2,
377
+ mlp_ratio=mlp_ratio,
378
+ qkv_bias=qkv_bias, qk_scale=qk_scale,
379
+ drop=drop, attn_drop=attn_drop,
380
+ drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,
381
+ norm_layer=norm_layer)
382
+ for i in range(depth)])
383
+
384
+ # patch merging layer
385
+ if downsample is not None:
386
+ self.downsample = downsample(input_resolution, dim=dim, norm_layer=norm_layer)
387
+ else:
388
+ self.downsample = None
389
+
390
+ def forward(self, x, x_size):
391
+ for blk in self.blocks:
392
+ if self.use_checkpoint:
393
+ x = checkpoint.checkpoint(blk, x, x_size)
394
+ else:
395
+ x = blk(x, x_size)
396
+ if self.downsample is not None:
397
+ x = self.downsample(x)
398
+ return x
399
+
400
+ def extra_repr(self) -> str:
401
+ return f"dim={self.dim}, input_resolution={self.input_resolution}, depth={self.depth}"
402
+
403
+ def flops(self):
404
+ flops = 0
405
+ for blk in self.blocks:
406
+ flops += blk.flops()
407
+ if self.downsample is not None:
408
+ flops += self.downsample.flops()
409
+ return flops
410
+
411
+
412
+ class RSTB(nn.Module):
413
+ """Residual Swin Transformer Block (RSTB).
414
+ Args:
415
+ dim (int): Number of input channels.
416
+ input_resolution (tuple[int]): Input resolution.
417
+ depth (int): Number of blocks.
418
+ num_heads (int): Number of attention heads.
419
+ window_size (int): Local window size.
420
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
421
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
422
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
423
+ drop (float, optional): Dropout rate. Default: 0.0
424
+ attn_drop (float, optional): Attention dropout rate. Default: 0.0
425
+ drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
426
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
427
+ downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
428
+ use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
429
+ img_size: Input image size.
430
+ patch_size: Patch size.
431
+ resi_connection: The convolutional block before residual connection.
432
+ """
433
+
434
+ def __init__(self, dim, input_resolution, depth, num_heads, window_size,
435
+ mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0.,
436
+ drop_path=0., norm_layer=nn.LayerNorm, downsample=None, use_checkpoint=False,
437
+ img_size=224, patch_size=4, resi_connection='1conv'):
438
+ super(RSTB, self).__init__()
439
+
440
+ self.dim = dim
441
+ self.input_resolution = input_resolution
442
+
443
+ self.residual_group = BasicLayer(dim=dim,
444
+ input_resolution=input_resolution,
445
+ depth=depth,
446
+ num_heads=num_heads,
447
+ window_size=window_size,
448
+ mlp_ratio=mlp_ratio,
449
+ qkv_bias=qkv_bias, qk_scale=qk_scale,
450
+ drop=drop, attn_drop=attn_drop,
451
+ drop_path=drop_path,
452
+ norm_layer=norm_layer,
453
+ downsample=downsample,
454
+ use_checkpoint=use_checkpoint)
455
+
456
+ if resi_connection == '1conv':
457
+ self.conv = nn.Conv2d(dim, dim, 3, 1, 1)
458
+ elif resi_connection == '3conv':
459
+ # to save parameters and memory
460
+ self.conv = nn.Sequential(nn.Conv2d(dim, dim // 4, 3, 1, 1), nn.LeakyReLU(negative_slope=0.2, inplace=True),
461
+ nn.Conv2d(dim // 4, dim // 4, 1, 1, 0),
462
+ nn.LeakyReLU(negative_slope=0.2, inplace=True),
463
+ nn.Conv2d(dim // 4, dim, 3, 1, 1))
464
+
465
+ self.patch_embed = PatchEmbed(
466
+ img_size=img_size, patch_size=patch_size, in_chans=0, embed_dim=dim,
467
+ norm_layer=None)
468
+
469
+ self.patch_unembed = PatchUnEmbed(
470
+ img_size=img_size, patch_size=patch_size, in_chans=0, embed_dim=dim,
471
+ norm_layer=None)
472
+
473
+ def forward(self, x, x_size):
474
+ return self.patch_embed(self.conv(self.patch_unembed(self.residual_group(x, x_size), x_size))) + x
475
+
476
+ def flops(self):
477
+ flops = 0
478
+ flops += self.residual_group.flops()
479
+ H, W = self.input_resolution
480
+ flops += H * W * self.dim * self.dim * 9
481
+ flops += self.patch_embed.flops()
482
+ flops += self.patch_unembed.flops()
483
+
484
+ return flops
485
+
486
+
487
+ class PatchEmbed(nn.Module):
488
+ r""" Image to Patch Embedding
489
+ Args:
490
+ img_size (int): Image size. Default: 224.
491
+ patch_size (int): Patch token size. Default: 4.
492
+ in_chans (int): Number of input image channels. Default: 3.
493
+ embed_dim (int): Number of linear projection output channels. Default: 96.
494
+ norm_layer (nn.Module, optional): Normalization layer. Default: None
495
+ """
496
+
497
+ def __init__(self, img_size=224, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None):
498
+ super().__init__()
499
+ img_size = to_2tuple(img_size)
500
+ patch_size = to_2tuple(patch_size)
501
+ patches_resolution = [img_size[0] // patch_size[0], img_size[1] // patch_size[1]]
502
+ self.img_size = img_size
503
+ self.patch_size = patch_size
504
+ self.patches_resolution = patches_resolution
505
+ self.num_patches = patches_resolution[0] * patches_resolution[1]
506
+
507
+ self.in_chans = in_chans
508
+ self.embed_dim = embed_dim
509
+
510
+ if norm_layer is not None:
511
+ self.norm = norm_layer(embed_dim)
512
+ else:
513
+ self.norm = None
514
+
515
+ def forward(self, x):
516
+ x = x.flatten(2).transpose(1, 2) # B Ph*Pw C
517
+ if self.norm is not None:
518
+ x = self.norm(x)
519
+ return x
520
+
521
+ def flops(self):
522
+ flops = 0
523
+ H, W = self.img_size
524
+ if self.norm is not None:
525
+ flops += H * W * self.embed_dim
526
+ return flops
527
+
528
+
529
+ class PatchUnEmbed(nn.Module):
530
+ r""" Image to Patch Unembedding
531
+ Args:
532
+ img_size (int): Image size. Default: 224.
533
+ patch_size (int): Patch token size. Default: 4.
534
+ in_chans (int): Number of input image channels. Default: 3.
535
+ embed_dim (int): Number of linear projection output channels. Default: 96.
536
+ norm_layer (nn.Module, optional): Normalization layer. Default: None
537
+ """
538
+
539
+ def __init__(self, img_size=224, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None):
540
+ super().__init__()
541
+ img_size = to_2tuple(img_size)
542
+ patch_size = to_2tuple(patch_size)
543
+ patches_resolution = [img_size[0] // patch_size[0], img_size[1] // patch_size[1]]
544
+ self.img_size = img_size
545
+ self.patch_size = patch_size
546
+ self.patches_resolution = patches_resolution
547
+ self.num_patches = patches_resolution[0] * patches_resolution[1]
548
+
549
+ self.in_chans = in_chans
550
+ self.embed_dim = embed_dim
551
+
552
+ def forward(self, x, x_size):
553
+ B, HW, C = x.shape
554
+ x = x.transpose(1, 2).view(B, self.embed_dim, x_size[0], x_size[1]) # B Ph*Pw C
555
+ return x
556
+
557
+ def flops(self):
558
+ flops = 0
559
+ return flops
560
+
561
+
562
+ class Upsample(nn.Sequential):
563
+ """Upsample module.
564
+ Args:
565
+ scale (int): Scale factor. Supported scales: 2^n and 3.
566
+ num_feat (int): Channel number of intermediate features.
567
+ """
568
+
569
+ def __init__(self, scale, num_feat):
570
+ m = []
571
+ if (scale & (scale - 1)) == 0: # scale = 2^n
572
+ for _ in range(int(math.log(scale, 2))):
573
+ m.append(nn.Conv2d(num_feat, 4 * num_feat, 3, 1, 1))
574
+ m.append(nn.PixelShuffle(2))
575
+ elif scale == 3:
576
+ m.append(nn.Conv2d(num_feat, 9 * num_feat, 3, 1, 1))
577
+ m.append(nn.PixelShuffle(3))
578
+ else:
579
+ raise ValueError(f'scale {scale} is not supported. ' 'Supported scales: 2^n and 3.')
580
+ super(Upsample, self).__init__(*m)
581
+
582
+
583
+ class UpsampleOneStep(nn.Sequential):
584
+ """UpsampleOneStep module (the difference with Upsample is that it always only has 1conv + 1pixelshuffle)
585
+ Used in lightweight SR to save parameters.
586
+ Args:
587
+ scale (int): Scale factor. Supported scales: 2^n and 3.
588
+ num_feat (int): Channel number of intermediate features.
589
+ """
590
+
591
+ def __init__(self, scale, num_feat, num_out_ch, input_resolution=None):
592
+ self.num_feat = num_feat
593
+ self.input_resolution = input_resolution
594
+ m = []
595
+ m.append(nn.Conv2d(num_feat, (scale ** 2) * num_out_ch, 3, 1, 1))
596
+ m.append(nn.PixelShuffle(scale))
597
+ super(UpsampleOneStep, self).__init__(*m)
598
+
599
+ def flops(self):
600
+ H, W = self.input_resolution
601
+ flops = H * W * self.num_feat * 3 * 9
602
+ return flops
603
+
604
+
605
+ class SwinIR(nn.Module):
606
+ r""" SwinIR
607
+ A PyTorch impl of : `SwinIR: Image Restoration Using Swin Transformer`, based on Swin Transformer.
608
+ Args:
609
+ img_size (int | tuple(int)): Input image size. Default 64
610
+ patch_size (int | tuple(int)): Patch size. Default: 1
611
+ in_chans (int): Number of input image channels. Default: 3
612
+ embed_dim (int): Patch embedding dimension. Default: 96
613
+ depths (tuple(int)): Depth of each Swin Transformer layer.
614
+ num_heads (tuple(int)): Number of attention heads in different layers.
615
+ window_size (int): Window size. Default: 7
616
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4
617
+ qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True
618
+ qk_scale (float): Override default qk scale of head_dim ** -0.5 if set. Default: None
619
+ drop_rate (float): Dropout rate. Default: 0
620
+ attn_drop_rate (float): Attention dropout rate. Default: 0
621
+ drop_path_rate (float): Stochastic depth rate. Default: 0.1
622
+ norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm.
623
+ ape (bool): If True, add absolute position embedding to the patch embedding. Default: False
624
+ patch_norm (bool): If True, add normalization after patch embedding. Default: True
625
+ use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False
626
+ upscale: Upscale factor. 2/3/4/8 for image SR, 1 for denoising and compress artifact reduction
627
+ img_range: Image range. 1. or 255.
628
+ upsampler: The reconstruction reconstruction module. 'pixelshuffle'/'pixelshuffledirect'/'nearest+conv'/None
629
+ resi_connection: The convolutional block before residual connection. '1conv'/'3conv'
630
+ """
631
+
632
+ def __init__(self, img_size=64, patch_size=1, in_chans=3,
633
+ embed_dim=96, depths=[6, 6, 6, 6], num_heads=[6, 6, 6, 6],
634
+ window_size=7, mlp_ratio=4., qkv_bias=True, qk_scale=None,
635
+ drop_rate=0., attn_drop_rate=0., drop_path_rate=0.1,
636
+ norm_layer=nn.LayerNorm, ape=False, patch_norm=True,
637
+ use_checkpoint=False, upscale=2, img_range=1., upsampler='', resi_connection='1conv',
638
+ **kwargs):
639
+ super(SwinIR, self).__init__()
640
+ num_in_ch = in_chans
641
+ num_out_ch = in_chans
642
+ num_feat = 64
643
+ self.img_range = img_range
644
+ if in_chans == 3:
645
+ rgb_mean = (0.4488, 0.4371, 0.4040)
646
+ self.mean = torch.Tensor(rgb_mean).view(1, 3, 1, 1)
647
+ else:
648
+ self.mean = torch.zeros(1, 1, 1, 1)
649
+ self.upscale = upscale
650
+ self.upsampler = upsampler
651
+
652
+ #####################################################################################################
653
+ ################################### 1, shallow feature extraction ###################################
654
+ self.conv_first = nn.Conv2d(num_in_ch, embed_dim, 3, 1, 1)
655
+
656
+ #####################################################################################################
657
+ ################################### 2, deep feature extraction ######################################
658
+ self.num_layers = len(depths)
659
+ self.embed_dim = embed_dim
660
+ self.ape = ape
661
+ self.patch_norm = patch_norm
662
+ self.num_features = embed_dim
663
+ self.mlp_ratio = mlp_ratio
664
+
665
+ # split image into non-overlapping patches
666
+ self.patch_embed = PatchEmbed(
667
+ img_size=img_size, patch_size=patch_size, in_chans=embed_dim, embed_dim=embed_dim,
668
+ norm_layer=norm_layer if self.patch_norm else None)
669
+ num_patches = self.patch_embed.num_patches
670
+ patches_resolution = self.patch_embed.patches_resolution
671
+ self.patches_resolution = patches_resolution
672
+
673
+ # merge non-overlapping patches into image
674
+ self.patch_unembed = PatchUnEmbed(
675
+ img_size=img_size, patch_size=patch_size, in_chans=embed_dim, embed_dim=embed_dim,
676
+ norm_layer=norm_layer if self.patch_norm else None)
677
+
678
+ # absolute position embedding
679
+ if self.ape:
680
+ self.absolute_pos_embed = nn.Parameter(torch.zeros(1, num_patches, embed_dim))
681
+ trunc_normal_(self.absolute_pos_embed, std=.02)
682
+
683
+ self.pos_drop = nn.Dropout(p=drop_rate)
684
+
685
+ # stochastic depth
686
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule
687
+
688
+ # build Residual Swin Transformer blocks (RSTB)
689
+ self.layers = nn.ModuleList()
690
+ for i_layer in range(self.num_layers):
691
+ layer = RSTB(dim=embed_dim,
692
+ input_resolution=(patches_resolution[0],
693
+ patches_resolution[1]),
694
+ depth=depths[i_layer],
695
+ num_heads=num_heads[i_layer],
696
+ window_size=window_size,
697
+ mlp_ratio=self.mlp_ratio,
698
+ qkv_bias=qkv_bias, qk_scale=qk_scale,
699
+ drop=drop_rate, attn_drop=attn_drop_rate,
700
+ drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])], # no impact on SR results
701
+ norm_layer=norm_layer,
702
+ downsample=None,
703
+ use_checkpoint=use_checkpoint,
704
+ img_size=img_size,
705
+ patch_size=patch_size,
706
+ resi_connection=resi_connection
707
+
708
+ )
709
+ self.layers.append(layer)
710
+ self.norm = norm_layer(self.num_features)
711
+
712
+ # build the last conv layer in deep feature extraction
713
+ if resi_connection == '1conv':
714
+ self.conv_after_body = nn.Conv2d(embed_dim, embed_dim, 3, 1, 1)
715
+ elif resi_connection == '3conv':
716
+ # to save parameters and memory
717
+ self.conv_after_body = nn.Sequential(nn.Conv2d(embed_dim, embed_dim // 4, 3, 1, 1),
718
+ nn.LeakyReLU(negative_slope=0.2, inplace=True),
719
+ nn.Conv2d(embed_dim // 4, embed_dim // 4, 1, 1, 0),
720
+ nn.LeakyReLU(negative_slope=0.2, inplace=True),
721
+ nn.Conv2d(embed_dim // 4, embed_dim, 3, 1, 1))
722
+
723
+ #####################################################################################################
724
+ ################################ 3, high quality image reconstruction ################################
725
+ if self.upsampler == 'pixelshuffle':
726
+ # for classical SR
727
+ self.conv_before_upsample = nn.Sequential(nn.Conv2d(embed_dim, num_feat, 3, 1, 1),
728
+ nn.LeakyReLU(inplace=True))
729
+ self.upsample = Upsample(upscale, num_feat)
730
+ self.conv_last = nn.Conv2d(num_feat, num_out_ch, 3, 1, 1)
731
+ elif self.upsampler == 'pixelshuffledirect':
732
+ # for lightweight SR (to save parameters)
733
+ self.upsample = UpsampleOneStep(upscale, embed_dim, num_out_ch,
734
+ (patches_resolution[0], patches_resolution[1]))
735
+ elif self.upsampler == 'nearest+conv':
736
+ # for real-world SR (less artifacts)
737
+ assert self.upscale == 4, 'only support x4 now.'
738
+ self.conv_before_upsample = nn.Sequential(nn.Conv2d(embed_dim, num_feat, 3, 1, 1),
739
+ nn.LeakyReLU(inplace=True))
740
+ self.conv_up1 = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
741
+ self.conv_up2 = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
742
+ self.conv_hr = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
743
+ self.conv_last = nn.Conv2d(num_feat, num_out_ch, 3, 1, 1)
744
+ self.lrelu = nn.LeakyReLU(negative_slope=0.2, inplace=True)
745
+ else:
746
+ # for image denoising and JPEG compression artifact reduction
747
+ self.conv_last = nn.Conv2d(embed_dim, num_out_ch, 3, 1, 1)
748
+
749
+ self.apply(self._init_weights)
750
+
751
+ def _init_weights(self, m):
752
+ if isinstance(m, nn.Linear):
753
+ trunc_normal_(m.weight, std=.02)
754
+ if isinstance(m, nn.Linear) and m.bias is not None:
755
+ nn.init.constant_(m.bias, 0)
756
+ elif isinstance(m, nn.LayerNorm):
757
+ nn.init.constant_(m.bias, 0)
758
+ nn.init.constant_(m.weight, 1.0)
759
+
760
+ @torch.jit.ignore
761
+ def no_weight_decay(self):
762
+ return {'absolute_pos_embed'}
763
+
764
+ @torch.jit.ignore
765
+ def no_weight_decay_keywords(self):
766
+ return {'relative_position_bias_table'}
767
+
768
+ def forward_features(self, x):
769
+ x_size = (x.shape[2], x.shape[3])
770
+ x = self.patch_embed(x)
771
+ if self.ape:
772
+ x = x + self.absolute_pos_embed
773
+ x = self.pos_drop(x)
774
+
775
+ for layer in self.layers:
776
+ x = layer(x, x_size)
777
+
778
+ x = self.norm(x) # B L C
779
+ x = self.patch_unembed(x, x_size)
780
+
781
+ return x
782
+
783
+ def forward(self, x):
784
+ self.mean = self.mean.type_as(x)
785
+ x = (x - self.mean) * self.img_range
786
+
787
+ if self.upsampler == 'pixelshuffle':
788
+ # for classical SR
789
+ x = self.conv_first(x)
790
+ x = self.conv_after_body(self.forward_features(x)) + x
791
+ x = self.conv_before_upsample(x)
792
+ x = self.conv_last(self.upsample(x))
793
+ elif self.upsampler == 'pixelshuffledirect':
794
+ # for lightweight SR
795
+ x = self.conv_first(x)
796
+ x = self.conv_after_body(self.forward_features(x)) + x
797
+ x = self.upsample(x)
798
+ elif self.upsampler == 'nearest+conv':
799
+ # for real-world SR
800
+ x = self.conv_first(x)
801
+ x = self.conv_after_body(self.forward_features(x)) + x
802
+ x = self.conv_before_upsample(x)
803
+ x = self.lrelu(self.conv_up1(torch.nn.functional.interpolate(x, scale_factor=2, mode='nearest')))
804
+ x = self.lrelu(self.conv_up2(torch.nn.functional.interpolate(x, scale_factor=2, mode='nearest')))
805
+ x = self.conv_last(self.lrelu(self.conv_hr(x)))
806
+ else:
807
+ # for image denoising and JPEG compression artifact reduction
808
+ x_first = self.conv_first(x)
809
+ res = self.conv_after_body(self.forward_features(x_first)) + x_first
810
+ x = x + self.conv_last(res)
811
+
812
+ x = x / self.img_range + self.mean
813
+
814
+ return x
815
+
816
+ def flops(self):
817
+ flops = 0
818
+ H, W = self.patches_resolution
819
+ flops += H * W * 3 * self.embed_dim * 9
820
+ flops += self.patch_embed.flops()
821
+ for i, layer in enumerate(self.layers):
822
+ flops += layer.flops()
823
+ flops += H * W * 3 * self.embed_dim * self.embed_dim
824
+ flops += self.upsample.flops()
825
+ return flops
826
+
827
+
828
+ if __name__ == '__main__':
829
+ upscale = 4
830
+ window_size = 8
831
+ height = (1024 // upscale // window_size + 1) * window_size
832
+ width = (720 // upscale // window_size + 1) * window_size
833
+ model = SwinIR(upscale=2, img_size=(height, width),
834
+ window_size=window_size, img_range=1., depths=[6, 6, 6, 6],
835
+ embed_dim=60, num_heads=[6, 6, 6, 6], mlp_ratio=2, upsampler='pixelshuffledirect')
836
+ print(model)
837
+ print(height, width, model.flops() / 1e9)
838
+
839
+ x = torch.randn((1, 3, height, width))
840
+ x = model(x)
841
+ print(x.shape)