白鹭先生
commited on
Commit
•
98068b3
1
Parent(s):
dcd7456
新增依赖文档
Browse files- app.py +3 -2
- models/SwinIR.py +928 -0
- models/resnest/__init__.py +2 -0
- models/resnest/ablation.py +106 -0
- models/resnest/resnest.py +60 -0
- models/resnest/resnet.py +310 -0
- models/resnest/splat.py +99 -0
- requirements.txt +11 -0
app.py
CHANGED
@@ -2,10 +2,11 @@
|
|
2 |
Author: Egrt
|
3 |
Date: 2022-01-13 13:34:10
|
4 |
LastEditors: [egrt]
|
5 |
-
LastEditTime: 2022-05-04 12:
|
6 |
FilePath: \MaskGAN\app.py
|
7 |
'''
|
8 |
-
|
|
|
9 |
from PIL import Image
|
10 |
from maskgan import MASKGAN
|
11 |
import gradio as gr
|
|
|
2 |
Author: Egrt
|
3 |
Date: 2022-01-13 13:34:10
|
4 |
LastEditors: [egrt]
|
5 |
+
LastEditTime: 2022-05-04 12:59:41
|
6 |
FilePath: \MaskGAN\app.py
|
7 |
'''
|
8 |
+
import os
|
9 |
+
os.system('pip install requirements.txt')
|
10 |
from PIL import Image
|
11 |
from maskgan import MASKGAN
|
12 |
import gradio as gr
|
models/SwinIR.py
ADDED
@@ -0,0 +1,928 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
|
8 |
+
import torch
|
9 |
+
import torch.nn as nn
|
10 |
+
import torch.nn.functional as F
|
11 |
+
import torch.utils.checkpoint as checkpoint
|
12 |
+
from timm.models.layers import DropPath, to_2tuple, trunc_normal_
|
13 |
+
|
14 |
+
|
15 |
+
class Mlp(nn.Module):
|
16 |
+
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
|
17 |
+
super().__init__()
|
18 |
+
out_features = out_features or in_features
|
19 |
+
hidden_features = hidden_features or in_features
|
20 |
+
self.fc1 = nn.Linear(in_features, hidden_features)
|
21 |
+
self.act = act_layer()
|
22 |
+
self.fc2 = nn.Linear(hidden_features, out_features)
|
23 |
+
self.drop = nn.Dropout(drop)
|
24 |
+
|
25 |
+
def forward(self, x):
|
26 |
+
x = self.fc1(x)
|
27 |
+
x = self.act(x)
|
28 |
+
x = self.drop(x)
|
29 |
+
x = self.fc2(x)
|
30 |
+
x = self.drop(x)
|
31 |
+
return x
|
32 |
+
|
33 |
+
|
34 |
+
def window_partition(x, window_size):
|
35 |
+
"""
|
36 |
+
Args:
|
37 |
+
x: (B, H, W, C)
|
38 |
+
window_size (int): window size
|
39 |
+
|
40 |
+
Returns:
|
41 |
+
windows: (num_windows*B, window_size, window_size, C)
|
42 |
+
"""
|
43 |
+
B, H, W, C = x.shape
|
44 |
+
x = x.view(B, H // window_size, window_size, W // window_size, window_size, C)
|
45 |
+
windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
|
46 |
+
return windows
|
47 |
+
|
48 |
+
|
49 |
+
def window_reverse(windows, window_size, H, W):
|
50 |
+
"""
|
51 |
+
Args:
|
52 |
+
windows: (num_windows*B, window_size, window_size, C)
|
53 |
+
window_size (int): Window size
|
54 |
+
H (int): Height of image
|
55 |
+
W (int): Width of image
|
56 |
+
|
57 |
+
Returns:
|
58 |
+
x: (B, H, W, C)
|
59 |
+
"""
|
60 |
+
B = int(windows.shape[0] / (H * W / window_size / window_size))
|
61 |
+
x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1)
|
62 |
+
x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)
|
63 |
+
return x
|
64 |
+
|
65 |
+
|
66 |
+
class WindowAttention(nn.Module):
|
67 |
+
r""" Window based multi-head self attention (W-MSA) module with relative position bias.
|
68 |
+
It supports both of shifted and non-shifted window.
|
69 |
+
|
70 |
+
Args:
|
71 |
+
dim (int): Number of input channels.
|
72 |
+
window_size (tuple[int]): The height and width of the window.
|
73 |
+
num_heads (int): Number of attention heads.
|
74 |
+
qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
|
75 |
+
qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set
|
76 |
+
attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
|
77 |
+
proj_drop (float, optional): Dropout ratio of output. Default: 0.0
|
78 |
+
"""
|
79 |
+
|
80 |
+
def __init__(self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0., proj_drop=0.):
|
81 |
+
|
82 |
+
super().__init__()
|
83 |
+
self.dim = dim
|
84 |
+
self.window_size = window_size # Wh, Ww
|
85 |
+
self.num_heads = num_heads
|
86 |
+
head_dim = dim // num_heads
|
87 |
+
self.scale = qk_scale or head_dim ** -0.5
|
88 |
+
|
89 |
+
# define a parameter table of relative position bias
|
90 |
+
self.relative_position_bias_table = nn.Parameter(
|
91 |
+
torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)) # 2*Wh-1 * 2*Ww-1, nH
|
92 |
+
|
93 |
+
# get pair-wise relative position index for each token inside the window
|
94 |
+
coords_h = torch.arange(self.window_size[0])
|
95 |
+
coords_w = torch.arange(self.window_size[1])
|
96 |
+
coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
|
97 |
+
coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
|
98 |
+
relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
|
99 |
+
relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
|
100 |
+
relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0
|
101 |
+
relative_coords[:, :, 1] += self.window_size[1] - 1
|
102 |
+
relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
|
103 |
+
relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
|
104 |
+
self.register_buffer("relative_position_index", relative_position_index)
|
105 |
+
|
106 |
+
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
|
107 |
+
self.attn_drop = nn.Dropout(attn_drop)
|
108 |
+
self.proj = nn.Linear(dim, dim)
|
109 |
+
|
110 |
+
self.proj_drop = nn.Dropout(proj_drop)
|
111 |
+
|
112 |
+
trunc_normal_(self.relative_position_bias_table, std=.02)
|
113 |
+
self.softmax = nn.Softmax(dim=-1)
|
114 |
+
|
115 |
+
def forward(self, x, mask=None):
|
116 |
+
"""
|
117 |
+
Args:
|
118 |
+
x: input features with shape of (num_windows*B, N, C)
|
119 |
+
mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None
|
120 |
+
"""
|
121 |
+
B_, N, C = x.shape
|
122 |
+
qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
|
123 |
+
q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
|
124 |
+
|
125 |
+
q = q * self.scale
|
126 |
+
attn = (q @ k.transpose(-2, -1))
|
127 |
+
|
128 |
+
relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(
|
129 |
+
self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1) # Wh*Ww,Wh*Ww,nH
|
130 |
+
relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
|
131 |
+
attn = attn + relative_position_bias.unsqueeze(0)
|
132 |
+
|
133 |
+
if mask is not None:
|
134 |
+
nW = mask.shape[0]
|
135 |
+
attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0)
|
136 |
+
attn = attn.view(-1, self.num_heads, N, N)
|
137 |
+
attn = self.softmax(attn)
|
138 |
+
else:
|
139 |
+
attn = self.softmax(attn)
|
140 |
+
|
141 |
+
attn = self.attn_drop(attn)
|
142 |
+
|
143 |
+
x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
|
144 |
+
x = self.proj(x)
|
145 |
+
x = self.proj_drop(x)
|
146 |
+
return x
|
147 |
+
|
148 |
+
def extra_repr(self) -> str:
|
149 |
+
return f'dim={self.dim}, window_size={self.window_size}, num_heads={self.num_heads}'
|
150 |
+
|
151 |
+
def flops(self, N):
|
152 |
+
# calculate flops for 1 window with token length of N
|
153 |
+
flops = 0
|
154 |
+
# qkv = self.qkv(x)
|
155 |
+
flops += N * self.dim * 3 * self.dim
|
156 |
+
# attn = (q @ k.transpose(-2, -1))
|
157 |
+
flops += self.num_heads * N * (self.dim // self.num_heads) * N
|
158 |
+
# x = (attn @ v)
|
159 |
+
flops += self.num_heads * N * N * (self.dim // self.num_heads)
|
160 |
+
# x = self.proj(x)
|
161 |
+
flops += N * self.dim * self.dim
|
162 |
+
return flops
|
163 |
+
|
164 |
+
|
165 |
+
class SwinTransformerBlock(nn.Module):
|
166 |
+
r""" Swin Transformer Block.
|
167 |
+
|
168 |
+
Args:
|
169 |
+
dim (int): Number of input channels.
|
170 |
+
input_resolution (tuple[int]): Input resulotion.
|
171 |
+
num_heads (int): Number of attention heads.
|
172 |
+
window_size (int): Window size.
|
173 |
+
shift_size (int): Shift size for SW-MSA.
|
174 |
+
mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
|
175 |
+
qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
|
176 |
+
qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
|
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 |
+
"""
|
183 |
+
|
184 |
+
def __init__(self, dim, input_resolution, num_heads, window_size=7, shift_size=0,
|
185 |
+
mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0.,
|
186 |
+
act_layer=nn.GELU, norm_layer=nn.LayerNorm):
|
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 |
+
|
200 |
+
self.norm1 = norm_layer(dim)
|
201 |
+
self.attn = WindowAttention(
|
202 |
+
dim, window_size=to_2tuple(self.window_size), num_heads=num_heads,
|
203 |
+
qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
|
204 |
+
|
205 |
+
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
|
206 |
+
self.norm2 = norm_layer(dim)
|
207 |
+
mlp_hidden_dim = int(dim * mlp_ratio)
|
208 |
+
self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
|
209 |
+
|
210 |
+
if self.shift_size > 0:
|
211 |
+
attn_mask = self.calculate_mask(self.input_resolution)
|
212 |
+
else:
|
213 |
+
attn_mask = None
|
214 |
+
|
215 |
+
self.register_buffer("attn_mask", attn_mask)
|
216 |
+
|
217 |
+
def calculate_mask(self, x_size):
|
218 |
+
# calculate attention mask for SW-MSA
|
219 |
+
H, W = x_size
|
220 |
+
img_mask = torch.zeros((1, H, W, 1)) # 1 H W 1
|
221 |
+
h_slices = (slice(0, -self.window_size),
|
222 |
+
slice(-self.window_size, -self.shift_size),
|
223 |
+
slice(-self.shift_size, None))
|
224 |
+
w_slices = (slice(0, -self.window_size),
|
225 |
+
slice(-self.window_size, -self.shift_size),
|
226 |
+
slice(-self.shift_size, None))
|
227 |
+
cnt = 0
|
228 |
+
for h in h_slices:
|
229 |
+
for w in w_slices:
|
230 |
+
img_mask[:, h, w, :] = cnt
|
231 |
+
cnt += 1
|
232 |
+
|
233 |
+
mask_windows = window_partition(img_mask, self.window_size) # nW, window_size, window_size, 1
|
234 |
+
mask_windows = mask_windows.view(-1, self.window_size * self.window_size)
|
235 |
+
attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
|
236 |
+
attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0))
|
237 |
+
|
238 |
+
return attn_mask
|
239 |
+
|
240 |
+
def forward(self, x, x_size):
|
241 |
+
H, W = x_size
|
242 |
+
B, L, C = x.shape
|
243 |
+
# assert L == H * W, "input feature has wrong size"
|
244 |
+
|
245 |
+
shortcut = x
|
246 |
+
x = self.norm1(x)
|
247 |
+
x = x.view(B, H, W, C)
|
248 |
+
|
249 |
+
# cyclic shift
|
250 |
+
if self.shift_size > 0:
|
251 |
+
shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
|
252 |
+
else:
|
253 |
+
shifted_x = x
|
254 |
+
|
255 |
+
# partition windows
|
256 |
+
x_windows = window_partition(shifted_x, self.window_size) # nW*B, window_size, window_size, C
|
257 |
+
x_windows = x_windows.view(-1, self.window_size * self.window_size, C) # nW*B, window_size*window_size, C
|
258 |
+
|
259 |
+
# W-MSA/SW-MSA (to be compatible for testing on images whose shapes are the multiple of window size
|
260 |
+
if self.input_resolution == x_size:
|
261 |
+
attn_windows = self.attn(x_windows, mask=self.attn_mask) # nW*B, window_size*window_size, C
|
262 |
+
else:
|
263 |
+
attn_windows = self.attn(x_windows, mask=self.calculate_mask(x_size).to(x.device))
|
264 |
+
|
265 |
+
# merge windows
|
266 |
+
attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C)
|
267 |
+
shifted_x = window_reverse(attn_windows, self.window_size, H, W) # B H' W' C
|
268 |
+
|
269 |
+
# reverse cyclic shift
|
270 |
+
if self.shift_size > 0:
|
271 |
+
x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
|
272 |
+
else:
|
273 |
+
x = shifted_x
|
274 |
+
x = x.view(B, H * W, C)
|
275 |
+
|
276 |
+
# FFN
|
277 |
+
x = shortcut + self.drop_path(x)
|
278 |
+
x = x + self.drop_path(self.mlp(self.norm2(x)))
|
279 |
+
|
280 |
+
return x
|
281 |
+
|
282 |
+
def extra_repr(self) -> str:
|
283 |
+
return f"dim={self.dim}, input_resolution={self.input_resolution}, num_heads={self.num_heads}, " \
|
284 |
+
f"window_size={self.window_size}, shift_size={self.shift_size}, mlp_ratio={self.mlp_ratio}"
|
285 |
+
|
286 |
+
def flops(self):
|
287 |
+
flops = 0
|
288 |
+
H, W = self.input_resolution
|
289 |
+
# norm1
|
290 |
+
flops += self.dim * H * W
|
291 |
+
# W-MSA/SW-MSA
|
292 |
+
nW = H * W / self.window_size / self.window_size
|
293 |
+
flops += nW * self.attn.flops(self.window_size * self.window_size)
|
294 |
+
# mlp
|
295 |
+
flops += 2 * H * W * self.dim * self.dim * self.mlp_ratio
|
296 |
+
# norm2
|
297 |
+
flops += self.dim * H * W
|
298 |
+
return flops
|
299 |
+
|
300 |
+
|
301 |
+
class PatchMerging(nn.Module):
|
302 |
+
r""" Patch Merging Layer.
|
303 |
+
|
304 |
+
Args:
|
305 |
+
input_resolution (tuple[int]): Resolution of input feature.
|
306 |
+
dim (int): Number of input channels.
|
307 |
+
norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
|
308 |
+
"""
|
309 |
+
|
310 |
+
def __init__(self, input_resolution, dim, norm_layer=nn.LayerNorm):
|
311 |
+
super().__init__()
|
312 |
+
self.input_resolution = input_resolution
|
313 |
+
self.dim = dim
|
314 |
+
self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
|
315 |
+
self.norm = norm_layer(4 * dim)
|
316 |
+
|
317 |
+
def forward(self, x):
|
318 |
+
"""
|
319 |
+
x: B, H*W, C
|
320 |
+
"""
|
321 |
+
H, W = self.input_resolution
|
322 |
+
B, L, C = x.shape
|
323 |
+
assert L == H * W, "input feature has wrong size"
|
324 |
+
assert H % 2 == 0 and W % 2 == 0, f"x size ({H}*{W}) are not even."
|
325 |
+
|
326 |
+
x = x.view(B, H, W, C)
|
327 |
+
|
328 |
+
x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C
|
329 |
+
x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C
|
330 |
+
x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C
|
331 |
+
x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C
|
332 |
+
x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C
|
333 |
+
x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C
|
334 |
+
|
335 |
+
x = self.norm(x)
|
336 |
+
x = self.reduction(x)
|
337 |
+
|
338 |
+
return x
|
339 |
+
|
340 |
+
def extra_repr(self) -> str:
|
341 |
+
return f"input_resolution={self.input_resolution}, dim={self.dim}"
|
342 |
+
|
343 |
+
def flops(self):
|
344 |
+
H, W = self.input_resolution
|
345 |
+
flops = H * W * self.dim
|
346 |
+
flops += (H // 2) * (W // 2) * 4 * self.dim * 2 * self.dim
|
347 |
+
return flops
|
348 |
+
|
349 |
+
|
350 |
+
class BasicLayer(nn.Module):
|
351 |
+
""" A basic Swin Transformer layer for one stage.
|
352 |
+
|
353 |
+
Args:
|
354 |
+
dim (int): Number of input channels.
|
355 |
+
input_resolution (tuple[int]): Input resolution.
|
356 |
+
depth (int): Number of blocks.
|
357 |
+
num_heads (int): Number of attention heads.
|
358 |
+
window_size (int): Local window size.
|
359 |
+
mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
|
360 |
+
qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
|
361 |
+
qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
|
362 |
+
drop (float, optional): Dropout rate. Default: 0.0
|
363 |
+
attn_drop (float, optional): Attention dropout rate. Default: 0.0
|
364 |
+
drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
|
365 |
+
norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
|
366 |
+
downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
|
367 |
+
use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
|
368 |
+
"""
|
369 |
+
|
370 |
+
def __init__(self, dim, input_resolution, depth, num_heads, window_size,
|
371 |
+
mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0.,
|
372 |
+
drop_path=0., norm_layer=nn.LayerNorm, downsample=None, use_checkpoint=False):
|
373 |
+
|
374 |
+
super().__init__()
|
375 |
+
self.dim = dim
|
376 |
+
self.input_resolution = input_resolution
|
377 |
+
self.depth = depth
|
378 |
+
self.use_checkpoint = use_checkpoint
|
379 |
+
|
380 |
+
# build blocks
|
381 |
+
self.blocks = nn.ModuleList([
|
382 |
+
SwinTransformerBlock(dim=dim, input_resolution=input_resolution,
|
383 |
+
num_heads=num_heads, window_size=window_size,
|
384 |
+
shift_size=0 if (i % 2 == 0) else window_size // 2,
|
385 |
+
mlp_ratio=mlp_ratio,
|
386 |
+
qkv_bias=qkv_bias, qk_scale=qk_scale,
|
387 |
+
drop=drop, attn_drop=attn_drop,
|
388 |
+
drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,
|
389 |
+
norm_layer=norm_layer)
|
390 |
+
for i in range(depth)])
|
391 |
+
|
392 |
+
# patch merging layer
|
393 |
+
if downsample is not None:
|
394 |
+
self.downsample = downsample(input_resolution, dim=dim, norm_layer=norm_layer)
|
395 |
+
else:
|
396 |
+
self.downsample = None
|
397 |
+
|
398 |
+
def forward(self, x, x_size):
|
399 |
+
for blk in self.blocks:
|
400 |
+
if self.use_checkpoint:
|
401 |
+
x = checkpoint.checkpoint(blk, x, x_size)
|
402 |
+
else:
|
403 |
+
x = blk(x, x_size)
|
404 |
+
if self.downsample is not None:
|
405 |
+
x = self.downsample(x)
|
406 |
+
return x
|
407 |
+
|
408 |
+
def extra_repr(self) -> str:
|
409 |
+
return f"dim={self.dim}, input_resolution={self.input_resolution}, depth={self.depth}"
|
410 |
+
|
411 |
+
def flops(self):
|
412 |
+
flops = 0
|
413 |
+
for blk in self.blocks:
|
414 |
+
flops += blk.flops()
|
415 |
+
if self.downsample is not None:
|
416 |
+
flops += self.downsample.flops()
|
417 |
+
return flops
|
418 |
+
|
419 |
+
|
420 |
+
class RSTB(nn.Module):
|
421 |
+
"""Residual Swin Transformer Block (RSTB).
|
422 |
+
|
423 |
+
Args:
|
424 |
+
dim (int): Number of input channels.
|
425 |
+
input_resolution (tuple[int]): Input resolution.
|
426 |
+
depth (int): Number of blocks.
|
427 |
+
num_heads (int): Number of attention heads.
|
428 |
+
window_size (int): Local window size.
|
429 |
+
mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
|
430 |
+
qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
|
431 |
+
qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
|
432 |
+
drop (float, optional): Dropout rate. Default: 0.0
|
433 |
+
attn_drop (float, optional): Attention dropout rate. Default: 0.0
|
434 |
+
drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
|
435 |
+
norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
|
436 |
+
downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
|
437 |
+
use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
|
438 |
+
img_size: Input image size.
|
439 |
+
patch_size: Patch size.
|
440 |
+
resi_connection: The convolutional block before residual connection.
|
441 |
+
"""
|
442 |
+
|
443 |
+
def __init__(self, dim, input_resolution, depth, num_heads, window_size,
|
444 |
+
mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0.,
|
445 |
+
drop_path=0., norm_layer=nn.LayerNorm, downsample=None, use_checkpoint=False,
|
446 |
+
img_size=224, patch_size=4, resi_connection='1conv'):
|
447 |
+
super(RSTB, self).__init__()
|
448 |
+
|
449 |
+
self.dim = dim
|
450 |
+
self.input_resolution = input_resolution
|
451 |
+
|
452 |
+
self.residual_group = BasicLayer(dim=dim,
|
453 |
+
input_resolution=input_resolution,
|
454 |
+
depth=depth,
|
455 |
+
num_heads=num_heads,
|
456 |
+
window_size=window_size,
|
457 |
+
mlp_ratio=mlp_ratio,
|
458 |
+
qkv_bias=qkv_bias, qk_scale=qk_scale,
|
459 |
+
drop=drop, attn_drop=attn_drop,
|
460 |
+
drop_path=drop_path,
|
461 |
+
norm_layer=norm_layer,
|
462 |
+
downsample=downsample,
|
463 |
+
use_checkpoint=use_checkpoint)
|
464 |
+
|
465 |
+
if resi_connection == '1conv':
|
466 |
+
self.conv = nn.Conv2d(dim, dim, 3, 1, 1)
|
467 |
+
elif resi_connection == '3conv':
|
468 |
+
# to save parameters and memory
|
469 |
+
self.conv = nn.Sequential(nn.Conv2d(dim, dim // 4, 3, 1, 1), nn.GELU(),
|
470 |
+
nn.Conv2d(dim // 4, dim // 4, 1, 1, 0),
|
471 |
+
nn.GELU(),
|
472 |
+
nn.Conv2d(dim // 4, dim, 3, 1, 1))
|
473 |
+
|
474 |
+
self.patch_embed = PatchEmbed(
|
475 |
+
img_size=img_size, patch_size=patch_size, in_chans=0, embed_dim=dim,
|
476 |
+
norm_layer=None)
|
477 |
+
|
478 |
+
self.patch_unembed = PatchUnEmbed(
|
479 |
+
img_size=img_size, patch_size=patch_size, in_chans=0, embed_dim=dim,
|
480 |
+
norm_layer=None)
|
481 |
+
|
482 |
+
def forward(self, x, x_size):
|
483 |
+
return self.patch_embed(self.conv(self.patch_unembed(self.residual_group(x, x_size), x_size))) + x
|
484 |
+
|
485 |
+
def flops(self):
|
486 |
+
flops = 0
|
487 |
+
flops += self.residual_group.flops()
|
488 |
+
H, W = self.input_resolution
|
489 |
+
flops += H * W * self.dim * self.dim * 9
|
490 |
+
flops += self.patch_embed.flops()
|
491 |
+
flops += self.patch_unembed.flops()
|
492 |
+
|
493 |
+
return flops
|
494 |
+
|
495 |
+
|
496 |
+
class PatchEmbed(nn.Module):
|
497 |
+
r""" Image to Patch Embedding
|
498 |
+
|
499 |
+
Args:
|
500 |
+
img_size (int): Image size. Default: 224.
|
501 |
+
patch_size (int): Patch token size. Default: 4.
|
502 |
+
in_chans (int): Number of input image channels. Default: 3.
|
503 |
+
embed_dim (int): Number of linear projection output channels. Default: 96.
|
504 |
+
norm_layer (nn.Module, optional): Normalization layer. Default: None
|
505 |
+
"""
|
506 |
+
|
507 |
+
def __init__(self, img_size=224, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None):
|
508 |
+
super().__init__()
|
509 |
+
img_size = to_2tuple(img_size)
|
510 |
+
patch_size = to_2tuple(patch_size)
|
511 |
+
patches_resolution = [img_size[0] // patch_size[0], img_size[1] // patch_size[1]]
|
512 |
+
self.img_size = img_size
|
513 |
+
self.patch_size = patch_size
|
514 |
+
self.patches_resolution = patches_resolution
|
515 |
+
self.num_patches = patches_resolution[0] * patches_resolution[1]
|
516 |
+
|
517 |
+
self.in_chans = in_chans
|
518 |
+
self.embed_dim = embed_dim
|
519 |
+
|
520 |
+
if norm_layer is not None:
|
521 |
+
self.norm = norm_layer(embed_dim)
|
522 |
+
else:
|
523 |
+
self.norm = None
|
524 |
+
|
525 |
+
def forward(self, x):
|
526 |
+
x = x.flatten(2).transpose(1, 2) # B Ph*Pw C
|
527 |
+
if self.norm is not None:
|
528 |
+
x = self.norm(x)
|
529 |
+
return x
|
530 |
+
|
531 |
+
def flops(self):
|
532 |
+
flops = 0
|
533 |
+
H, W = self.img_size
|
534 |
+
if self.norm is not None:
|
535 |
+
flops += H * W * self.embed_dim
|
536 |
+
return flops
|
537 |
+
|
538 |
+
|
539 |
+
class PatchUnEmbed(nn.Module):
|
540 |
+
r""" Image to Patch Unembedding
|
541 |
+
|
542 |
+
Args:
|
543 |
+
img_size (int): Image size. Default: 224.
|
544 |
+
patch_size (int): Patch token size. Default: 4.
|
545 |
+
in_chans (int): Number of input image channels. Default: 3.
|
546 |
+
embed_dim (int): Number of linear projection output channels. Default: 96.
|
547 |
+
norm_layer (nn.Module, optional): Normalization layer. Default: None
|
548 |
+
"""
|
549 |
+
|
550 |
+
def __init__(self, img_size=224, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None):
|
551 |
+
super().__init__()
|
552 |
+
img_size = to_2tuple(img_size)
|
553 |
+
patch_size = to_2tuple(patch_size)
|
554 |
+
patches_resolution = [img_size[0] // patch_size[0], img_size[1] // patch_size[1]]
|
555 |
+
self.img_size = img_size
|
556 |
+
self.patch_size = patch_size
|
557 |
+
self.patches_resolution = patches_resolution
|
558 |
+
self.num_patches = patches_resolution[0] * patches_resolution[1]
|
559 |
+
|
560 |
+
self.in_chans = in_chans
|
561 |
+
self.embed_dim = embed_dim
|
562 |
+
|
563 |
+
def forward(self, x, x_size):
|
564 |
+
B, HW, C = x.shape
|
565 |
+
x = x.transpose(1, 2).view(B, self.embed_dim, x_size[0], x_size[1]) # B Ph*Pw C
|
566 |
+
return x
|
567 |
+
|
568 |
+
def flops(self):
|
569 |
+
flops = 0
|
570 |
+
return flops
|
571 |
+
|
572 |
+
|
573 |
+
class Upsample(nn.Sequential):
|
574 |
+
"""Upsample module.
|
575 |
+
|
576 |
+
Args:
|
577 |
+
scale (int): Scale factor. Supported scales: 2^n and 3.
|
578 |
+
num_feat (int): Channel number of intermediate features.
|
579 |
+
"""
|
580 |
+
|
581 |
+
def __init__(self, scale, num_feat):
|
582 |
+
m = []
|
583 |
+
if (scale & (scale - 1)) == 0: # scale = 2^n
|
584 |
+
for _ in range(int(math.log(scale, 2))):
|
585 |
+
m.append(nn.Conv2d(num_feat, 4 * num_feat, 3, 1, 1))
|
586 |
+
m.append(nn.PixelShuffle(2))
|
587 |
+
elif scale == 3:
|
588 |
+
m.append(nn.Conv2d(num_feat, 9 * num_feat, 3, 1, 1))
|
589 |
+
m.append(nn.PixelShuffle(3))
|
590 |
+
else:
|
591 |
+
raise ValueError(f'scale {scale} is not supported. ' 'Supported scales: 2^n and 3.')
|
592 |
+
super(Upsample, self).__init__(*m)
|
593 |
+
|
594 |
+
|
595 |
+
class UpsampleOneStep(nn.Sequential):
|
596 |
+
"""UpsampleOneStep module (the difference with Upsample is that it always only has 1conv + 1pixelshuffle)
|
597 |
+
Used in lightweight SR to save parameters.
|
598 |
+
|
599 |
+
Args:
|
600 |
+
scale (int): Scale factor. Supported scales: 2^n and 3.
|
601 |
+
num_feat (int): Channel number of intermediate features.
|
602 |
+
|
603 |
+
"""
|
604 |
+
|
605 |
+
def __init__(self, scale, num_feat, num_out_ch, input_resolution=None):
|
606 |
+
self.num_feat = num_feat
|
607 |
+
self.input_resolution = input_resolution
|
608 |
+
m = []
|
609 |
+
m.append(nn.Conv2d(num_feat, (scale ** 2) * num_out_ch, 3, 1, 1))
|
610 |
+
m.append(nn.PixelShuffle(scale))
|
611 |
+
super(UpsampleOneStep, self).__init__(*m)
|
612 |
+
|
613 |
+
def flops(self):
|
614 |
+
H, W = self.input_resolution
|
615 |
+
flops = H * W * self.num_feat * 3 * 9
|
616 |
+
return flops
|
617 |
+
|
618 |
+
|
619 |
+
class Generator(nn.Module):
|
620 |
+
r""" SwinIR
|
621 |
+
A PyTorch impl of : `SwinIR: Image Restoration Using Swin Transformer`, based on Swin Transformer.
|
622 |
+
|
623 |
+
Args:
|
624 |
+
img_size (int | tuple(int)): Input image size. Default 64
|
625 |
+
patch_size (int | tuple(int)): Patch size. Default: 1
|
626 |
+
in_chans (int): Number of input image channels. Default: 3
|
627 |
+
embed_dim (int): Patch embedding dimension. Default: 96
|
628 |
+
depths (tuple(int)): Depth of each Swin Transformer layer.
|
629 |
+
num_heads (tuple(int)): Number of attention heads in different layers.
|
630 |
+
window_size (int): Window size. Default: 7
|
631 |
+
mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4
|
632 |
+
qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True
|
633 |
+
qk_scale (float): Override default qk scale of head_dim ** -0.5 if set. Default: None
|
634 |
+
drop_rate (float): Dropout rate. Default: 0
|
635 |
+
attn_drop_rate (float): Attention dropout rate. Default: 0
|
636 |
+
drop_path_rate (float): Stochastic depth rate. Default: 0.1
|
637 |
+
norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm.
|
638 |
+
ape (bool): If True, add absolute position embedding to the patch embedding. Default: False
|
639 |
+
patch_norm (bool): If True, add normalization after patch embedding. Default: True
|
640 |
+
use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False
|
641 |
+
upscale: Upscale factor. 2/3/4/8 for image SR, 1 for denoising and compress artifact reduction
|
642 |
+
img_range: Image range. 1. or 255.
|
643 |
+
upsampler: The reconstruction reconstruction module. 'pixelshuffle'/'pixelshuffledirect'/'nearest+conv'/None
|
644 |
+
resi_connection: The convolutional block before residual connection. '1conv'/'3conv'
|
645 |
+
"""
|
646 |
+
|
647 |
+
def __init__(self, img_size=64, patch_size=1, in_chans=3,
|
648 |
+
embed_dim=96, depths=[6, 6, 6, 6], num_heads=[6, 6, 6, 6],
|
649 |
+
window_size=7, mlp_ratio=4., qkv_bias=True, qk_scale=None,
|
650 |
+
drop_rate=0., attn_drop_rate=0., drop_path_rate=0.1,
|
651 |
+
norm_layer=nn.LayerNorm, ape=False, patch_norm=True,
|
652 |
+
use_checkpoint=False, upscale=2, img_range=1., upsampler='', resi_connection='1conv',
|
653 |
+
**kwargs):
|
654 |
+
super(Generator, self).__init__()
|
655 |
+
num_in_ch = in_chans
|
656 |
+
num_out_ch = in_chans
|
657 |
+
num_feat = 64
|
658 |
+
self.img_range = img_range
|
659 |
+
if in_chans == 3:
|
660 |
+
rgb_mean = (0.4488, 0.4371, 0.4040)
|
661 |
+
self.mean = torch.Tensor(rgb_mean).view(1, 3, 1, 1)
|
662 |
+
else:
|
663 |
+
self.mean = torch.zeros(1, 1, 1, 1)
|
664 |
+
self.upscale = upscale
|
665 |
+
self.upsampler = upsampler
|
666 |
+
self.window_size = window_size
|
667 |
+
|
668 |
+
#####################################################################################################
|
669 |
+
################################### 1, shallow feature extraction ###################################
|
670 |
+
self.conv_first = nn.Conv2d(num_in_ch, embed_dim, 3, 1, 1)
|
671 |
+
|
672 |
+
#####################################################################################################
|
673 |
+
################################### 2, deep feature extraction ######################################
|
674 |
+
self.num_layers = len(depths)
|
675 |
+
self.embed_dim = embed_dim
|
676 |
+
self.ape = ape
|
677 |
+
self.patch_norm = patch_norm
|
678 |
+
self.num_features = embed_dim
|
679 |
+
self.mlp_ratio = mlp_ratio
|
680 |
+
|
681 |
+
# split image into non-overlapping patches
|
682 |
+
self.patch_embed = PatchEmbed(
|
683 |
+
img_size=img_size, patch_size=patch_size, in_chans=embed_dim, embed_dim=embed_dim,
|
684 |
+
norm_layer=norm_layer if self.patch_norm else None)
|
685 |
+
num_patches = self.patch_embed.num_patches
|
686 |
+
patches_resolution = self.patch_embed.patches_resolution
|
687 |
+
self.patches_resolution = patches_resolution
|
688 |
+
|
689 |
+
# merge non-overlapping patches into image
|
690 |
+
self.patch_unembed = PatchUnEmbed(
|
691 |
+
img_size=img_size, patch_size=patch_size, in_chans=embed_dim, embed_dim=embed_dim,
|
692 |
+
norm_layer=norm_layer if self.patch_norm else None)
|
693 |
+
|
694 |
+
# absolute position embedding
|
695 |
+
if self.ape:
|
696 |
+
self.absolute_pos_embed = nn.Parameter(torch.zeros(1, num_patches, embed_dim))
|
697 |
+
trunc_normal_(self.absolute_pos_embed, std=.02)
|
698 |
+
|
699 |
+
self.pos_drop = nn.Dropout(p=drop_rate)
|
700 |
+
|
701 |
+
# stochastic depth
|
702 |
+
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule
|
703 |
+
|
704 |
+
# build Residual Swin Transformer blocks (RSTB)
|
705 |
+
self.layers = nn.ModuleList()
|
706 |
+
for i_layer in range(self.num_layers):
|
707 |
+
layer = RSTB(dim=embed_dim,
|
708 |
+
input_resolution=(patches_resolution[0],
|
709 |
+
patches_resolution[1]),
|
710 |
+
depth=depths[i_layer],
|
711 |
+
num_heads=num_heads[i_layer],
|
712 |
+
window_size=window_size,
|
713 |
+
mlp_ratio=self.mlp_ratio,
|
714 |
+
qkv_bias=qkv_bias, qk_scale=qk_scale,
|
715 |
+
drop=drop_rate, attn_drop=attn_drop_rate,
|
716 |
+
drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])], # no impact on SR results
|
717 |
+
norm_layer=norm_layer,
|
718 |
+
downsample=None,
|
719 |
+
use_checkpoint=use_checkpoint,
|
720 |
+
img_size=img_size,
|
721 |
+
patch_size=patch_size,
|
722 |
+
resi_connection=resi_connection
|
723 |
+
|
724 |
+
)
|
725 |
+
self.layers.append(layer)
|
726 |
+
self.norm = norm_layer(self.num_features)
|
727 |
+
|
728 |
+
# build the last conv layer in deep feature extraction
|
729 |
+
if resi_connection == '1conv':
|
730 |
+
self.conv_after_body = nn.Conv2d(embed_dim, embed_dim, 3, 1, 1)
|
731 |
+
elif resi_connection == '3conv':
|
732 |
+
# to save parameters and memory
|
733 |
+
self.conv_after_body = nn.Sequential(nn.Conv2d(embed_dim, embed_dim // 4, 3, 1, 1),
|
734 |
+
nn.GELU(),
|
735 |
+
nn.Conv2d(embed_dim // 4, embed_dim // 4, 1, 1, 0),
|
736 |
+
nn.GELU(),
|
737 |
+
nn.Conv2d(embed_dim // 4, embed_dim, 3, 1, 1))
|
738 |
+
|
739 |
+
#####################################################################################################
|
740 |
+
################################ 3, high quality image reconstruction ################################
|
741 |
+
if self.upsampler == 'pixelshuffle':
|
742 |
+
# for classical SR
|
743 |
+
self.conv_before_upsample = nn.Sequential(nn.Conv2d(embed_dim, num_feat, 3, 1, 1),
|
744 |
+
nn.GELU())
|
745 |
+
self.upsample = Upsample(upscale, num_feat)
|
746 |
+
self.conv_last = nn.Conv2d(num_feat, num_out_ch, 3, 1, 1)
|
747 |
+
elif self.upsampler == 'pixelshuffledirect':
|
748 |
+
# for lightweight SR (to save parameters)
|
749 |
+
self.upsample = UpsampleOneStep(upscale, embed_dim, num_out_ch,
|
750 |
+
(patches_resolution[0], patches_resolution[1]))
|
751 |
+
elif self.upsampler == 'nearest+conv':
|
752 |
+
# for real-world SR (less artifacts)
|
753 |
+
assert self.upscale == 4, 'only support x4 now.'
|
754 |
+
self.conv_before_upsample = nn.Sequential(nn.Conv2d(embed_dim, num_feat, 3, 1, 1),
|
755 |
+
nn.GELU())
|
756 |
+
self.conv_up1 = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
|
757 |
+
self.conv_up2 = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
|
758 |
+
self.conv_hr = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
|
759 |
+
self.conv_last = nn.Conv2d(num_feat, num_out_ch, 3, 1, 1)
|
760 |
+
self.lrelu = nn.GELU()
|
761 |
+
else:
|
762 |
+
# for image denoising and JPEG compression artifact reduction
|
763 |
+
self.conv_last = nn.Conv2d(embed_dim, num_out_ch, 3, 1, 1)
|
764 |
+
|
765 |
+
self.apply(self._init_weights)
|
766 |
+
|
767 |
+
def _init_weights(self, m):
|
768 |
+
if isinstance(m, nn.Linear):
|
769 |
+
trunc_normal_(m.weight, std=.02)
|
770 |
+
if isinstance(m, nn.Linear) and m.bias is not None:
|
771 |
+
nn.init.constant_(m.bias, 0)
|
772 |
+
elif isinstance(m, nn.LayerNorm):
|
773 |
+
nn.init.constant_(m.bias, 0)
|
774 |
+
nn.init.constant_(m.weight, 1.0)
|
775 |
+
|
776 |
+
@torch.jit.ignore
|
777 |
+
def no_weight_decay(self):
|
778 |
+
return {'absolute_pos_embed'}
|
779 |
+
|
780 |
+
@torch.jit.ignore
|
781 |
+
def no_weight_decay_keywords(self):
|
782 |
+
return {'relative_position_bias_table'}
|
783 |
+
|
784 |
+
def check_image_size(self, x):
|
785 |
+
_, _, h, w = x.size()
|
786 |
+
mod_pad_h = (self.window_size - h % self.window_size) % self.window_size
|
787 |
+
mod_pad_w = (self.window_size - w % self.window_size) % self.window_size
|
788 |
+
x = F.pad(x, (0, mod_pad_w, 0, mod_pad_h), 'reflect')
|
789 |
+
return x
|
790 |
+
|
791 |
+
def forward_features(self, x):
|
792 |
+
x_size = (x.shape[2], x.shape[3])
|
793 |
+
x = self.patch_embed(x)
|
794 |
+
if self.ape:
|
795 |
+
x = x + self.absolute_pos_embed
|
796 |
+
x = self.pos_drop(x)
|
797 |
+
|
798 |
+
for layer in self.layers:
|
799 |
+
x = layer(x, x_size)
|
800 |
+
|
801 |
+
x = self.norm(x) # B L C
|
802 |
+
x = self.patch_unembed(x, x_size)
|
803 |
+
|
804 |
+
return x
|
805 |
+
|
806 |
+
def forward(self, x):
|
807 |
+
H, W = x.shape[2:]
|
808 |
+
x = self.check_image_size(x)
|
809 |
+
|
810 |
+
self.mean = self.mean.type_as(x)
|
811 |
+
x = (x - self.mean) * self.img_range
|
812 |
+
|
813 |
+
if self.upsampler == 'pixelshuffle':
|
814 |
+
# for classical SR
|
815 |
+
x = self.conv_first(x)
|
816 |
+
x = self.conv_after_body(self.forward_features(x)) + x
|
817 |
+
x = self.conv_before_upsample(x)
|
818 |
+
x = self.conv_last(self.upsample(x))
|
819 |
+
elif self.upsampler == 'pixelshuffledirect':
|
820 |
+
# for lightweight SR
|
821 |
+
x = self.conv_first(x)
|
822 |
+
x = self.conv_after_body(self.forward_features(x)) + x
|
823 |
+
x = self.upsample(x)
|
824 |
+
elif self.upsampler == 'nearest+conv':
|
825 |
+
# for real-world SR
|
826 |
+
x = self.conv_first(x)
|
827 |
+
x = self.conv_after_body(self.forward_features(x)) + x
|
828 |
+
x = self.conv_before_upsample(x)
|
829 |
+
x = self.lrelu(self.conv_up1(torch.nn.functional.interpolate(x, scale_factor=2, mode='nearest')))
|
830 |
+
x = self.lrelu(self.conv_up2(torch.nn.functional.interpolate(x, scale_factor=2, mode='nearest')))
|
831 |
+
x = self.conv_last(self.lrelu(self.conv_hr(x)))
|
832 |
+
else:
|
833 |
+
# for image denoising and JPEG compression artifact reduction
|
834 |
+
x_first = self.conv_first(x)
|
835 |
+
res = self.conv_after_body(self.forward_features(x_first)) + x_first
|
836 |
+
x = x + self.conv_last(res)
|
837 |
+
|
838 |
+
x = x / self.img_range + self.mean
|
839 |
+
|
840 |
+
return x[:, :, :H*self.upscale, :W*self.upscale]
|
841 |
+
|
842 |
+
def flops(self):
|
843 |
+
flops = 0
|
844 |
+
H, W = self.patches_resolution
|
845 |
+
flops += H * W * 3 * self.embed_dim * 9
|
846 |
+
flops += self.patch_embed.flops()
|
847 |
+
for i, layer in enumerate(self.layers):
|
848 |
+
flops += layer.flops()
|
849 |
+
flops += H * W * 3 * self.embed_dim * self.embed_dim
|
850 |
+
flops += self.upsample.flops()
|
851 |
+
return flops
|
852 |
+
|
853 |
+
|
854 |
+
class Discriminator(nn.Module):
|
855 |
+
def __init__(self):
|
856 |
+
super(Discriminator, self).__init__()
|
857 |
+
self.net = nn.Sequential(
|
858 |
+
nn.Conv2d(3, 64, kernel_size=3, padding=1),
|
859 |
+
nn.GELU(),
|
860 |
+
|
861 |
+
nn.Conv2d(64, 64, kernel_size=3, stride=2, padding=1),
|
862 |
+
nn.GELU(),
|
863 |
+
|
864 |
+
nn.Conv2d(64, 128, kernel_size=3, padding=1),
|
865 |
+
nn.GELU(),
|
866 |
+
|
867 |
+
nn.Conv2d(128, 128, kernel_size=3, stride=2, padding=1),
|
868 |
+
nn.GELU(),
|
869 |
+
|
870 |
+
nn.Conv2d(128, 256, kernel_size=3, padding=1),
|
871 |
+
nn.GELU(),
|
872 |
+
|
873 |
+
nn.Conv2d(256, 256, kernel_size=3, stride=2, padding=1),
|
874 |
+
nn.GELU(),
|
875 |
+
|
876 |
+
nn.Conv2d(256, 512, kernel_size=3, padding=1),
|
877 |
+
nn.GELU(),
|
878 |
+
|
879 |
+
nn.Conv2d(512, 512, kernel_size=3, stride=2, padding=1),
|
880 |
+
nn.GELU(),
|
881 |
+
|
882 |
+
nn.AdaptiveAvgPool2d(1),
|
883 |
+
nn.Conv2d(512, 1024, kernel_size=1),
|
884 |
+
nn.GELU(),
|
885 |
+
nn.Conv2d(1024, 1, kernel_size=1)
|
886 |
+
)
|
887 |
+
|
888 |
+
def forward(self, x):
|
889 |
+
batch_size = x.size(0)
|
890 |
+
return self.net(x).view(batch_size)
|
891 |
+
|
892 |
+
def compute_gradient_penalty(D, real_samples, fake_samples):
|
893 |
+
alpha = torch.randn(real_samples.size(0), 1, 1, 1)
|
894 |
+
if torch.cuda.is_available():
|
895 |
+
alpha = alpha.cuda()
|
896 |
+
|
897 |
+
interpolates = (alpha * real_samples + ((1 - alpha) * fake_samples)).requires_grad_(True)
|
898 |
+
d_interpolates = D(interpolates)
|
899 |
+
fake = torch.ones(d_interpolates.size())
|
900 |
+
if torch.cuda.is_available():
|
901 |
+
fake = fake.cuda()
|
902 |
+
|
903 |
+
gradients = torch.autograd.grad(
|
904 |
+
outputs=d_interpolates,
|
905 |
+
inputs=interpolates,
|
906 |
+
grad_outputs=fake,
|
907 |
+
create_graph=True,
|
908 |
+
retain_graph=True,
|
909 |
+
only_inputs=True,
|
910 |
+
)[0]
|
911 |
+
gradients = gradients.view(gradients.size(0), -1)
|
912 |
+
gradient_penalty = ((gradients.norm(2, dim=1) - 1) ** 2).mean()
|
913 |
+
return gradient_penalty
|
914 |
+
|
915 |
+
if __name__ == '__main__':
|
916 |
+
upscale = 4
|
917 |
+
window_size = 7
|
918 |
+
height = (112 // upscale // window_size + 1) * window_size
|
919 |
+
width = (112 // upscale // window_size + 1) * window_size
|
920 |
+
model = Generator(upscale=upscale, img_size=(height, width),
|
921 |
+
window_size=window_size, img_range=1., depths=[6, 6, 6, 6],
|
922 |
+
embed_dim=60, num_heads=[6, 6, 6, 6], mlp_ratio=4, upsampler='nearest+conv')
|
923 |
+
print(model)
|
924 |
+
# print(height, width, model.flops() / 1e9)
|
925 |
+
|
926 |
+
x = torch.randn((1, 3, height, width))
|
927 |
+
x = model(x)
|
928 |
+
print(x.shape)
|
models/resnest/__init__.py
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
from .resnest import *
|
2 |
+
from .ablation import *
|
models/resnest/ablation.py
ADDED
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
2 |
+
## Created by: Hang Zhang
|
3 |
+
## Email: zhanghang0704@gmail.com
|
4 |
+
## Copyright (c) 2020
|
5 |
+
##
|
6 |
+
## LICENSE file in the root directory of this source tree
|
7 |
+
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
8 |
+
"""ResNeSt ablation study models"""
|
9 |
+
|
10 |
+
import torch
|
11 |
+
from .resnet import ResNet, Bottleneck
|
12 |
+
|
13 |
+
__all__ = ['resnest50_fast_1s1x64d', 'resnest50_fast_2s1x64d', 'resnest50_fast_4s1x64d',
|
14 |
+
'resnest50_fast_1s2x40d', 'resnest50_fast_2s2x40d', 'resnest50_fast_4s2x40d',
|
15 |
+
'resnest50_fast_1s4x24d']
|
16 |
+
|
17 |
+
_url_format = 'https://s3.us-west-1.wasabisys.com/resnest/torch/{}-{}.pth'
|
18 |
+
|
19 |
+
_model_sha256 = {name: checksum for checksum, name in [
|
20 |
+
('d8fbf808', 'resnest50_fast_1s1x64d'),
|
21 |
+
('44938639', 'resnest50_fast_2s1x64d'),
|
22 |
+
('f74f3fc3', 'resnest50_fast_4s1x64d'),
|
23 |
+
('32830b84', 'resnest50_fast_1s2x40d'),
|
24 |
+
('9d126481', 'resnest50_fast_2s2x40d'),
|
25 |
+
('41d14ed0', 'resnest50_fast_4s2x40d'),
|
26 |
+
('d4a4f76f', 'resnest50_fast_1s4x24d'),
|
27 |
+
]}
|
28 |
+
|
29 |
+
def short_hash(name):
|
30 |
+
if name not in _model_sha256:
|
31 |
+
raise ValueError('Pretrained model for {name} is not available.'.format(name=name))
|
32 |
+
return _model_sha256[name][:8]
|
33 |
+
|
34 |
+
resnest_model_urls = {name: _url_format.format(name, short_hash(name)) for
|
35 |
+
name in _model_sha256.keys()
|
36 |
+
}
|
37 |
+
|
38 |
+
def resnest50_fast_1s1x64d(pretrained=False, root='~/.encoding/models', **kwargs):
|
39 |
+
model = ResNet(Bottleneck, [3, 4, 6, 3],
|
40 |
+
radix=1, groups=1, bottleneck_width=64,
|
41 |
+
deep_stem=True, stem_width=32, avg_down=True,
|
42 |
+
avd=True, avd_first=True, **kwargs)
|
43 |
+
if pretrained:
|
44 |
+
model.load_state_dict(torch.hub.load_state_dict_from_url(
|
45 |
+
resnest_model_urls['resnest50_fast_1s1x64d'], progress=True, check_hash=True))
|
46 |
+
return model
|
47 |
+
|
48 |
+
def resnest50_fast_2s1x64d(pretrained=False, root='~/.encoding/models', **kwargs):
|
49 |
+
model = ResNet(Bottleneck, [3, 4, 6, 3],
|
50 |
+
radix=2, groups=1, bottleneck_width=64,
|
51 |
+
deep_stem=True, stem_width=32, avg_down=True,
|
52 |
+
avd=True, avd_first=True, **kwargs)
|
53 |
+
if pretrained:
|
54 |
+
model.load_state_dict(torch.hub.load_state_dict_from_url(
|
55 |
+
resnest_model_urls['resnest50_fast_2s1x64d'], progress=True, check_hash=True))
|
56 |
+
return model
|
57 |
+
|
58 |
+
def resnest50_fast_4s1x64d(pretrained=False, root='~/.encoding/models', **kwargs):
|
59 |
+
model = ResNet(Bottleneck, [3, 4, 6, 3],
|
60 |
+
radix=4, groups=1, bottleneck_width=64,
|
61 |
+
deep_stem=True, stem_width=32, avg_down=True,
|
62 |
+
avd=True, avd_first=True, **kwargs)
|
63 |
+
if pretrained:
|
64 |
+
model.load_state_dict(torch.hub.load_state_dict_from_url(
|
65 |
+
resnest_model_urls['resnest50_fast_4s1x64d'], progress=True, check_hash=True))
|
66 |
+
return model
|
67 |
+
|
68 |
+
def resnest50_fast_1s2x40d(pretrained=False, root='~/.encoding/models', **kwargs):
|
69 |
+
model = ResNet(Bottleneck, [3, 4, 6, 3],
|
70 |
+
radix=1, groups=2, bottleneck_width=40,
|
71 |
+
deep_stem=True, stem_width=32, avg_down=True,
|
72 |
+
avd=True, avd_first=True, **kwargs)
|
73 |
+
if pretrained:
|
74 |
+
model.load_state_dict(torch.hub.load_state_dict_from_url(
|
75 |
+
resnest_model_urls['resnest50_fast_1s2x40d'], progress=True, check_hash=True))
|
76 |
+
return model
|
77 |
+
|
78 |
+
def resnest50_fast_2s2x40d(pretrained=False, root='~/.encoding/models', **kwargs):
|
79 |
+
model = ResNet(Bottleneck, [3, 4, 6, 3],
|
80 |
+
radix=2, groups=2, bottleneck_width=40,
|
81 |
+
deep_stem=True, stem_width=32, avg_down=True,
|
82 |
+
avd=True, avd_first=True, **kwargs)
|
83 |
+
if pretrained:
|
84 |
+
model.load_state_dict(torch.hub.load_state_dict_from_url(
|
85 |
+
resnest_model_urls['resnest50_fast_2s2x40d'], progress=True, check_hash=True))
|
86 |
+
return model
|
87 |
+
|
88 |
+
def resnest50_fast_4s2x40d(pretrained=False, root='~/.encoding/models', **kwargs):
|
89 |
+
model = ResNet(Bottleneck, [3, 4, 6, 3],
|
90 |
+
radix=4, groups=2, bottleneck_width=40,
|
91 |
+
deep_stem=True, stem_width=32, avg_down=True,
|
92 |
+
avd=True, avd_first=True, **kwargs)
|
93 |
+
if pretrained:
|
94 |
+
model.load_state_dict(torch.hub.load_state_dict_from_url(
|
95 |
+
resnest_model_urls['resnest50_fast_4s2x40d'], progress=True, check_hash=True))
|
96 |
+
return model
|
97 |
+
|
98 |
+
def resnest50_fast_1s4x24d(pretrained=False, root='~/.encoding/models', **kwargs):
|
99 |
+
model = ResNet(Bottleneck, [3, 4, 6, 3],
|
100 |
+
radix=1, groups=4, bottleneck_width=24,
|
101 |
+
deep_stem=True, stem_width=32, avg_down=True,
|
102 |
+
avd=True, avd_first=True, **kwargs)
|
103 |
+
if pretrained:
|
104 |
+
model.load_state_dict(torch.hub.load_state_dict_from_url(
|
105 |
+
resnest_model_urls['resnest50_fast_1s4x24d'], progress=True, check_hash=True))
|
106 |
+
return model
|
models/resnest/resnest.py
ADDED
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
@author: Jun Wang
|
3 |
+
@date: 20210301
|
4 |
+
@contact: jun21wangustc@gmail.com
|
5 |
+
"""
|
6 |
+
|
7 |
+
# based on:
|
8 |
+
# https://github.com/zhanghang1989/ResNeSt/blob/master/resnest/torch/resnest.py
|
9 |
+
|
10 |
+
import torch
|
11 |
+
import torch.nn as nn
|
12 |
+
from .resnet import ResNet, Bottleneck
|
13 |
+
|
14 |
+
class Flatten(nn.Module):
|
15 |
+
def forward(self, input):
|
16 |
+
return input.view(input.size(0), -1)
|
17 |
+
|
18 |
+
def l2_norm(input,axis=1):
|
19 |
+
norm = torch.norm(input,2,axis,True)
|
20 |
+
output = torch.div(input, norm)
|
21 |
+
return output
|
22 |
+
|
23 |
+
class ResNeSt(nn.Module):
|
24 |
+
def __init__(self, num_layers=50, drop_ratio=0.4, feat_dim=512, out_h=7, out_w=7):
|
25 |
+
super(ResNeSt, self).__init__()
|
26 |
+
self.input_layer = nn.Sequential(nn.Conv2d(3, 64, (3, 3), 1, 1 ,bias=False),
|
27 |
+
nn.BatchNorm2d(64),
|
28 |
+
nn.PReLU(64))
|
29 |
+
self.output_layer = nn.Sequential(nn.BatchNorm2d(2048),
|
30 |
+
nn.Dropout(drop_ratio),
|
31 |
+
Flatten(),
|
32 |
+
nn.Linear(2048 * out_h * out_w, feat_dim),
|
33 |
+
nn.BatchNorm1d(feat_dim))
|
34 |
+
if num_layers == 50:
|
35 |
+
self.body = ResNet(Bottleneck, [3, 4, 6, 3],
|
36 |
+
radix=2, groups=1, bottleneck_width=64,
|
37 |
+
deep_stem=True, stem_width=32, avg_down=True,
|
38 |
+
avd=True, avd_first=False)
|
39 |
+
elif num_layers == 101:
|
40 |
+
self.body = ResNet(Bottleneck, [3, 4, 23, 3],
|
41 |
+
radix=2, groups=1, bottleneck_width=64,
|
42 |
+
deep_stem=True, stem_width=64, avg_down=True,
|
43 |
+
avd=True, avd_first=False)
|
44 |
+
elif num_layers == 200:
|
45 |
+
self.body = ResNet(Bottleneck, [3, 24, 36, 3],
|
46 |
+
radix=2, groups=1, bottleneck_width=64,
|
47 |
+
deep_stem=True, stem_width=64, avg_down=True,
|
48 |
+
avd=True, avd_first=False)
|
49 |
+
elif num_layers == 269:
|
50 |
+
self.body = ResNet(Bottleneck, [3, 30, 48, 8],
|
51 |
+
radix=2, groups=1, bottleneck_width=64,
|
52 |
+
deep_stem=True, stem_width=64, avg_down=True,
|
53 |
+
avd=True, avd_first=False)
|
54 |
+
else:
|
55 |
+
pass
|
56 |
+
def forward(self, x):
|
57 |
+
x = self.input_layer(x)
|
58 |
+
x = self.body(x)
|
59 |
+
x = self.output_layer(x)
|
60 |
+
return l2_norm(x)
|
models/resnest/resnet.py
ADDED
@@ -0,0 +1,310 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
2 |
+
## Created by: Hang Zhang
|
3 |
+
## Email: zhanghang0704@gmail.com
|
4 |
+
## Copyright (c) 2020
|
5 |
+
##
|
6 |
+
## LICENSE file in the root directory of this source tree
|
7 |
+
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
8 |
+
"""ResNet variants"""
|
9 |
+
import math
|
10 |
+
import torch
|
11 |
+
import torch.nn as nn
|
12 |
+
|
13 |
+
from .splat import SplAtConv2d
|
14 |
+
|
15 |
+
__all__ = ['ResNet', 'Bottleneck']
|
16 |
+
|
17 |
+
class DropBlock2D(object):
|
18 |
+
def __init__(self, *args, **kwargs):
|
19 |
+
raise NotImplementedError
|
20 |
+
|
21 |
+
class GlobalAvgPool2d(nn.Module):
|
22 |
+
def __init__(self):
|
23 |
+
"""Global average pooling over the input's spatial dimensions"""
|
24 |
+
super(GlobalAvgPool2d, self).__init__()
|
25 |
+
|
26 |
+
def forward(self, inputs):
|
27 |
+
return nn.functional.adaptive_avg_pool2d(inputs, 1).view(inputs.size(0), -1)
|
28 |
+
|
29 |
+
class Bottleneck(nn.Module):
|
30 |
+
"""ResNet Bottleneck
|
31 |
+
"""
|
32 |
+
# pylint: disable=unused-argument
|
33 |
+
expansion = 4
|
34 |
+
def __init__(self, inplanes, planes, stride=1, downsample=None,
|
35 |
+
radix=1, cardinality=1, bottleneck_width=64,
|
36 |
+
avd=False, avd_first=False, dilation=1, is_first=False,
|
37 |
+
rectified_conv=False, rectify_avg=False,
|
38 |
+
norm_layer=None, dropblock_prob=0.0, last_gamma=False):
|
39 |
+
super(Bottleneck, self).__init__()
|
40 |
+
group_width = int(planes * (bottleneck_width / 64.)) * cardinality
|
41 |
+
self.conv1 = nn.Conv2d(inplanes, group_width, kernel_size=1, bias=False)
|
42 |
+
self.bn1 = norm_layer(group_width)
|
43 |
+
self.dropblock_prob = dropblock_prob
|
44 |
+
self.radix = radix
|
45 |
+
self.avd = avd and (stride > 1 or is_first)
|
46 |
+
self.avd_first = avd_first
|
47 |
+
|
48 |
+
if self.avd:
|
49 |
+
self.avd_layer = nn.AvgPool2d(3, stride, padding=1)
|
50 |
+
stride = 1
|
51 |
+
|
52 |
+
if dropblock_prob > 0.0:
|
53 |
+
self.dropblock1 = DropBlock2D(dropblock_prob, 3)
|
54 |
+
if radix == 1:
|
55 |
+
self.dropblock2 = DropBlock2D(dropblock_prob, 3)
|
56 |
+
self.dropblock3 = DropBlock2D(dropblock_prob, 3)
|
57 |
+
|
58 |
+
if radix >= 1:
|
59 |
+
self.conv2 = SplAtConv2d(
|
60 |
+
group_width, group_width, kernel_size=3,
|
61 |
+
stride=stride, padding=dilation,
|
62 |
+
dilation=dilation, groups=cardinality, bias=False,
|
63 |
+
radix=radix, rectify=rectified_conv,
|
64 |
+
rectify_avg=rectify_avg,
|
65 |
+
norm_layer=norm_layer,
|
66 |
+
dropblock_prob=dropblock_prob)
|
67 |
+
elif rectified_conv:
|
68 |
+
from rfconv import RFConv2d
|
69 |
+
self.conv2 = RFConv2d(
|
70 |
+
group_width, group_width, kernel_size=3, stride=stride,
|
71 |
+
padding=dilation, dilation=dilation,
|
72 |
+
groups=cardinality, bias=False,
|
73 |
+
average_mode=rectify_avg)
|
74 |
+
self.bn2 = norm_layer(group_width)
|
75 |
+
else:
|
76 |
+
self.conv2 = nn.Conv2d(
|
77 |
+
group_width, group_width, kernel_size=3, stride=stride,
|
78 |
+
padding=dilation, dilation=dilation,
|
79 |
+
groups=cardinality, bias=False)
|
80 |
+
self.bn2 = norm_layer(group_width)
|
81 |
+
|
82 |
+
self.conv3 = nn.Conv2d(
|
83 |
+
group_width, planes * 4, kernel_size=1, bias=False)
|
84 |
+
self.bn3 = norm_layer(planes*4)
|
85 |
+
|
86 |
+
if last_gamma:
|
87 |
+
from torch.nn.init import zeros_
|
88 |
+
zeros_(self.bn3.weight)
|
89 |
+
self.relu = nn.ReLU(inplace=True)
|
90 |
+
self.downsample = downsample
|
91 |
+
self.dilation = dilation
|
92 |
+
self.stride = stride
|
93 |
+
|
94 |
+
def forward(self, x):
|
95 |
+
residual = x
|
96 |
+
|
97 |
+
out = self.conv1(x)
|
98 |
+
out = self.bn1(out)
|
99 |
+
if self.dropblock_prob > 0.0:
|
100 |
+
out = self.dropblock1(out)
|
101 |
+
out = self.relu(out)
|
102 |
+
|
103 |
+
if self.avd and self.avd_first:
|
104 |
+
out = self.avd_layer(out)
|
105 |
+
|
106 |
+
out = self.conv2(out)
|
107 |
+
if self.radix == 0:
|
108 |
+
out = self.bn2(out)
|
109 |
+
if self.dropblock_prob > 0.0:
|
110 |
+
out = self.dropblock2(out)
|
111 |
+
out = self.relu(out)
|
112 |
+
|
113 |
+
if self.avd and not self.avd_first:
|
114 |
+
out = self.avd_layer(out)
|
115 |
+
|
116 |
+
out = self.conv3(out)
|
117 |
+
out = self.bn3(out)
|
118 |
+
if self.dropblock_prob > 0.0:
|
119 |
+
out = self.dropblock3(out)
|
120 |
+
|
121 |
+
if self.downsample is not None:
|
122 |
+
residual = self.downsample(x)
|
123 |
+
|
124 |
+
out += residual
|
125 |
+
out = self.relu(out)
|
126 |
+
|
127 |
+
return out
|
128 |
+
|
129 |
+
class ResNet(nn.Module):
|
130 |
+
"""ResNet Variants
|
131 |
+
|
132 |
+
Parameters
|
133 |
+
----------
|
134 |
+
block : Block
|
135 |
+
Class for the residual block. Options are BasicBlockV1, BottleneckV1.
|
136 |
+
layers : list of int
|
137 |
+
Numbers of layers in each block
|
138 |
+
classes : int, default 1000
|
139 |
+
Number of classification classes.
|
140 |
+
dilated : bool, default False
|
141 |
+
Applying dilation strategy to pretrained ResNet yielding a stride-8 model,
|
142 |
+
typically used in Semantic Segmentation.
|
143 |
+
norm_layer : object
|
144 |
+
Normalization layer used in backbone network (default: :class:`mxnet.gluon.nn.BatchNorm`;
|
145 |
+
for Synchronized Cross-GPU BachNormalization).
|
146 |
+
|
147 |
+
Reference:
|
148 |
+
|
149 |
+
- He, Kaiming, et al. "Deep residual learning for image recognition." Proceedings of the IEEE conference on computer vision and pattern recognition. 2016.
|
150 |
+
|
151 |
+
- Yu, Fisher, and Vladlen Koltun. "Multi-scale context aggregation by dilated convolutions."
|
152 |
+
"""
|
153 |
+
# pylint: disable=unused-variable
|
154 |
+
def __init__(self, block, layers, radix=1, groups=1, bottleneck_width=64,
|
155 |
+
num_classes=1000, dilated=False, dilation=1,
|
156 |
+
deep_stem=False, stem_width=64, avg_down=False,
|
157 |
+
rectified_conv=False, rectify_avg=False,
|
158 |
+
avd=False, avd_first=False,
|
159 |
+
final_drop=0.0, dropblock_prob=0,
|
160 |
+
last_gamma=False, norm_layer=nn.BatchNorm2d):
|
161 |
+
self.cardinality = groups
|
162 |
+
self.bottleneck_width = bottleneck_width
|
163 |
+
# ResNet-D params
|
164 |
+
self.inplanes = stem_width*2 if deep_stem else 64
|
165 |
+
self.avg_down = avg_down
|
166 |
+
self.last_gamma = last_gamma
|
167 |
+
# ResNeSt params
|
168 |
+
self.radix = radix
|
169 |
+
self.avd = avd
|
170 |
+
self.avd_first = avd_first
|
171 |
+
|
172 |
+
super(ResNet, self).__init__()
|
173 |
+
self.rectified_conv = rectified_conv
|
174 |
+
self.rectify_avg = rectify_avg
|
175 |
+
if rectified_conv:
|
176 |
+
from rfconv import RFConv2d
|
177 |
+
conv_layer = RFConv2d
|
178 |
+
else:
|
179 |
+
conv_layer = nn.Conv2d
|
180 |
+
conv_kwargs = {'average_mode': rectify_avg} if rectified_conv else {}
|
181 |
+
'''
|
182 |
+
if deep_stem:
|
183 |
+
self.conv1 = nn.Sequential(
|
184 |
+
conv_layer(3, stem_width, kernel_size=3, stride=2, padding=1, bias=False, **conv_kwargs),
|
185 |
+
norm_layer(stem_width),
|
186 |
+
nn.ReLU(inplace=True),
|
187 |
+
conv_layer(stem_width, stem_width, kernel_size=3, stride=1, padding=1, bias=False, **conv_kwargs),
|
188 |
+
norm_layer(stem_width),
|
189 |
+
nn.ReLU(inplace=True),
|
190 |
+
conv_layer(stem_width, stem_width*2, kernel_size=3, stride=1, padding=1, bias=False, **conv_kwargs),
|
191 |
+
)
|
192 |
+
else:
|
193 |
+
self.conv1 = conv_layer(3, 64, kernel_size=7, stride=2, padding=3,
|
194 |
+
bias=False, **conv_kwargs)
|
195 |
+
self.bn1 = norm_layer(self.inplanes)
|
196 |
+
self.relu = nn.ReLU(inplace=True)
|
197 |
+
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
|
198 |
+
'''
|
199 |
+
#self.layer1 = self._make_layer(block, 64, layers[0], norm_layer=norm_layer, is_first=False)
|
200 |
+
self.layer1 = self._make_layer(block, 64, layers[0], stride=2, norm_layer=norm_layer, is_first=False)
|
201 |
+
self.layer2 = self._make_layer(block, 128, layers[1], stride=2, norm_layer=norm_layer)
|
202 |
+
if dilated or dilation == 4:
|
203 |
+
self.layer3 = self._make_layer(block, 256, layers[2], stride=1,
|
204 |
+
dilation=2, norm_layer=norm_layer,
|
205 |
+
dropblock_prob=dropblock_prob)
|
206 |
+
self.layer4 = self._make_layer(block, 512, layers[3], stride=1,
|
207 |
+
dilation=4, norm_layer=norm_layer,
|
208 |
+
dropblock_prob=dropblock_prob)
|
209 |
+
elif dilation==2:
|
210 |
+
self.layer3 = self._make_layer(block, 256, layers[2], stride=2,
|
211 |
+
dilation=1, norm_layer=norm_layer,
|
212 |
+
dropblock_prob=dropblock_prob)
|
213 |
+
self.layer4 = self._make_layer(block, 512, layers[3], stride=1,
|
214 |
+
dilation=2, norm_layer=norm_layer,
|
215 |
+
dropblock_prob=dropblock_prob)
|
216 |
+
else:
|
217 |
+
self.layer3 = self._make_layer(block, 256, layers[2], stride=2,
|
218 |
+
norm_layer=norm_layer,
|
219 |
+
dropblock_prob=dropblock_prob)
|
220 |
+
self.layer4 = self._make_layer(block, 512, layers[3], stride=2,
|
221 |
+
norm_layer=norm_layer,
|
222 |
+
dropblock_prob=dropblock_prob)
|
223 |
+
'''
|
224 |
+
self.avgpool = GlobalAvgPool2d()
|
225 |
+
self.drop = nn.Dropout(final_drop) if final_drop > 0.0 else None
|
226 |
+
self.fc = nn.Linear(512 * block.expansion, num_classes)
|
227 |
+
|
228 |
+
for m in self.modules():
|
229 |
+
if isinstance(m, nn.Conv2d):
|
230 |
+
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
|
231 |
+
m.weight.data.normal_(0, math.sqrt(2. / n))
|
232 |
+
elif isinstance(m, norm_layer):
|
233 |
+
m.weight.data.fill_(1)
|
234 |
+
m.bias.data.zero_()
|
235 |
+
'''
|
236 |
+
def _make_layer(self, block, planes, blocks, stride=1, dilation=1, norm_layer=None,
|
237 |
+
dropblock_prob=0.0, is_first=True):
|
238 |
+
downsample = None
|
239 |
+
if stride != 1 or self.inplanes != planes * block.expansion:
|
240 |
+
down_layers = []
|
241 |
+
if self.avg_down:
|
242 |
+
if dilation == 1:
|
243 |
+
down_layers.append(nn.AvgPool2d(kernel_size=stride, stride=stride,
|
244 |
+
ceil_mode=True, count_include_pad=False))
|
245 |
+
else:
|
246 |
+
down_layers.append(nn.AvgPool2d(kernel_size=1, stride=1,
|
247 |
+
ceil_mode=True, count_include_pad=False))
|
248 |
+
down_layers.append(nn.Conv2d(self.inplanes, planes * block.expansion,
|
249 |
+
kernel_size=1, stride=1, bias=False))
|
250 |
+
else:
|
251 |
+
down_layers.append(nn.Conv2d(self.inplanes, planes * block.expansion,
|
252 |
+
kernel_size=1, stride=stride, bias=False))
|
253 |
+
down_layers.append(norm_layer(planes * block.expansion))
|
254 |
+
downsample = nn.Sequential(*down_layers)
|
255 |
+
|
256 |
+
layers = []
|
257 |
+
if dilation == 1 or dilation == 2:
|
258 |
+
layers.append(block(self.inplanes, planes, stride, downsample=downsample,
|
259 |
+
radix=self.radix, cardinality=self.cardinality,
|
260 |
+
bottleneck_width=self.bottleneck_width,
|
261 |
+
avd=self.avd, avd_first=self.avd_first,
|
262 |
+
dilation=1, is_first=is_first, rectified_conv=self.rectified_conv,
|
263 |
+
rectify_avg=self.rectify_avg,
|
264 |
+
norm_layer=norm_layer, dropblock_prob=dropblock_prob,
|
265 |
+
last_gamma=self.last_gamma))
|
266 |
+
elif dilation == 4:
|
267 |
+
layers.append(block(self.inplanes, planes, stride, downsample=downsample,
|
268 |
+
radix=self.radix, cardinality=self.cardinality,
|
269 |
+
bottleneck_width=self.bottleneck_width,
|
270 |
+
avd=self.avd, avd_first=self.avd_first,
|
271 |
+
dilation=2, is_first=is_first, rectified_conv=self.rectified_conv,
|
272 |
+
rectify_avg=self.rectify_avg,
|
273 |
+
norm_layer=norm_layer, dropblock_prob=dropblock_prob,
|
274 |
+
last_gamma=self.last_gamma))
|
275 |
+
else:
|
276 |
+
raise RuntimeError("=> unknown dilation size: {}".format(dilation))
|
277 |
+
|
278 |
+
self.inplanes = planes * block.expansion
|
279 |
+
for i in range(1, blocks):
|
280 |
+
layers.append(block(self.inplanes, planes,
|
281 |
+
radix=self.radix, cardinality=self.cardinality,
|
282 |
+
bottleneck_width=self.bottleneck_width,
|
283 |
+
avd=self.avd, avd_first=self.avd_first,
|
284 |
+
dilation=dilation, rectified_conv=self.rectified_conv,
|
285 |
+
rectify_avg=self.rectify_avg,
|
286 |
+
norm_layer=norm_layer, dropblock_prob=dropblock_prob,
|
287 |
+
last_gamma=self.last_gamma))
|
288 |
+
|
289 |
+
return nn.Sequential(*layers)
|
290 |
+
|
291 |
+
def forward(self, x):
|
292 |
+
'''
|
293 |
+
x = self.conv1(x)
|
294 |
+
x = self.bn1(x)
|
295 |
+
x = self.relu(x)
|
296 |
+
x = self.maxpool(x)
|
297 |
+
'''
|
298 |
+
x = self.layer1(x)
|
299 |
+
x = self.layer2(x)
|
300 |
+
x = self.layer3(x)
|
301 |
+
x = self.layer4(x)
|
302 |
+
'''
|
303 |
+
x = self.avgpool(x)
|
304 |
+
#x = x.view(x.size(0), -1)
|
305 |
+
x = torch.flatten(x, 1)
|
306 |
+
if self.drop:
|
307 |
+
x = self.drop(x)
|
308 |
+
x = self.fc(x)
|
309 |
+
'''
|
310 |
+
return x
|
models/resnest/splat.py
ADDED
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Split-Attention"""
|
2 |
+
|
3 |
+
import torch
|
4 |
+
from torch import nn
|
5 |
+
import torch.nn.functional as F
|
6 |
+
from torch.nn import Conv2d, Module, Linear, BatchNorm2d, ReLU
|
7 |
+
from torch.nn.modules.utils import _pair
|
8 |
+
|
9 |
+
__all__ = ['SplAtConv2d']
|
10 |
+
|
11 |
+
class SplAtConv2d(Module):
|
12 |
+
"""Split-Attention Conv2d
|
13 |
+
"""
|
14 |
+
def __init__(self, in_channels, channels, kernel_size, stride=(1, 1), padding=(0, 0),
|
15 |
+
dilation=(1, 1), groups=1, bias=True,
|
16 |
+
radix=2, reduction_factor=4,
|
17 |
+
rectify=False, rectify_avg=False, norm_layer=None,
|
18 |
+
dropblock_prob=0.0, **kwargs):
|
19 |
+
super(SplAtConv2d, self).__init__()
|
20 |
+
padding = _pair(padding)
|
21 |
+
self.rectify = rectify and (padding[0] > 0 or padding[1] > 0)
|
22 |
+
self.rectify_avg = rectify_avg
|
23 |
+
inter_channels = max(in_channels*radix//reduction_factor, 32)
|
24 |
+
self.radix = radix
|
25 |
+
self.cardinality = groups
|
26 |
+
self.channels = channels
|
27 |
+
self.dropblock_prob = dropblock_prob
|
28 |
+
if self.rectify:
|
29 |
+
from rfconv import RFConv2d
|
30 |
+
self.conv = RFConv2d(in_channels, channels*radix, kernel_size, stride, padding, dilation,
|
31 |
+
groups=groups*radix, bias=bias, average_mode=rectify_avg, **kwargs)
|
32 |
+
else:
|
33 |
+
self.conv = Conv2d(in_channels, channels*radix, kernel_size, stride, padding, dilation,
|
34 |
+
groups=groups*radix, bias=bias, **kwargs)
|
35 |
+
self.use_bn = norm_layer is not None
|
36 |
+
if self.use_bn:
|
37 |
+
self.bn0 = norm_layer(channels*radix)
|
38 |
+
self.relu = ReLU(inplace=True)
|
39 |
+
self.fc1 = Conv2d(channels, inter_channels, 1, groups=self.cardinality)
|
40 |
+
if self.use_bn:
|
41 |
+
self.bn1 = norm_layer(inter_channels)
|
42 |
+
self.fc2 = Conv2d(inter_channels, channels*radix, 1, groups=self.cardinality)
|
43 |
+
if dropblock_prob > 0.0:
|
44 |
+
self.dropblock = DropBlock2D(dropblock_prob, 3)
|
45 |
+
self.rsoftmax = rSoftMax(radix, groups)
|
46 |
+
|
47 |
+
def forward(self, x):
|
48 |
+
x = self.conv(x)
|
49 |
+
if self.use_bn:
|
50 |
+
x = self.bn0(x)
|
51 |
+
if self.dropblock_prob > 0.0:
|
52 |
+
x = self.dropblock(x)
|
53 |
+
x = self.relu(x)
|
54 |
+
|
55 |
+
batch, rchannel = x.shape[:2]
|
56 |
+
if self.radix > 1:
|
57 |
+
if torch.__version__ < '1.5':
|
58 |
+
splited = torch.split(x, int(rchannel//self.radix), dim=1)
|
59 |
+
else:
|
60 |
+
splited = torch.split(x, rchannel//self.radix, dim=1)
|
61 |
+
gap = sum(splited)
|
62 |
+
else:
|
63 |
+
gap = x
|
64 |
+
gap = F.adaptive_avg_pool2d(gap, 1)
|
65 |
+
gap = self.fc1(gap)
|
66 |
+
|
67 |
+
if self.use_bn:
|
68 |
+
gap = self.bn1(gap)
|
69 |
+
gap = self.relu(gap)
|
70 |
+
|
71 |
+
atten = self.fc2(gap)
|
72 |
+
atten = self.rsoftmax(atten).view(batch, -1, 1, 1)
|
73 |
+
|
74 |
+
if self.radix > 1:
|
75 |
+
if torch.__version__ < '1.5':
|
76 |
+
attens = torch.split(atten, int(rchannel//self.radix), dim=1)
|
77 |
+
else:
|
78 |
+
attens = torch.split(atten, rchannel//self.radix, dim=1)
|
79 |
+
out = sum([att*split for (att, split) in zip(attens, splited)])
|
80 |
+
else:
|
81 |
+
out = atten * x
|
82 |
+
return out.contiguous()
|
83 |
+
|
84 |
+
class rSoftMax(nn.Module):
|
85 |
+
def __init__(self, radix, cardinality):
|
86 |
+
super().__init__()
|
87 |
+
self.radix = radix
|
88 |
+
self.cardinality = cardinality
|
89 |
+
|
90 |
+
def forward(self, x):
|
91 |
+
batch = x.size(0)
|
92 |
+
if self.radix > 1:
|
93 |
+
x = x.view(batch, self.cardinality, self.radix, -1).transpose(1, 2)
|
94 |
+
x = F.softmax(x, dim=1)
|
95 |
+
x = x.reshape(batch, -1)
|
96 |
+
else:
|
97 |
+
x = torch.sigmoid(x)
|
98 |
+
return x
|
99 |
+
|
requirements.txt
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
scipy==1.5.0
|
2 |
+
numpy==1.18.5
|
3 |
+
matplotlib==3.2.2
|
4 |
+
opencv-python==4.5.3.56
|
5 |
+
torch==1.7.0
|
6 |
+
torchvision==0.8.0
|
7 |
+
tqdm==4.47.0
|
8 |
+
Pillow==7.2.0
|
9 |
+
h5py==2.10.0
|
10 |
+
gradio==2.5.3
|
11 |
+
timm==0.4.12
|