swinir_model_arch_v2.py 45 KB

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