Spaces:
Running
on
T4
Running
on
T4
HikariDawn
commited on
Commit
•
9bf54b1
1
Parent(s):
72f81a3
feat: DAT and comparison
Browse files- app.py +22 -6
- architecture/dat.py +889 -0
- test_code/test_utils.py +44 -0
app.py
CHANGED
@@ -1,6 +1,10 @@
|
|
|
|
|
|
|
|
1 |
import os, sys
|
2 |
import cv2
|
3 |
import time
|
|
|
4 |
import gradio as gr
|
5 |
import torch
|
6 |
import numpy as np
|
@@ -11,7 +15,7 @@ from torchvision.utils import save_image
|
|
11 |
root_path = os.path.abspath('.')
|
12 |
sys.path.append(root_path)
|
13 |
from test_code.inference import super_resolve_img
|
14 |
-
from test_code.test_utils import load_grl, load_rrdb
|
15 |
|
16 |
|
17 |
def auto_download_if_needed(weight_path):
|
@@ -32,7 +36,10 @@ def auto_download_if_needed(weight_path):
|
|
32 |
if weight_path == "pretrained/2x_APISR_RRDB_GAN_generator.pth":
|
33 |
os.system("wget https://github.com/Kiteretsu77/APISR/releases/download/v0.1.0/2x_APISR_RRDB_GAN_generator.pth")
|
34 |
os.system("mv 2x_APISR_RRDB_GAN_generator.pth pretrained")
|
35 |
-
|
|
|
|
|
|
|
36 |
|
37 |
|
38 |
|
@@ -57,12 +64,20 @@ def inference(img_path, model_name):
|
|
57 |
auto_download_if_needed(weight_path)
|
58 |
generator = load_rrdb(weight_path, scale=2) # Directly use default way now
|
59 |
|
|
|
|
|
|
|
|
|
|
|
60 |
else:
|
61 |
raise gr.Error("We don't support such Model")
|
62 |
|
63 |
generator = generator.to(dtype=weight_dtype)
|
64 |
|
65 |
|
|
|
|
|
|
|
66 |
# In default, we will automatically use crop to match 4x size
|
67 |
super_resolved_img = super_resolve_img(generator, img_path, output_path=None, weight_dtype=weight_dtype, downsample_threshold=720, crop_for_4x=True)
|
68 |
store_name = str(time.time()) + ".png"
|
@@ -90,9 +105,9 @@ if __name__ == '__main__':
|
|
90 |
APISR aims at restoring and enhancing low-quality low-resolution **anime** images and video sources with various degradations from real-world scenarios.
|
91 |
|
92 |
### Note: Due to memory restriction, all images whose short side is over 720 pixel will be downsampled to 720 pixel with the same aspect ratio. E.g., 1920x1080 -> 1280x720
|
93 |
-
### Note: Please check [Model Zoo](https://github.com/Kiteretsu77/APISR/blob/main/docs/model_zoo.md) for the description of each weight.
|
94 |
|
95 |
-
If APISR is helpful, please help star the [GitHub Repo](https://github.com/Kiteretsu77/APISR). Thanks!
|
96 |
"""
|
97 |
|
98 |
block = gr.Blocks().queue(max_size=10)
|
@@ -106,7 +121,8 @@ if __name__ == '__main__':
|
|
106 |
[
|
107 |
"2xRRDB",
|
108 |
"4xRRDB",
|
109 |
-
"4xGRL"
|
|
|
110 |
],
|
111 |
type="value",
|
112 |
value="4xGRL",
|
@@ -134,4 +150,4 @@ if __name__ == '__main__':
|
|
134 |
|
135 |
run_btn.click(inference, inputs=[input_image, model_name], outputs=[output_image])
|
136 |
|
137 |
-
block.launch()
|
|
|
1 |
+
'''
|
2 |
+
Gradio demo (almost the same code as the one used in Huggingface space)
|
3 |
+
'''
|
4 |
import os, sys
|
5 |
import cv2
|
6 |
import time
|
7 |
+
import datetime, pytz
|
8 |
import gradio as gr
|
9 |
import torch
|
10 |
import numpy as np
|
|
|
15 |
root_path = os.path.abspath('.')
|
16 |
sys.path.append(root_path)
|
17 |
from test_code.inference import super_resolve_img
|
18 |
+
from test_code.test_utils import load_grl, load_rrdb, load_dat
|
19 |
|
20 |
|
21 |
def auto_download_if_needed(weight_path):
|
|
|
36 |
if weight_path == "pretrained/2x_APISR_RRDB_GAN_generator.pth":
|
37 |
os.system("wget https://github.com/Kiteretsu77/APISR/releases/download/v0.1.0/2x_APISR_RRDB_GAN_generator.pth")
|
38 |
os.system("mv 2x_APISR_RRDB_GAN_generator.pth pretrained")
|
39 |
+
|
40 |
+
if weight_path == "pretrained/4x_APISR_DAT_GAN_generator.pth":
|
41 |
+
os.system("wget https://github.com/Kiteretsu77/APISR/releases/download/v0.3.0/4x_APISR_DAT_GAN_generator.pth")
|
42 |
+
os.system("mv 4x_APISR_DAT_GAN_generator.pth pretrained")
|
43 |
|
44 |
|
45 |
|
|
|
64 |
auto_download_if_needed(weight_path)
|
65 |
generator = load_rrdb(weight_path, scale=2) # Directly use default way now
|
66 |
|
67 |
+
elif model_name == "4xDAT":
|
68 |
+
weight_path = "pretrained/4x_APISR_DAT_GAN_generator.pth"
|
69 |
+
auto_download_if_needed(weight_path)
|
70 |
+
generator = load_dat(weight_path, scale=4) # Directly use default way now
|
71 |
+
|
72 |
else:
|
73 |
raise gr.Error("We don't support such Model")
|
74 |
|
75 |
generator = generator.to(dtype=weight_dtype)
|
76 |
|
77 |
|
78 |
+
print("We are processing ", img_path)
|
79 |
+
print("The time now is ", datetime.datetime.now(pytz.timezone('US/Eastern')))
|
80 |
+
|
81 |
# In default, we will automatically use crop to match 4x size
|
82 |
super_resolved_img = super_resolve_img(generator, img_path, output_path=None, weight_dtype=weight_dtype, downsample_threshold=720, crop_for_4x=True)
|
83 |
store_name = str(time.time()) + ".png"
|
|
|
105 |
APISR aims at restoring and enhancing low-quality low-resolution **anime** images and video sources with various degradations from real-world scenarios.
|
106 |
|
107 |
### Note: Due to memory restriction, all images whose short side is over 720 pixel will be downsampled to 720 pixel with the same aspect ratio. E.g., 1920x1080 -> 1280x720
|
108 |
+
### Note: Please check [Model Zoo](https://github.com/Kiteretsu77/APISR/blob/main/docs/model_zoo.md) for the description of each weight and [Here](https://imgsli.com/MjU0MjI0) for model comparisons.
|
109 |
|
110 |
+
### If APISR is helpful, please help star the [GitHub Repo](https://github.com/Kiteretsu77/APISR). Thanks! ###
|
111 |
"""
|
112 |
|
113 |
block = gr.Blocks().queue(max_size=10)
|
|
|
121 |
[
|
122 |
"2xRRDB",
|
123 |
"4xRRDB",
|
124 |
+
"4xGRL",
|
125 |
+
"4xDAT",
|
126 |
],
|
127 |
type="value",
|
128 |
value="4xGRL",
|
|
|
150 |
|
151 |
run_btn.click(inference, inputs=[input_image, model_name], outputs=[output_image])
|
152 |
|
153 |
+
block.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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
'''
|
2 |
+
DAT network from https://github.com/zhengchen1999/DAT (https://openaccess.thecvf.com/content/ICCV2023/papers/Chen_Dual_Aggregation_Transformer_for_Image_Super-Resolution_ICCV_2023_paper.pdf)
|
3 |
+
'''
|
4 |
+
|
5 |
+
import torch
|
6 |
+
import torch.nn as nn
|
7 |
+
import torch.utils.checkpoint as checkpoint
|
8 |
+
from torch import Tensor
|
9 |
+
from torch.nn import functional as F
|
10 |
+
|
11 |
+
from timm.models.layers import DropPath, trunc_normal_
|
12 |
+
from einops.layers.torch import Rearrange
|
13 |
+
from einops import rearrange
|
14 |
+
|
15 |
+
import math
|
16 |
+
import numpy as np
|
17 |
+
|
18 |
+
|
19 |
+
|
20 |
+
def img2windows(img, H_sp, W_sp):
|
21 |
+
"""
|
22 |
+
Input: Image (B, C, H, W)
|
23 |
+
Output: Window Partition (B', N, C)
|
24 |
+
"""
|
25 |
+
B, C, H, W = img.shape
|
26 |
+
img_reshape = img.view(B, C, H // H_sp, H_sp, W // W_sp, W_sp)
|
27 |
+
img_perm = img_reshape.permute(0, 2, 4, 3, 5, 1).contiguous().reshape(-1, H_sp* W_sp, C)
|
28 |
+
return img_perm
|
29 |
+
|
30 |
+
|
31 |
+
def windows2img(img_splits_hw, H_sp, W_sp, H, W):
|
32 |
+
"""
|
33 |
+
Input: Window Partition (B', N, C)
|
34 |
+
Output: Image (B, H, W, C)
|
35 |
+
"""
|
36 |
+
B = int(img_splits_hw.shape[0] / (H * W / H_sp / W_sp))
|
37 |
+
|
38 |
+
img = img_splits_hw.view(B, H // H_sp, W // W_sp, H_sp, W_sp, -1)
|
39 |
+
img = img.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)
|
40 |
+
return img
|
41 |
+
|
42 |
+
|
43 |
+
class SpatialGate(nn.Module):
|
44 |
+
""" Spatial-Gate.
|
45 |
+
Args:
|
46 |
+
dim (int): Half of input channels.
|
47 |
+
"""
|
48 |
+
def __init__(self, dim):
|
49 |
+
super().__init__()
|
50 |
+
self.norm = nn.LayerNorm(dim)
|
51 |
+
self.conv = nn.Conv2d(dim, dim, kernel_size=3, stride=1, padding=1, groups=dim) # DW Conv
|
52 |
+
|
53 |
+
def forward(self, x, H, W):
|
54 |
+
# Split
|
55 |
+
x1, x2 = x.chunk(2, dim = -1)
|
56 |
+
B, N, C = x.shape
|
57 |
+
x2 = self.conv(self.norm(x2).transpose(1, 2).contiguous().view(B, C//2, H, W)).flatten(2).transpose(-1, -2).contiguous()
|
58 |
+
|
59 |
+
return x1 * x2
|
60 |
+
|
61 |
+
|
62 |
+
class SGFN(nn.Module):
|
63 |
+
""" Spatial-Gate Feed-Forward Network.
|
64 |
+
Args:
|
65 |
+
in_features (int): Number of input channels.
|
66 |
+
hidden_features (int | None): Number of hidden channels. Default: None
|
67 |
+
out_features (int | None): Number of output channels. Default: None
|
68 |
+
act_layer (nn.Module): Activation layer. Default: nn.GELU
|
69 |
+
drop (float): Dropout rate. Default: 0.0
|
70 |
+
"""
|
71 |
+
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
|
72 |
+
super().__init__()
|
73 |
+
out_features = out_features or in_features
|
74 |
+
hidden_features = hidden_features or in_features
|
75 |
+
self.fc1 = nn.Linear(in_features, hidden_features)
|
76 |
+
self.act = act_layer()
|
77 |
+
self.sg = SpatialGate(hidden_features//2)
|
78 |
+
self.fc2 = nn.Linear(hidden_features//2, out_features)
|
79 |
+
self.drop = nn.Dropout(drop)
|
80 |
+
|
81 |
+
def forward(self, x, H, W):
|
82 |
+
"""
|
83 |
+
Input: x: (B, H*W, C), H, W
|
84 |
+
Output: x: (B, H*W, C)
|
85 |
+
"""
|
86 |
+
x = self.fc1(x)
|
87 |
+
x = self.act(x)
|
88 |
+
x = self.drop(x)
|
89 |
+
|
90 |
+
x = self.sg(x, H, W)
|
91 |
+
x = self.drop(x)
|
92 |
+
|
93 |
+
x = self.fc2(x)
|
94 |
+
x = self.drop(x)
|
95 |
+
return x
|
96 |
+
|
97 |
+
|
98 |
+
class DynamicPosBias(nn.Module):
|
99 |
+
# The implementation builds on Crossformer code https://github.com/cheerss/CrossFormer/blob/main/models/crossformer.py
|
100 |
+
""" Dynamic Relative Position Bias.
|
101 |
+
Args:
|
102 |
+
dim (int): Number of input channels.
|
103 |
+
num_heads (int): Number of attention heads.
|
104 |
+
residual (bool): If True, use residual strage to connect conv.
|
105 |
+
"""
|
106 |
+
def __init__(self, dim, num_heads, residual):
|
107 |
+
super().__init__()
|
108 |
+
self.residual = residual
|
109 |
+
self.num_heads = num_heads
|
110 |
+
self.pos_dim = dim // 4
|
111 |
+
self.pos_proj = nn.Linear(2, self.pos_dim)
|
112 |
+
self.pos1 = nn.Sequential(
|
113 |
+
nn.LayerNorm(self.pos_dim),
|
114 |
+
nn.ReLU(inplace=True),
|
115 |
+
nn.Linear(self.pos_dim, self.pos_dim),
|
116 |
+
)
|
117 |
+
self.pos2 = nn.Sequential(
|
118 |
+
nn.LayerNorm(self.pos_dim),
|
119 |
+
nn.ReLU(inplace=True),
|
120 |
+
nn.Linear(self.pos_dim, self.pos_dim)
|
121 |
+
)
|
122 |
+
self.pos3 = nn.Sequential(
|
123 |
+
nn.LayerNorm(self.pos_dim),
|
124 |
+
nn.ReLU(inplace=True),
|
125 |
+
nn.Linear(self.pos_dim, self.num_heads)
|
126 |
+
)
|
127 |
+
def forward(self, biases):
|
128 |
+
if self.residual:
|
129 |
+
pos = self.pos_proj(biases) # 2Gh-1 * 2Gw-1, heads
|
130 |
+
pos = pos + self.pos1(pos)
|
131 |
+
pos = pos + self.pos2(pos)
|
132 |
+
pos = self.pos3(pos)
|
133 |
+
else:
|
134 |
+
pos = self.pos3(self.pos2(self.pos1(self.pos_proj(biases))))
|
135 |
+
return pos
|
136 |
+
|
137 |
+
|
138 |
+
class Spatial_Attention(nn.Module):
|
139 |
+
""" Spatial Window Self-Attention.
|
140 |
+
It supports rectangle window (containing square window).
|
141 |
+
Args:
|
142 |
+
dim (int): Number of input channels.
|
143 |
+
idx (int): The indentix of window. (0/1)
|
144 |
+
split_size (tuple(int)): Height and Width of spatial window.
|
145 |
+
dim_out (int | None): The dimension of the attention output. Default: None
|
146 |
+
num_heads (int): Number of attention heads. Default: 6
|
147 |
+
attn_drop (float): Dropout ratio of attention weight. Default: 0.0
|
148 |
+
proj_drop (float): Dropout ratio of output. Default: 0.0
|
149 |
+
qk_scale (float | None): Override default qk scale of head_dim ** -0.5 if set
|
150 |
+
position_bias (bool): The dynamic relative position bias. Default: True
|
151 |
+
"""
|
152 |
+
def __init__(self, dim, idx, split_size=[8,8], dim_out=None, num_heads=6, attn_drop=0., proj_drop=0., qk_scale=None, position_bias=True):
|
153 |
+
super().__init__()
|
154 |
+
self.dim = dim
|
155 |
+
self.dim_out = dim_out or dim
|
156 |
+
self.split_size = split_size
|
157 |
+
self.num_heads = num_heads
|
158 |
+
self.idx = idx
|
159 |
+
self.position_bias = position_bias
|
160 |
+
|
161 |
+
head_dim = dim // num_heads
|
162 |
+
self.scale = qk_scale or head_dim ** -0.5
|
163 |
+
|
164 |
+
if idx == 0:
|
165 |
+
H_sp, W_sp = self.split_size[0], self.split_size[1]
|
166 |
+
elif idx == 1:
|
167 |
+
W_sp, H_sp = self.split_size[0], self.split_size[1]
|
168 |
+
else:
|
169 |
+
print ("ERROR MODE", idx)
|
170 |
+
exit(0)
|
171 |
+
self.H_sp = H_sp
|
172 |
+
self.W_sp = W_sp
|
173 |
+
|
174 |
+
if self.position_bias:
|
175 |
+
self.pos = DynamicPosBias(self.dim // 4, self.num_heads, residual=False)
|
176 |
+
# generate mother-set
|
177 |
+
position_bias_h = torch.arange(1 - self.H_sp, self.H_sp)
|
178 |
+
position_bias_w = torch.arange(1 - self.W_sp, self.W_sp)
|
179 |
+
biases = torch.stack(torch.meshgrid([position_bias_h, position_bias_w]))
|
180 |
+
biases = biases.flatten(1).transpose(0, 1).contiguous().float()
|
181 |
+
self.register_buffer('rpe_biases', biases)
|
182 |
+
|
183 |
+
# get pair-wise relative position index for each token inside the window
|
184 |
+
coords_h = torch.arange(self.H_sp)
|
185 |
+
coords_w = torch.arange(self.W_sp)
|
186 |
+
coords = torch.stack(torch.meshgrid([coords_h, coords_w]))
|
187 |
+
coords_flatten = torch.flatten(coords, 1)
|
188 |
+
relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :]
|
189 |
+
relative_coords = relative_coords.permute(1, 2, 0).contiguous()
|
190 |
+
relative_coords[:, :, 0] += self.H_sp - 1
|
191 |
+
relative_coords[:, :, 1] += self.W_sp - 1
|
192 |
+
relative_coords[:, :, 0] *= 2 * self.W_sp - 1
|
193 |
+
relative_position_index = relative_coords.sum(-1)
|
194 |
+
self.register_buffer('relative_position_index', relative_position_index)
|
195 |
+
|
196 |
+
self.attn_drop = nn.Dropout(attn_drop)
|
197 |
+
|
198 |
+
def im2win(self, x, H, W):
|
199 |
+
B, N, C = x.shape
|
200 |
+
x = x.transpose(-2,-1).contiguous().view(B, C, H, W)
|
201 |
+
x = img2windows(x, self.H_sp, self.W_sp)
|
202 |
+
x = x.reshape(-1, self.H_sp* self.W_sp, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3).contiguous()
|
203 |
+
return x
|
204 |
+
|
205 |
+
def forward(self, qkv, H, W, mask=None):
|
206 |
+
"""
|
207 |
+
Input: qkv: (B, 3*L, C), H, W, mask: (B, N, N), N is the window size
|
208 |
+
Output: x (B, H, W, C)
|
209 |
+
"""
|
210 |
+
q,k,v = qkv[0], qkv[1], qkv[2]
|
211 |
+
|
212 |
+
B, L, C = q.shape
|
213 |
+
assert L == H * W, "flatten img_tokens has wrong size"
|
214 |
+
|
215 |
+
# partition the q,k,v, image to window
|
216 |
+
q = self.im2win(q, H, W)
|
217 |
+
k = self.im2win(k, H, W)
|
218 |
+
v = self.im2win(v, H, W)
|
219 |
+
|
220 |
+
q = q * self.scale
|
221 |
+
attn = (q @ k.transpose(-2, -1)) # B head N C @ B head C N --> B head N N
|
222 |
+
|
223 |
+
# calculate drpe
|
224 |
+
if self.position_bias:
|
225 |
+
pos = self.pos(self.rpe_biases)
|
226 |
+
# select position bias
|
227 |
+
relative_position_bias = pos[self.relative_position_index.view(-1)].view(
|
228 |
+
self.H_sp * self.W_sp, self.H_sp * self.W_sp, -1)
|
229 |
+
relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous()
|
230 |
+
attn = attn + relative_position_bias.unsqueeze(0)
|
231 |
+
|
232 |
+
N = attn.shape[3]
|
233 |
+
|
234 |
+
# use mask for shift window
|
235 |
+
if mask is not None:
|
236 |
+
nW = mask.shape[0]
|
237 |
+
attn = attn.view(B, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0)
|
238 |
+
attn = attn.view(-1, self.num_heads, N, N)
|
239 |
+
|
240 |
+
attn = nn.functional.softmax(attn, dim=-1, dtype=attn.dtype)
|
241 |
+
attn = self.attn_drop(attn)
|
242 |
+
|
243 |
+
x = (attn @ v)
|
244 |
+
x = x.transpose(1, 2).reshape(-1, self.H_sp* self.W_sp, C) # B head N N @ B head N C
|
245 |
+
|
246 |
+
# merge the window, window to image
|
247 |
+
x = windows2img(x, self.H_sp, self.W_sp, H, W) # B H' W' C
|
248 |
+
|
249 |
+
return x
|
250 |
+
|
251 |
+
|
252 |
+
class Adaptive_Spatial_Attention(nn.Module):
|
253 |
+
# The implementation builds on CAT code https://github.com/Zhengchen1999/CAT
|
254 |
+
""" Adaptive Spatial Self-Attention
|
255 |
+
Args:
|
256 |
+
dim (int): Number of input channels.
|
257 |
+
num_heads (int): Number of attention heads. Default: 6
|
258 |
+
split_size (tuple(int)): Height and Width of spatial window.
|
259 |
+
shift_size (tuple(int)): Shift size for spatial window.
|
260 |
+
qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True
|
261 |
+
qk_scale (float | None): Override default qk scale of head_dim ** -0.5 if set.
|
262 |
+
drop (float): Dropout rate. Default: 0.0
|
263 |
+
attn_drop (float): Attention dropout rate. Default: 0.0
|
264 |
+
rg_idx (int): The indentix of Residual Group (RG)
|
265 |
+
b_idx (int): The indentix of Block in each RG
|
266 |
+
"""
|
267 |
+
def __init__(self, dim, num_heads,
|
268 |
+
reso=64, split_size=[8,8], shift_size=[1,2], qkv_bias=False, qk_scale=None,
|
269 |
+
drop=0., attn_drop=0., rg_idx=0, b_idx=0):
|
270 |
+
super().__init__()
|
271 |
+
self.dim = dim
|
272 |
+
self.num_heads = num_heads
|
273 |
+
self.split_size = split_size
|
274 |
+
self.shift_size = shift_size
|
275 |
+
self.b_idx = b_idx
|
276 |
+
self.rg_idx = rg_idx
|
277 |
+
self.patches_resolution = reso
|
278 |
+
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
|
279 |
+
|
280 |
+
assert 0 <= self.shift_size[0] < self.split_size[0], "shift_size must in 0-split_size0"
|
281 |
+
assert 0 <= self.shift_size[1] < self.split_size[1], "shift_size must in 0-split_size1"
|
282 |
+
|
283 |
+
self.branch_num = 2
|
284 |
+
|
285 |
+
self.proj = nn.Linear(dim, dim)
|
286 |
+
self.proj_drop = nn.Dropout(drop)
|
287 |
+
|
288 |
+
self.attns = nn.ModuleList([
|
289 |
+
Spatial_Attention(
|
290 |
+
dim//2, idx = i,
|
291 |
+
split_size=split_size, num_heads=num_heads//2, dim_out=dim//2,
|
292 |
+
qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop, position_bias=True)
|
293 |
+
for i in range(self.branch_num)])
|
294 |
+
|
295 |
+
if (self.rg_idx % 2 == 0 and self.b_idx > 0 and (self.b_idx - 2) % 4 == 0) or (self.rg_idx % 2 != 0 and self.b_idx % 4 == 0):
|
296 |
+
attn_mask = self.calculate_mask(self.patches_resolution, self.patches_resolution)
|
297 |
+
self.register_buffer("attn_mask_0", attn_mask[0])
|
298 |
+
self.register_buffer("attn_mask_1", attn_mask[1])
|
299 |
+
else:
|
300 |
+
attn_mask = None
|
301 |
+
self.register_buffer("attn_mask_0", None)
|
302 |
+
self.register_buffer("attn_mask_1", None)
|
303 |
+
|
304 |
+
self.dwconv = nn.Sequential(
|
305 |
+
nn.Conv2d(dim, dim, kernel_size=3, stride=1, padding=1,groups=dim),
|
306 |
+
nn.BatchNorm2d(dim),
|
307 |
+
nn.GELU()
|
308 |
+
)
|
309 |
+
self.channel_interaction = nn.Sequential(
|
310 |
+
nn.AdaptiveAvgPool2d(1),
|
311 |
+
nn.Conv2d(dim, dim // 8, kernel_size=1),
|
312 |
+
nn.BatchNorm2d(dim // 8),
|
313 |
+
nn.GELU(),
|
314 |
+
nn.Conv2d(dim // 8, dim, kernel_size=1),
|
315 |
+
)
|
316 |
+
self.spatial_interaction = nn.Sequential(
|
317 |
+
nn.Conv2d(dim, dim // 16, kernel_size=1),
|
318 |
+
nn.BatchNorm2d(dim // 16),
|
319 |
+
nn.GELU(),
|
320 |
+
nn.Conv2d(dim // 16, 1, kernel_size=1)
|
321 |
+
)
|
322 |
+
|
323 |
+
def calculate_mask(self, H, W):
|
324 |
+
# The implementation builds on Swin Transformer code https://github.com/microsoft/Swin-Transformer/blob/main/models/swin_transformer.py
|
325 |
+
# calculate attention mask for shift window
|
326 |
+
img_mask_0 = torch.zeros((1, H, W, 1)) # 1 H W 1 idx=0
|
327 |
+
img_mask_1 = torch.zeros((1, H, W, 1)) # 1 H W 1 idx=1
|
328 |
+
h_slices_0 = (slice(0, -self.split_size[0]),
|
329 |
+
slice(-self.split_size[0], -self.shift_size[0]),
|
330 |
+
slice(-self.shift_size[0], None))
|
331 |
+
w_slices_0 = (slice(0, -self.split_size[1]),
|
332 |
+
slice(-self.split_size[1], -self.shift_size[1]),
|
333 |
+
slice(-self.shift_size[1], None))
|
334 |
+
|
335 |
+
h_slices_1 = (slice(0, -self.split_size[1]),
|
336 |
+
slice(-self.split_size[1], -self.shift_size[1]),
|
337 |
+
slice(-self.shift_size[1], None))
|
338 |
+
w_slices_1 = (slice(0, -self.split_size[0]),
|
339 |
+
slice(-self.split_size[0], -self.shift_size[0]),
|
340 |
+
slice(-self.shift_size[0], None))
|
341 |
+
cnt = 0
|
342 |
+
for h in h_slices_0:
|
343 |
+
for w in w_slices_0:
|
344 |
+
img_mask_0[:, h, w, :] = cnt
|
345 |
+
cnt += 1
|
346 |
+
cnt = 0
|
347 |
+
for h in h_slices_1:
|
348 |
+
for w in w_slices_1:
|
349 |
+
img_mask_1[:, h, w, :] = cnt
|
350 |
+
cnt += 1
|
351 |
+
|
352 |
+
# calculate mask for window-0
|
353 |
+
img_mask_0 = img_mask_0.view(1, H // self.split_size[0], self.split_size[0], W // self.split_size[1], self.split_size[1], 1)
|
354 |
+
img_mask_0 = img_mask_0.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, self.split_size[0], self.split_size[1], 1) # nW, sw[0], sw[1], 1
|
355 |
+
mask_windows_0 = img_mask_0.view(-1, self.split_size[0] * self.split_size[1])
|
356 |
+
attn_mask_0 = mask_windows_0.unsqueeze(1) - mask_windows_0.unsqueeze(2)
|
357 |
+
attn_mask_0 = attn_mask_0.masked_fill(attn_mask_0 != 0, float(-100.0)).masked_fill(attn_mask_0 == 0, float(0.0))
|
358 |
+
|
359 |
+
# calculate mask for window-1
|
360 |
+
img_mask_1 = img_mask_1.view(1, H // self.split_size[1], self.split_size[1], W // self.split_size[0], self.split_size[0], 1)
|
361 |
+
img_mask_1 = img_mask_1.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, self.split_size[1], self.split_size[0], 1) # nW, sw[1], sw[0], 1
|
362 |
+
mask_windows_1 = img_mask_1.view(-1, self.split_size[1] * self.split_size[0])
|
363 |
+
attn_mask_1 = mask_windows_1.unsqueeze(1) - mask_windows_1.unsqueeze(2)
|
364 |
+
attn_mask_1 = attn_mask_1.masked_fill(attn_mask_1 != 0, float(-100.0)).masked_fill(attn_mask_1 == 0, float(0.0))
|
365 |
+
|
366 |
+
return attn_mask_0, attn_mask_1
|
367 |
+
|
368 |
+
def forward(self, x, H, W):
|
369 |
+
"""
|
370 |
+
Input: x: (B, H*W, C), H, W
|
371 |
+
Output: x: (B, H*W, C)
|
372 |
+
"""
|
373 |
+
B, L, C = x.shape
|
374 |
+
assert L == H * W, "flatten img_tokens has wrong size"
|
375 |
+
|
376 |
+
qkv = self.qkv(x).reshape(B, -1, 3, C).permute(2, 0, 1, 3) # 3, B, HW, C
|
377 |
+
# V without partition
|
378 |
+
v = qkv[2].transpose(-2,-1).contiguous().view(B, C, H, W)
|
379 |
+
|
380 |
+
# image padding
|
381 |
+
max_split_size = max(self.split_size[0], self.split_size[1])
|
382 |
+
pad_l = pad_t = 0
|
383 |
+
pad_r = (max_split_size - W % max_split_size) % max_split_size
|
384 |
+
pad_b = (max_split_size - H % max_split_size) % max_split_size
|
385 |
+
|
386 |
+
qkv = qkv.reshape(3*B, H, W, C).permute(0, 3, 1, 2) # 3B C H W
|
387 |
+
qkv = F.pad(qkv, (pad_l, pad_r, pad_t, pad_b)).reshape(3, B, C, -1).transpose(-2, -1) # l r t b
|
388 |
+
_H = pad_b + H
|
389 |
+
_W = pad_r + W
|
390 |
+
_L = _H * _W
|
391 |
+
|
392 |
+
# window-0 and window-1 on split channels [C/2, C/2]; for square windows (e.g., 8x8), window-0 and window-1 can be merged
|
393 |
+
# shift in block: (0, 4, 8, ...), (2, 6, 10, ...), (0, 4, 8, ...), (2, 6, 10, ...), ...
|
394 |
+
if (self.rg_idx % 2 == 0 and self.b_idx > 0 and (self.b_idx - 2) % 4 == 0) or (self.rg_idx % 2 != 0 and self.b_idx % 4 == 0):
|
395 |
+
qkv = qkv.view(3, B, _H, _W, C)
|
396 |
+
qkv_0 = torch.roll(qkv[:,:,:,:,:C//2], shifts=(-self.shift_size[0], -self.shift_size[1]), dims=(2, 3))
|
397 |
+
qkv_0 = qkv_0.view(3, B, _L, C//2)
|
398 |
+
qkv_1 = torch.roll(qkv[:,:,:,:,C//2:], shifts=(-self.shift_size[1], -self.shift_size[0]), dims=(2, 3))
|
399 |
+
qkv_1 = qkv_1.view(3, B, _L, C//2)
|
400 |
+
|
401 |
+
if self.patches_resolution != _H or self.patches_resolution != _W:
|
402 |
+
mask_tmp = self.calculate_mask(_H, _W)
|
403 |
+
x1_shift = self.attns[0](qkv_0, _H, _W, mask=mask_tmp[0].to(x.device))
|
404 |
+
x2_shift = self.attns[1](qkv_1, _H, _W, mask=mask_tmp[1].to(x.device))
|
405 |
+
else:
|
406 |
+
x1_shift = self.attns[0](qkv_0, _H, _W, mask=self.attn_mask_0)
|
407 |
+
x2_shift = self.attns[1](qkv_1, _H, _W, mask=self.attn_mask_1)
|
408 |
+
|
409 |
+
x1 = torch.roll(x1_shift, shifts=(self.shift_size[0], self.shift_size[1]), dims=(1, 2))
|
410 |
+
x2 = torch.roll(x2_shift, shifts=(self.shift_size[1], self.shift_size[0]), dims=(1, 2))
|
411 |
+
x1 = x1[:, :H, :W, :].reshape(B, L, C//2)
|
412 |
+
x2 = x2[:, :H, :W, :].reshape(B, L, C//2)
|
413 |
+
# attention output
|
414 |
+
attened_x = torch.cat([x1,x2], dim=2)
|
415 |
+
|
416 |
+
else:
|
417 |
+
x1 = self.attns[0](qkv[:,:,:,:C//2], _H, _W)[:, :H, :W, :].reshape(B, L, C//2)
|
418 |
+
x2 = self.attns[1](qkv[:,:,:,C//2:], _H, _W)[:, :H, :W, :].reshape(B, L, C//2)
|
419 |
+
# attention output
|
420 |
+
attened_x = torch.cat([x1,x2], dim=2)
|
421 |
+
|
422 |
+
# convolution output
|
423 |
+
conv_x = self.dwconv(v)
|
424 |
+
|
425 |
+
# Adaptive Interaction Module (AIM)
|
426 |
+
# C-Map (before sigmoid)
|
427 |
+
channel_map = self.channel_interaction(conv_x).permute(0, 2, 3, 1).contiguous().view(B, 1, C)
|
428 |
+
# S-Map (before sigmoid)
|
429 |
+
attention_reshape = attened_x.transpose(-2,-1).contiguous().view(B, C, H, W)
|
430 |
+
spatial_map = self.spatial_interaction(attention_reshape)
|
431 |
+
|
432 |
+
# C-I
|
433 |
+
attened_x = attened_x * torch.sigmoid(channel_map)
|
434 |
+
# S-I
|
435 |
+
conv_x = torch.sigmoid(spatial_map) * conv_x
|
436 |
+
conv_x = conv_x.permute(0, 2, 3, 1).contiguous().view(B, L, C)
|
437 |
+
|
438 |
+
x = attened_x + conv_x
|
439 |
+
|
440 |
+
x = self.proj(x)
|
441 |
+
x = self.proj_drop(x)
|
442 |
+
|
443 |
+
return x
|
444 |
+
|
445 |
+
|
446 |
+
class Adaptive_Channel_Attention(nn.Module):
|
447 |
+
# The implementation builds on XCiT code https://github.com/facebookresearch/xcit
|
448 |
+
""" Adaptive Channel Self-Attention
|
449 |
+
Args:
|
450 |
+
dim (int): Number of input channels.
|
451 |
+
num_heads (int): Number of attention heads. Default: 6
|
452 |
+
qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True
|
453 |
+
qk_scale (float | None): Override default qk scale of head_dim ** -0.5 if set.
|
454 |
+
attn_drop (float): Attention dropout rate. Default: 0.0
|
455 |
+
drop_path (float): Stochastic depth rate. Default: 0.0
|
456 |
+
"""
|
457 |
+
def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.):
|
458 |
+
super().__init__()
|
459 |
+
self.num_heads = num_heads
|
460 |
+
self.temperature = nn.Parameter(torch.ones(num_heads, 1, 1))
|
461 |
+
|
462 |
+
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
|
463 |
+
self.attn_drop = nn.Dropout(attn_drop)
|
464 |
+
self.proj = nn.Linear(dim, dim)
|
465 |
+
self.proj_drop = nn.Dropout(proj_drop)
|
466 |
+
|
467 |
+
self.dwconv = nn.Sequential(
|
468 |
+
nn.Conv2d(dim, dim, kernel_size=3, stride=1, padding=1,groups=dim),
|
469 |
+
nn.BatchNorm2d(dim),
|
470 |
+
nn.GELU()
|
471 |
+
)
|
472 |
+
self.channel_interaction = nn.Sequential(
|
473 |
+
nn.AdaptiveAvgPool2d(1),
|
474 |
+
nn.Conv2d(dim, dim // 8, kernel_size=1),
|
475 |
+
nn.BatchNorm2d(dim // 8),
|
476 |
+
nn.GELU(),
|
477 |
+
nn.Conv2d(dim // 8, dim, kernel_size=1),
|
478 |
+
)
|
479 |
+
self.spatial_interaction = nn.Sequential(
|
480 |
+
nn.Conv2d(dim, dim // 16, kernel_size=1),
|
481 |
+
nn.BatchNorm2d(dim // 16),
|
482 |
+
nn.GELU(),
|
483 |
+
nn.Conv2d(dim // 16, 1, kernel_size=1)
|
484 |
+
)
|
485 |
+
|
486 |
+
def forward(self, x, H, W):
|
487 |
+
"""
|
488 |
+
Input: x: (B, H*W, C), H, W
|
489 |
+
Output: x: (B, H*W, C)
|
490 |
+
"""
|
491 |
+
B, N, C = x.shape
|
492 |
+
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads)
|
493 |
+
qkv = qkv.permute(2, 0, 3, 1, 4)
|
494 |
+
q, k, v = qkv[0], qkv[1], qkv[2]
|
495 |
+
|
496 |
+
q = q.transpose(-2, -1)
|
497 |
+
k = k.transpose(-2, -1)
|
498 |
+
v = v.transpose(-2, -1)
|
499 |
+
|
500 |
+
v_ = v.reshape(B, C, N).contiguous().view(B, C, H, W)
|
501 |
+
|
502 |
+
q = torch.nn.functional.normalize(q, dim=-1)
|
503 |
+
k = torch.nn.functional.normalize(k, dim=-1)
|
504 |
+
|
505 |
+
attn = (q @ k.transpose(-2, -1)) * self.temperature
|
506 |
+
attn = attn.softmax(dim=-1)
|
507 |
+
attn = self.attn_drop(attn)
|
508 |
+
|
509 |
+
# attention output
|
510 |
+
attened_x = (attn @ v).permute(0, 3, 1, 2).reshape(B, N, C)
|
511 |
+
|
512 |
+
# convolution output
|
513 |
+
conv_x = self.dwconv(v_)
|
514 |
+
|
515 |
+
# Adaptive Interaction Module (AIM)
|
516 |
+
# C-Map (before sigmoid)
|
517 |
+
attention_reshape = attened_x.transpose(-2,-1).contiguous().view(B, C, H, W)
|
518 |
+
channel_map = self.channel_interaction(attention_reshape)
|
519 |
+
# S-Map (before sigmoid)
|
520 |
+
spatial_map = self.spatial_interaction(conv_x).permute(0, 2, 3, 1).contiguous().view(B, N, 1)
|
521 |
+
|
522 |
+
# S-I
|
523 |
+
attened_x = attened_x * torch.sigmoid(spatial_map)
|
524 |
+
# C-I
|
525 |
+
conv_x = conv_x * torch.sigmoid(channel_map)
|
526 |
+
conv_x = conv_x.permute(0, 2, 3, 1).contiguous().view(B, N, C)
|
527 |
+
|
528 |
+
x = attened_x + conv_x
|
529 |
+
|
530 |
+
x = self.proj(x)
|
531 |
+
x = self.proj_drop(x)
|
532 |
+
|
533 |
+
return x
|
534 |
+
|
535 |
+
|
536 |
+
class DATB(nn.Module):
|
537 |
+
def __init__(self, dim, num_heads, reso=64, split_size=[2,4],shift_size=[1,2], expansion_factor=4., qkv_bias=False, qk_scale=None, drop=0.,
|
538 |
+
attn_drop=0., drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, rg_idx=0, b_idx=0):
|
539 |
+
super().__init__()
|
540 |
+
|
541 |
+
self.norm1 = norm_layer(dim)
|
542 |
+
|
543 |
+
if b_idx % 2 == 0:
|
544 |
+
# DSTB
|
545 |
+
self.attn = Adaptive_Spatial_Attention(
|
546 |
+
dim, num_heads=num_heads, reso=reso, split_size=split_size, shift_size=shift_size, qkv_bias=qkv_bias, qk_scale=qk_scale,
|
547 |
+
drop=drop, attn_drop=attn_drop, rg_idx=rg_idx, b_idx=b_idx
|
548 |
+
)
|
549 |
+
else:
|
550 |
+
# DCTB
|
551 |
+
self.attn = Adaptive_Channel_Attention(
|
552 |
+
dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop,
|
553 |
+
proj_drop=drop
|
554 |
+
)
|
555 |
+
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
|
556 |
+
|
557 |
+
ffn_hidden_dim = int(dim * expansion_factor)
|
558 |
+
self.ffn = SGFN(in_features=dim, hidden_features=ffn_hidden_dim, out_features=dim, act_layer=act_layer)
|
559 |
+
self.norm2 = norm_layer(dim)
|
560 |
+
|
561 |
+
def forward(self, x, x_size):
|
562 |
+
"""
|
563 |
+
Input: x: (B, H*W, C), x_size: (H, W)
|
564 |
+
Output: x: (B, H*W, C)
|
565 |
+
"""
|
566 |
+
H , W = x_size
|
567 |
+
x = x + self.drop_path(self.attn(self.norm1(x), H, W))
|
568 |
+
x = x + self.drop_path(self.ffn(self.norm2(x), H, W))
|
569 |
+
|
570 |
+
return x
|
571 |
+
|
572 |
+
|
573 |
+
class ResidualGroup(nn.Module):
|
574 |
+
""" ResidualGroup
|
575 |
+
Args:
|
576 |
+
dim (int): Number of input channels.
|
577 |
+
reso (int): Input resolution.
|
578 |
+
num_heads (int): Number of attention heads.
|
579 |
+
split_size (tuple(int)): Height and Width of spatial window.
|
580 |
+
expansion_factor (float): Ratio of ffn hidden dim to embedding dim.
|
581 |
+
qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True
|
582 |
+
qk_scale (float | None): Override default qk scale of head_dim ** -0.5 if set. Default: None
|
583 |
+
drop (float): Dropout rate. Default: 0
|
584 |
+
attn_drop(float): Attention dropout rate. Default: 0
|
585 |
+
drop_paths (float | None): Stochastic depth rate.
|
586 |
+
act_layer (nn.Module): Activation layer. Default: nn.GELU
|
587 |
+
norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm
|
588 |
+
depth (int): Number of dual aggregation Transformer blocks in residual group.
|
589 |
+
use_chk (bool): Whether to use checkpointing to save memory.
|
590 |
+
resi_connection: The convolutional block before residual connection. '1conv'/'3conv'
|
591 |
+
"""
|
592 |
+
def __init__( self,
|
593 |
+
dim,
|
594 |
+
reso,
|
595 |
+
num_heads,
|
596 |
+
split_size=[2,4],
|
597 |
+
expansion_factor=4.,
|
598 |
+
qkv_bias=False,
|
599 |
+
qk_scale=None,
|
600 |
+
drop=0.,
|
601 |
+
attn_drop=0.,
|
602 |
+
drop_paths=None,
|
603 |
+
act_layer=nn.GELU,
|
604 |
+
norm_layer=nn.LayerNorm,
|
605 |
+
depth=2,
|
606 |
+
use_chk=False,
|
607 |
+
resi_connection='1conv',
|
608 |
+
rg_idx=0):
|
609 |
+
super().__init__()
|
610 |
+
self.use_chk = use_chk
|
611 |
+
self.reso = reso
|
612 |
+
|
613 |
+
self.blocks = nn.ModuleList([
|
614 |
+
DATB(
|
615 |
+
dim=dim,
|
616 |
+
num_heads=num_heads,
|
617 |
+
reso = reso,
|
618 |
+
split_size = split_size,
|
619 |
+
shift_size = [split_size[0]//2, split_size[1]//2],
|
620 |
+
expansion_factor=expansion_factor,
|
621 |
+
qkv_bias=qkv_bias,
|
622 |
+
qk_scale=qk_scale,
|
623 |
+
drop=drop,
|
624 |
+
attn_drop=attn_drop,
|
625 |
+
drop_path=drop_paths[i],
|
626 |
+
act_layer=act_layer,
|
627 |
+
norm_layer=norm_layer,
|
628 |
+
rg_idx = rg_idx,
|
629 |
+
b_idx = i,
|
630 |
+
)for i in range(depth)])
|
631 |
+
|
632 |
+
if resi_connection == '1conv':
|
633 |
+
self.conv = nn.Conv2d(dim, dim, 3, 1, 1)
|
634 |
+
elif resi_connection == '3conv':
|
635 |
+
self.conv = nn.Sequential(
|
636 |
+
nn.Conv2d(dim, dim // 4, 3, 1, 1), nn.LeakyReLU(negative_slope=0.2, inplace=True),
|
637 |
+
nn.Conv2d(dim // 4, dim // 4, 1, 1, 0), nn.LeakyReLU(negative_slope=0.2, inplace=True),
|
638 |
+
nn.Conv2d(dim // 4, dim, 3, 1, 1))
|
639 |
+
|
640 |
+
def forward(self, x, x_size):
|
641 |
+
"""
|
642 |
+
Input: x: (B, H*W, C), x_size: (H, W)
|
643 |
+
Output: x: (B, H*W, C)
|
644 |
+
"""
|
645 |
+
H, W = x_size
|
646 |
+
res = x
|
647 |
+
for blk in self.blocks:
|
648 |
+
if self.use_chk:
|
649 |
+
x = checkpoint.checkpoint(blk, x, x_size)
|
650 |
+
else:
|
651 |
+
x = blk(x, x_size)
|
652 |
+
x = rearrange(x, "b (h w) c -> b c h w", h=H, w=W)
|
653 |
+
x = self.conv(x)
|
654 |
+
x = rearrange(x, "b c h w -> b (h w) c")
|
655 |
+
x = res + x
|
656 |
+
|
657 |
+
return x
|
658 |
+
|
659 |
+
|
660 |
+
class Upsample(nn.Sequential):
|
661 |
+
"""Upsample module.
|
662 |
+
Args:
|
663 |
+
scale (int): Scale factor. Supported scales: 2^n and 3.
|
664 |
+
num_feat (int): Channel number of intermediate features.
|
665 |
+
"""
|
666 |
+
def __init__(self, scale, num_feat):
|
667 |
+
m = []
|
668 |
+
if (scale & (scale - 1)) == 0: # scale = 2^n
|
669 |
+
for _ in range(int(math.log(scale, 2))):
|
670 |
+
m.append(nn.Conv2d(num_feat, 4 * num_feat, 3, 1, 1))
|
671 |
+
m.append(nn.PixelShuffle(2))
|
672 |
+
elif scale == 3:
|
673 |
+
m.append(nn.Conv2d(num_feat, 9 * num_feat, 3, 1, 1))
|
674 |
+
m.append(nn.PixelShuffle(3))
|
675 |
+
else:
|
676 |
+
raise ValueError(f'scale {scale} is not supported. ' 'Supported scales: 2^n and 3.')
|
677 |
+
super(Upsample, self).__init__(*m)
|
678 |
+
|
679 |
+
|
680 |
+
class UpsampleOneStep(nn.Sequential):
|
681 |
+
"""UpsampleOneStep module (the difference with Upsample is that it always only has 1conv + 1pixelshuffle)
|
682 |
+
Used in lightweight SR to save parameters.
|
683 |
+
|
684 |
+
Args:
|
685 |
+
scale (int): Scale factor. Supported scales: 2^n and 3.
|
686 |
+
num_feat (int): Channel number of intermediate features.
|
687 |
+
|
688 |
+
"""
|
689 |
+
|
690 |
+
def __init__(self, scale, num_feat, num_out_ch, input_resolution=None):
|
691 |
+
self.num_feat = num_feat
|
692 |
+
self.input_resolution = input_resolution
|
693 |
+
m = []
|
694 |
+
m.append(nn.Conv2d(num_feat, (scale**2) * num_out_ch, 3, 1, 1))
|
695 |
+
m.append(nn.PixelShuffle(scale))
|
696 |
+
super(UpsampleOneStep, self).__init__(*m)
|
697 |
+
|
698 |
+
def flops(self):
|
699 |
+
h, w = self.input_resolution
|
700 |
+
flops = h * w * self.num_feat * 3 * 9
|
701 |
+
return flops
|
702 |
+
|
703 |
+
|
704 |
+
class DAT(nn.Module):
|
705 |
+
""" Dual Aggregation Transformer
|
706 |
+
Args:
|
707 |
+
img_size (int): Input image size. Default: 64
|
708 |
+
in_chans (int): Number of input image channels. Default: 3
|
709 |
+
embed_dim (int): Patch embedding dimension. Default: 180
|
710 |
+
depths (tuple(int)): Depth of each residual group (number of DATB in each RG).
|
711 |
+
split_size (tuple(int)): Height and Width of spatial window.
|
712 |
+
num_heads (tuple(int)): Number of attention heads in different residual groups.
|
713 |
+
expansion_factor (float): Ratio of ffn hidden dim to embedding dim. Default: 4
|
714 |
+
qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True
|
715 |
+
qk_scale (float | None): Override default qk scale of head_dim ** -0.5 if set. Default: None
|
716 |
+
drop_rate (float): Dropout rate. Default: 0
|
717 |
+
attn_drop_rate (float): Attention dropout rate. Default: 0
|
718 |
+
drop_path_rate (float): Stochastic depth rate. Default: 0.1
|
719 |
+
act_layer (nn.Module): Activation layer. Default: nn.GELU
|
720 |
+
norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm
|
721 |
+
use_chk (bool): Whether to use checkpointing to save memory.
|
722 |
+
upscale: Upscale factor. 2/3/4 for image SR
|
723 |
+
img_range: Image range. 1. or 255.
|
724 |
+
resi_connection: The convolutional block before residual connection. '1conv'/'3conv'
|
725 |
+
"""
|
726 |
+
def __init__(self,
|
727 |
+
img_size=64,
|
728 |
+
in_chans=3,
|
729 |
+
embed_dim=180,
|
730 |
+
split_size=[2,4],
|
731 |
+
depth=[2,2,2,2],
|
732 |
+
num_heads=[2,2,2,2],
|
733 |
+
expansion_factor=4.,
|
734 |
+
qkv_bias=True,
|
735 |
+
qk_scale=None,
|
736 |
+
drop_rate=0.,
|
737 |
+
attn_drop_rate=0.,
|
738 |
+
drop_path_rate=0.1,
|
739 |
+
act_layer=nn.GELU,
|
740 |
+
norm_layer=nn.LayerNorm,
|
741 |
+
use_chk=False,
|
742 |
+
upscale=2,
|
743 |
+
img_range=1.,
|
744 |
+
resi_connection='1conv',
|
745 |
+
upsampler='pixelshuffle',
|
746 |
+
**kwargs):
|
747 |
+
super().__init__()
|
748 |
+
|
749 |
+
num_in_ch = in_chans
|
750 |
+
num_out_ch = in_chans
|
751 |
+
num_feat = 64
|
752 |
+
self.img_range = img_range
|
753 |
+
if in_chans == 3:
|
754 |
+
rgb_mean = (0.4488, 0.4371, 0.4040)
|
755 |
+
self.mean = torch.Tensor(rgb_mean).view(1, 3, 1, 1)
|
756 |
+
else:
|
757 |
+
self.mean = torch.zeros(1, 1, 1, 1)
|
758 |
+
self.upscale = upscale
|
759 |
+
self.upsampler = upsampler
|
760 |
+
|
761 |
+
# ------------------------- 1, Shallow Feature Extraction ------------------------- #
|
762 |
+
self.conv_first = nn.Conv2d(num_in_ch, embed_dim, 3, 1, 1)
|
763 |
+
|
764 |
+
# ------------------------- 2, Deep Feature Extraction ------------------------- #
|
765 |
+
self.num_layers = len(depth)
|
766 |
+
self.use_chk = use_chk
|
767 |
+
self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
|
768 |
+
heads=num_heads
|
769 |
+
|
770 |
+
self.before_RG = nn.Sequential(
|
771 |
+
Rearrange('b c h w -> b (h w) c'),
|
772 |
+
nn.LayerNorm(embed_dim)
|
773 |
+
)
|
774 |
+
|
775 |
+
curr_dim = embed_dim
|
776 |
+
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, np.sum(depth))] # stochastic depth decay rule
|
777 |
+
|
778 |
+
self.layers = nn.ModuleList()
|
779 |
+
for i in range(self.num_layers):
|
780 |
+
layer = ResidualGroup(
|
781 |
+
dim=embed_dim,
|
782 |
+
num_heads=heads[i],
|
783 |
+
reso=img_size,
|
784 |
+
split_size=split_size,
|
785 |
+
expansion_factor=expansion_factor,
|
786 |
+
qkv_bias=qkv_bias,
|
787 |
+
qk_scale=qk_scale,
|
788 |
+
drop=drop_rate,
|
789 |
+
attn_drop=attn_drop_rate,
|
790 |
+
drop_paths=dpr[sum(depth[:i]):sum(depth[:i + 1])],
|
791 |
+
act_layer=act_layer,
|
792 |
+
norm_layer=norm_layer,
|
793 |
+
depth=depth[i],
|
794 |
+
use_chk=use_chk,
|
795 |
+
resi_connection=resi_connection,
|
796 |
+
rg_idx=i)
|
797 |
+
self.layers.append(layer)
|
798 |
+
|
799 |
+
self.norm = norm_layer(curr_dim)
|
800 |
+
# build the last conv layer in deep feature extraction
|
801 |
+
if resi_connection == '1conv':
|
802 |
+
self.conv_after_body = nn.Conv2d(embed_dim, embed_dim, 3, 1, 1)
|
803 |
+
elif resi_connection == '3conv':
|
804 |
+
# to save parameters and memory
|
805 |
+
self.conv_after_body = nn.Sequential(
|
806 |
+
nn.Conv2d(embed_dim, embed_dim // 4, 3, 1, 1), nn.LeakyReLU(negative_slope=0.2, inplace=True),
|
807 |
+
nn.Conv2d(embed_dim // 4, embed_dim // 4, 1, 1, 0), nn.LeakyReLU(negative_slope=0.2, inplace=True),
|
808 |
+
nn.Conv2d(embed_dim // 4, embed_dim, 3, 1, 1))
|
809 |
+
|
810 |
+
# ------------------------- 3, Reconstruction ------------------------- #
|
811 |
+
if self.upsampler == 'pixelshuffle':
|
812 |
+
# for classical SR
|
813 |
+
self.conv_before_upsample = nn.Sequential(
|
814 |
+
nn.Conv2d(embed_dim, num_feat, 3, 1, 1), nn.LeakyReLU(inplace=True))
|
815 |
+
self.upsample = Upsample(upscale, num_feat)
|
816 |
+
self.conv_last = nn.Conv2d(num_feat, num_out_ch, 3, 1, 1)
|
817 |
+
elif self.upsampler == 'pixelshuffledirect':
|
818 |
+
# for lightweight SR (to save parameters)
|
819 |
+
self.upsample = UpsampleOneStep(upscale, embed_dim, num_out_ch,
|
820 |
+
(img_size, img_size))
|
821 |
+
|
822 |
+
self.apply(self._init_weights)
|
823 |
+
|
824 |
+
def _init_weights(self, m):
|
825 |
+
if isinstance(m, nn.Linear):
|
826 |
+
trunc_normal_(m.weight, std=.02)
|
827 |
+
if isinstance(m, nn.Linear) and m.bias is not None:
|
828 |
+
nn.init.constant_(m.bias, 0)
|
829 |
+
elif isinstance(m, (nn.LayerNorm, nn.BatchNorm2d, nn.GroupNorm, nn.InstanceNorm2d)):
|
830 |
+
nn.init.constant_(m.bias, 0)
|
831 |
+
nn.init.constant_(m.weight, 1.0)
|
832 |
+
|
833 |
+
def forward_features(self, x):
|
834 |
+
_, _, H, W = x.shape
|
835 |
+
x_size = [H, W]
|
836 |
+
x = self.before_RG(x)
|
837 |
+
for layer in self.layers:
|
838 |
+
x = layer(x, x_size)
|
839 |
+
x = self.norm(x)
|
840 |
+
x = rearrange(x, "b (h w) c -> b c h w", h=H, w=W)
|
841 |
+
|
842 |
+
return x
|
843 |
+
|
844 |
+
def forward(self, x):
|
845 |
+
"""
|
846 |
+
Input: x: (B, C, H, W)
|
847 |
+
"""
|
848 |
+
self.mean = self.mean.type_as(x)
|
849 |
+
x = (x - self.mean) * self.img_range
|
850 |
+
|
851 |
+
if self.upsampler == 'pixelshuffle':
|
852 |
+
# for image SR
|
853 |
+
x = self.conv_first(x)
|
854 |
+
x = self.conv_after_body(self.forward_features(x)) + x
|
855 |
+
x = self.conv_before_upsample(x)
|
856 |
+
x = self.conv_last(self.upsample(x))
|
857 |
+
elif self.upsampler == 'pixelshuffledirect':
|
858 |
+
# for lightweight SR
|
859 |
+
x = self.conv_first(x)
|
860 |
+
x = self.conv_after_body(self.forward_features(x)) + x
|
861 |
+
x = self.upsample(x)
|
862 |
+
|
863 |
+
x = x / self.img_range + self.mean
|
864 |
+
return x
|
865 |
+
|
866 |
+
|
867 |
+
if __name__ == '__main__':
|
868 |
+
upscale = 1
|
869 |
+
height = 64
|
870 |
+
width = 64
|
871 |
+
model = DAT(upscale=4,
|
872 |
+
in_chans=3,
|
873 |
+
img_size=64,
|
874 |
+
img_range=1.,
|
875 |
+
depth=[18],
|
876 |
+
embed_dim=60,
|
877 |
+
num_heads=[6],
|
878 |
+
expansion_factor=2,
|
879 |
+
resi_connection='3conv',
|
880 |
+
split_size=[8,32],
|
881 |
+
upsampler='pixelshuffledirect',
|
882 |
+
).cuda().eval()
|
883 |
+
|
884 |
+
print(height, width)
|
885 |
+
|
886 |
+
x = torch.randn((1, 3, height, width)).cuda()
|
887 |
+
x = model(x)
|
888 |
+
|
889 |
+
print(x.shape)
|
test_code/test_utils.py
CHANGED
@@ -7,6 +7,7 @@ sys.path.append(root_path)
|
|
7 |
from opt import opt
|
8 |
from architecture.rrdb import RRDBNet
|
9 |
from architecture.grl import GRL
|
|
|
10 |
from architecture.swinir import SwinIR
|
11 |
from architecture.cunet import UNet_Full
|
12 |
|
@@ -173,4 +174,47 @@ def load_grl(generator_weight_PATH, scale=4):
|
|
173 |
print(f"Number of parameters {num_params / 10 ** 6: 0.2f}")
|
174 |
|
175 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
176 |
return generator
|
|
|
7 |
from opt import opt
|
8 |
from architecture.rrdb import RRDBNet
|
9 |
from architecture.grl import GRL
|
10 |
+
from architecture.dat import DAT
|
11 |
from architecture.swinir import SwinIR
|
12 |
from architecture.cunet import UNet_Full
|
13 |
|
|
|
174 |
print(f"Number of parameters {num_params / 10 ** 6: 0.2f}")
|
175 |
|
176 |
|
177 |
+
return generator
|
178 |
+
|
179 |
+
|
180 |
+
|
181 |
+
def load_dat(generator_weight_PATH, scale=4):
|
182 |
+
|
183 |
+
# Load the checkpoint
|
184 |
+
checkpoint_g = torch.load(generator_weight_PATH)
|
185 |
+
|
186 |
+
# Find the generator weight
|
187 |
+
if 'model_state_dict' in checkpoint_g:
|
188 |
+
weight = checkpoint_g['model_state_dict']
|
189 |
+
|
190 |
+
# DAT small model in default
|
191 |
+
generator = DAT(upscale = 4,
|
192 |
+
in_chans = 3,
|
193 |
+
img_size = 64,
|
194 |
+
img_range = 1.,
|
195 |
+
depth = [6, 6, 6, 6, 6, 6],
|
196 |
+
embed_dim = 180,
|
197 |
+
num_heads = [6, 6, 6, 6, 6, 6],
|
198 |
+
expansion_factor = 2,
|
199 |
+
resi_connection = '1conv',
|
200 |
+
split_size = [8, 16],
|
201 |
+
upsampler = 'pixelshuffledirect',
|
202 |
+
).cuda()
|
203 |
+
|
204 |
+
else:
|
205 |
+
print("This weight is not supported")
|
206 |
+
os._exit(0)
|
207 |
+
|
208 |
+
|
209 |
+
generator.load_state_dict(weight)
|
210 |
+
generator = generator.eval().cuda()
|
211 |
+
|
212 |
+
|
213 |
+
num_params = 0
|
214 |
+
for p in generator.parameters():
|
215 |
+
if p.requires_grad:
|
216 |
+
num_params += p.numel()
|
217 |
+
print(f"Number of parameters {num_params / 10 ** 6: 0.2f}")
|
218 |
+
|
219 |
+
|
220 |
return generator
|