Egrt commited on
Commit
95e767b
1 Parent(s): 2669933
.gitignore ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ignore map, miou, datasets
2
+ map_out/
3
+ miou_out/
4
+ VOCdevkit/
5
+ datasets/
6
+ Medical_Datasets/
7
+ lfw/
8
+ logs/
9
+ model_data/
10
+ .temp_map_out/
11
+ results/
12
+
13
+ # Byte-compiled / optimized / DLL files
14
+ __pycache__/
15
+ *.py[cod]
16
+ *$py.class
17
+
18
+ # C extensions
19
+ *.so
20
+
21
+ # Distribution / packaging
22
+ .Python
23
+ build/
24
+ develop-eggs/
25
+ dist/
26
+ downloads/
27
+ eggs/
28
+ .eggs/
29
+ lib/
30
+ lib64/
31
+ parts/
32
+ sdist/
33
+ var/
34
+ wheels/
35
+ pip-wheel-metadata/
36
+ share/python-wheels/
37
+ *.egg-info/
38
+ .installed.cfg
39
+ *.egg
40
+ MANIFEST
41
+
42
+ # PyInstaller
43
+ # Usually these files are written by a python script from a template
44
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
45
+ *.manifest
46
+ *.spec
47
+
48
+ # Installer logs
49
+ pip-log.txt
50
+ pip-delete-this-directory.txt
51
+
52
+ # Unit test / coverage reports
53
+ htmlcov/
54
+ .tox/
55
+ .nox/
56
+ .coverage
57
+ .coverage.*
58
+ .cache
59
+ nosetests.xml
60
+ coverage.xml
61
+ *.cover
62
+ *.py,cover
63
+ .hypothesis/
64
+ .pytest_cache/
65
+
66
+ # Translations
67
+ *.mo
68
+ *.pot
69
+
70
+ # Django stuff:
71
+ *.log
72
+ local_settings.py
73
+ db.sqlite3
74
+ db.sqlite3-journal
75
+
76
+ # Flask stuff:
77
+ instance/
78
+ .webassets-cache
79
+
80
+ # Scrapy stuff:
81
+ .scrapy
82
+
83
+ # Sphinx documentation
84
+ docs/_build/
85
+
86
+ # PyBuilder
87
+ target/
88
+
89
+ # Jupyter Notebook
90
+ .ipynb_checkpoints
91
+
92
+ # IPython
93
+ profile_default/
94
+ ipython_config.py
95
+
96
+ # pyenv
97
+ .python-version
98
+
99
+ # pipenv
100
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
101
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
102
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
103
+ # install all needed dependencies.
104
+ #Pipfile.lock
105
+
106
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow
107
+ __pypackages__/
108
+
109
+ # Celery stuff
110
+ celerybeat-schedule
111
+ celerybeat.pid
112
+
113
+ # SageMath parsed files
114
+ *.sage.py
115
+
116
+ # Environments
117
+ .env
118
+ .venv
119
+ env/
120
+ venv/
121
+ ENV/
122
+ env.bak/
123
+ venv.bak/
124
+
125
+ # Spyder project settings
126
+ .spyderproject
127
+ .spyproject
128
+
129
+ # Rope project settings
130
+ .ropeproject
131
+
132
+ # mkdocs documentation
133
+ /site
134
+
135
+ # mypy
136
+ .mypy_cache/
137
+ .dmypy.json
138
+ dmypy.json
139
+
140
+ # Pyre type checker
141
+ .pyre/
app.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ Author: Egrt
3
+ Date: 2022-01-13 13:34:10
4
+ LastEditors: Egrt
5
+ LastEditTime: 2022-10-17 10:23:29
6
+ FilePath: \MaskGAN\app.py
7
+ '''
8
+ from cyclegan import CYCLEGAN
9
+ import gradio as gr
10
+ import os
11
+ cyclegan = CYCLEGAN()
12
+
13
+ # --------模型推理---------- #
14
+ '''
15
+ description:
16
+ param {*} img 戴眼镜的人脸图片 Image
17
+ return {*} r_image 去遮挡的人脸图片 Image
18
+ '''
19
+ def inference(img):
20
+ r_image = cyclegan.detect_image(img)
21
+ return r_image
22
+
23
+ # --------网页信息---------- #
24
+ title = "融合无监督的戴眼镜遮挡人脸重建"
25
+ description = "使用生成对抗网络对戴眼镜遮挡人脸重建,能够有效地去除眼镜遮挡。 @西南科技大学智能控制与图像处理研究室"
26
+ article = "<p style='text-align: center'>DeMaskGAN: Face Restoration Using Swin Transformer </p>"
27
+ example_img_dir = 'img'
28
+ example_img_name = os.listdir(example_img_dir)
29
+ examples=[os.path.join(example_img_dir, image_path) for image_path in example_img_name if image_path.endswith(('.jpg','.jpeg'))]
30
+ gr.Interface(
31
+ inference,
32
+ gr.inputs.Image(type="pil", label="Input"),
33
+ gr.outputs.Image(type="pil", label="Output"),
34
+ title=title,
35
+ description=description,
36
+ article=article,
37
+ examples=examples
38
+ ).launch()
cyclegan.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ import torch
4
+ from PIL import Image
5
+ from torch import nn
6
+
7
+ from nets.cyclegan import Generator
8
+ from utils.utils import (cvtColor, postprocess_output, preprocess_input,
9
+ resize_image, show_config)
10
+
11
+
12
+ class CYCLEGAN(object):
13
+ _defaults = {
14
+ #-----------------------------------------------#
15
+ # model_path指向logs文件夹下的权值文件
16
+ #-----------------------------------------------#
17
+ "model_path" : 'model_data/G_model_B2A_last_epoch_weights.pth',
18
+ #-----------------------------------------------#
19
+ # 输入图像大小的设置
20
+ #-----------------------------------------------#
21
+ "input_shape" : [112, 112],
22
+ #-------------------------------#
23
+ # 是否进行不失真的resize
24
+ #-------------------------------#
25
+ "letterbox_image" : True,
26
+ #-------------------------------#
27
+ # 是否使用Cuda
28
+ # 没有GPU可以设置成False
29
+ #-------------------------------#
30
+ "cuda" : True,
31
+ }
32
+
33
+ #---------------------------------------------------#
34
+ # 初始化CYCLEGAN
35
+ #---------------------------------------------------#
36
+ def __init__(self, **kwargs):
37
+ self.__dict__.update(self._defaults)
38
+ for name, value in kwargs.items():
39
+ setattr(self, name, value)
40
+ self._defaults[name] = value
41
+ self.generate()
42
+
43
+ show_config(**self._defaults)
44
+
45
+ def generate(self):
46
+ #----------------------------------------#
47
+ # 创建GAN模型
48
+ #----------------------------------------#
49
+ self.net = Generator(upscale=1, img_size=tuple(self.input_shape),
50
+ window_size=7, img_range=1., depths=[3, 3, 3, 3],
51
+ embed_dim=60, num_heads=[3, 3, 3, 3], mlp_ratio=1, upsampler='1conv').eval()
52
+
53
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
54
+ self.net.load_state_dict(torch.load(self.model_path, map_location=device))
55
+ self.net = self.net.eval()
56
+ print('{} model loaded.'.format(self.model_path))
57
+
58
+ if self.cuda:
59
+ self.net = nn.DataParallel(self.net)
60
+ self.net = self.net.cuda()
61
+
62
+ #---------------------------------------------------#
63
+ # 生成1x1的图片
64
+ #---------------------------------------------------#
65
+ def detect_image(self, image):
66
+ #---------------------------------------------------------#
67
+ # 在这里将图像转换成RGB图像,防止灰度图在预测时报错。
68
+ # 代码仅仅支持RGB图像的预测,所有其它类型的图像都会转化成RGB
69
+ #---------------------------------------------------------#
70
+ image = cvtColor(image)
71
+ #---------------------------------------------------#
72
+ # 获得高宽
73
+ #---------------------------------------------------#
74
+ orininal_h = np.array(image).shape[0]
75
+ orininal_w = np.array(image).shape[1]
76
+ #---------------------------------------------------------#
77
+ # 给图像增加灰条,实现不失真的resize
78
+ # 也可以直接resize进行识别
79
+ #---------------------------------------------------------#
80
+ image_data, nw, nh = resize_image(image, (self.input_shape[1],self.input_shape[0]), self.letterbox_image)
81
+ #---------------------------------------------------------#
82
+ # 添加上batch_size维度
83
+ #---------------------------------------------------------#
84
+ image_data = np.expand_dims(np.transpose(preprocess_input(np.array(image_data, dtype='float32')), (2, 0, 1)), 0)
85
+
86
+ with torch.no_grad():
87
+ images = torch.from_numpy(image_data)
88
+ if self.cuda:
89
+ images = images.cuda()
90
+
91
+ #---------------------------------------------------#
92
+ # 图片传入网络进行预测
93
+ #---------------------------------------------------#
94
+ pr = self.net(images)[0]
95
+ #---------------------------------------------------#
96
+ # 转为numpy
97
+ #---------------------------------------------------#
98
+ pr = pr.permute(1, 2, 0).cpu().numpy()
99
+
100
+ #--------------------------------------#
101
+ # 将灰条部分截取掉
102
+ #--------------------------------------#
103
+ if nw is not None:
104
+ pr = pr[int((self.input_shape[0] - nh) // 2) : int((self.input_shape[0] - nh) // 2 + nh), \
105
+ int((self.input_shape[1] - nw) // 2) : int((self.input_shape[1] - nw) // 2 + nw)]
106
+
107
+ #---------------------------------------------------#
108
+ # 进行图片的resize
109
+ #---------------------------------------------------#
110
+ pr = cv2.resize(pr, (orininal_w, orininal_h), interpolation = cv2.INTER_LINEAR)
111
+
112
+ image = postprocess_output(pr)
113
+ image = np.clip(image, 0, 255)
114
+ image = Image.fromarray(np.uint8(image))
115
+
116
+ return image
img/7134850@N05_identity_2@7720949260_0.jpg ADDED
img/7134850@N05_identity_2@7720963358_0.jpg ADDED
img/7134850@N05_identity_2@8978938957_3.jpg ADDED
img/7134850@N05_identity_2@8980174892_1.jpg ADDED
img/7154980@N03_identity_0@2379147786_0.jpg ADDED
img/epoch_14_results.png ADDED
nets/__init__.py ADDED
File without changes
nets/cyclegan.py ADDED
@@ -0,0 +1,923 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, out_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 = out_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
+ self.conv_first = nn.Conv2d(num_in_ch, embed_dim, 3, 1, 1)
669
+
670
+ # -------------深层特征提取------------ #
671
+ self.num_layers = len(depths)
672
+ self.embed_dim = embed_dim
673
+ self.ape = ape
674
+ self.patch_norm = patch_norm
675
+ self.num_features = embed_dim
676
+ self.mlp_ratio = mlp_ratio
677
+
678
+ # -------------将图片划分为不重叠的Patch------------ #
679
+ self.patch_embed = PatchEmbed(
680
+ img_size=img_size, patch_size=patch_size, in_chans=embed_dim, embed_dim=embed_dim,
681
+ norm_layer=norm_layer if self.patch_norm else None)
682
+ num_patches = self.patch_embed.num_patches
683
+ patches_resolution = self.patch_embed.patches_resolution
684
+ self.patches_resolution = patches_resolution
685
+
686
+ # -------------将重叠的Patch进行融合------------ #
687
+ self.patch_unembed = PatchUnEmbed(
688
+ img_size=img_size, patch_size=patch_size, in_chans=embed_dim, embed_dim=embed_dim,
689
+ norm_layer=norm_layer if self.patch_norm else None)
690
+
691
+ # -------------绝对位置编码------------ #
692
+ if self.ape:
693
+ self.absolute_pos_embed = nn.Parameter(torch.zeros(1, num_patches, embed_dim))
694
+ trunc_normal_(self.absolute_pos_embed, std=.02)
695
+
696
+ self.pos_drop = nn.Dropout(p=drop_rate)
697
+
698
+ # stochastic depth
699
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule
700
+
701
+ # build Residual Swin Transformer blocks (RSTB)
702
+ self.layers = nn.ModuleList()
703
+ for i_layer in range(self.num_layers):
704
+ layer = RSTB(dim=embed_dim,
705
+ input_resolution=(patches_resolution[0],
706
+ patches_resolution[1]),
707
+ depth=depths[i_layer],
708
+ num_heads=num_heads[i_layer],
709
+ window_size=window_size,
710
+ mlp_ratio=self.mlp_ratio,
711
+ qkv_bias=qkv_bias, qk_scale=qk_scale,
712
+ drop=drop_rate, attn_drop=attn_drop_rate,
713
+ drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])], # no impact on SR results
714
+ norm_layer=norm_layer,
715
+ downsample=None,
716
+ use_checkpoint=use_checkpoint,
717
+ img_size=img_size,
718
+ patch_size=patch_size,
719
+ resi_connection=resi_connection
720
+
721
+ )
722
+ self.layers.append(layer)
723
+ self.norm = norm_layer(self.num_features)
724
+
725
+ # build the last conv layer in deep feature extraction
726
+ if resi_connection == '1conv':
727
+ self.conv_after_body = nn.Conv2d(embed_dim, embed_dim, 3, 1, 1)
728
+ elif resi_connection == '3conv':
729
+ # to save parameters and memory
730
+ self.conv_after_body = nn.Sequential(nn.Conv2d(embed_dim, embed_dim // 4, 3, 1, 1),
731
+ nn.GELU(),
732
+ nn.Conv2d(embed_dim // 4, embed_dim // 4, 1, 1, 0),
733
+ nn.GELU(),
734
+ nn.Conv2d(embed_dim // 4, embed_dim, 3, 1, 1))
735
+ # -------------超分辨率重建模块------------ #
736
+ if self.upsampler == 'pixelshuffle':
737
+ # for classical SR
738
+ self.conv_before_upsample = nn.Sequential(nn.Conv2d(embed_dim, num_feat, 3, 1, 1),
739
+ nn.GELU())
740
+ self.upsample = Upsample(upscale, num_feat)
741
+ self.conv_last = nn.Conv2d(num_feat, num_out_ch, 3, 1, 1)
742
+ elif self.upsampler == 'pixelshuffledirect':
743
+ # for lightweight SR (to save parameters)
744
+ self.upsample = UpsampleOneStep(upscale, embed_dim, num_out_ch,
745
+ (patches_resolution[0], patches_resolution[1]))
746
+ elif self.upsampler == 'nearest+conv':
747
+ # for real-world SR (less artifacts)
748
+ assert self.upscale == 4, 'only support x4 now.'
749
+ self.conv_before_upsample = nn.Sequential(nn.Conv2d(embed_dim, num_feat, 3, 1, 1),
750
+ nn.GELU())
751
+ self.conv_up1 = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
752
+ self.conv_up2 = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
753
+ self.conv_hr = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
754
+ self.conv_last = nn.Conv2d(num_feat, num_out_ch, 3, 1, 1)
755
+ self.lrelu = nn.GELU()
756
+ else:
757
+ # for image denoising and JPEG compression artifact reduction
758
+ self.conv_last = nn.Conv2d(embed_dim, num_out_ch, 3, 1, 1)
759
+
760
+ self.apply(self._init_weights)
761
+
762
+ def _init_weights(self, m):
763
+ if isinstance(m, nn.Linear):
764
+ trunc_normal_(m.weight, std=.02)
765
+ if isinstance(m, nn.Linear) and m.bias is not None:
766
+ nn.init.constant_(m.bias, 0)
767
+ elif isinstance(m, nn.LayerNorm):
768
+ nn.init.constant_(m.bias, 0)
769
+ nn.init.constant_(m.weight, 1.0)
770
+
771
+ @torch.jit.ignore
772
+ def no_weight_decay(self):
773
+ return {'absolute_pos_embed'}
774
+
775
+ @torch.jit.ignore
776
+ def no_weight_decay_keywords(self):
777
+ return {'relative_position_bias_table'}
778
+
779
+ def check_image_size(self, x):
780
+ _, _, h, w = x.size()
781
+ mod_pad_h = (self.window_size - h % self.window_size) % self.window_size
782
+ mod_pad_w = (self.window_size - w % self.window_size) % self.window_size
783
+ x = F.pad(x, (0, mod_pad_w, 0, mod_pad_h), 'reflect')
784
+ return x
785
+
786
+ def forward_features(self, x):
787
+ x_size = (x.shape[2], x.shape[3])
788
+ x = self.patch_embed(x)
789
+ if self.ape:
790
+ x = x + self.absolute_pos_embed
791
+ x = self.pos_drop(x)
792
+
793
+ for layer in self.layers:
794
+ x = layer(x, x_size)
795
+
796
+ x = self.norm(x) # B L C
797
+ x = self.patch_unembed(x, x_size)
798
+
799
+ return x
800
+
801
+ def forward(self, x):
802
+ H, W = x.shape[2:]
803
+ x = self.check_image_size(x)
804
+
805
+ self.mean = self.mean.type_as(x)
806
+ x = (x - self.mean) * self.img_range
807
+
808
+ if self.upsampler == 'pixelshuffle':
809
+ # for classical SR
810
+ x = self.conv_first(x)
811
+ x = self.conv_after_body(self.forward_features(x)) + x
812
+ x = self.conv_before_upsample(x)
813
+ x = self.conv_last(self.upsample(x))
814
+ elif self.upsampler == 'pixelshuffledirect':
815
+ # for lightweight SR
816
+ x = self.conv_first(x)
817
+ x = self.conv_after_body(self.forward_features(x)) + x
818
+ x = self.upsample(x)
819
+ elif self.upsampler == 'nearest+conv':
820
+ # for real-world SR
821
+ x = self.conv_first(x)
822
+ x = self.conv_after_body(self.forward_features(x)) + x
823
+ x = self.conv_before_upsample(x)
824
+ x = self.lrelu(self.conv_up1(torch.nn.functional.interpolate(x, scale_factor=2, mode='nearest')))
825
+ x = self.lrelu(self.conv_up2(torch.nn.functional.interpolate(x, scale_factor=2, mode='nearest')))
826
+ x = self.conv_last(self.lrelu(self.conv_hr(x)))
827
+ else:
828
+ # for image denoising and JPEG compression artifact reduction
829
+ x_first = self.conv_first(x)
830
+ res = self.conv_after_body(self.forward_features(x_first)) + x_first
831
+ x = self.conv_last(res)
832
+
833
+ x = x / self.img_range + self.mean
834
+
835
+ return x[:, :, :H*self.upscale, :W*self.upscale]
836
+
837
+ def flops(self):
838
+ flops = 0
839
+ H, W = self.patches_resolution
840
+ flops += H * W * 3 * self.embed_dim * 9
841
+ flops += self.patch_embed.flops()
842
+ for i, layer in enumerate(self.layers):
843
+ flops += layer.flops()
844
+ flops += H * W * 3 * self.embed_dim * self.embed_dim
845
+ flops += self.upsample.flops()
846
+ return flops
847
+
848
+
849
+ class Discriminator(nn.Module):
850
+ def __init__(self):
851
+ super(Discriminator, self).__init__()
852
+ self.net = nn.Sequential(
853
+ nn.Conv2d(3, 64, kernel_size=3, padding=1),
854
+ nn.GELU(),
855
+
856
+ nn.Conv2d(64, 64, kernel_size=3, stride=2, padding=1),
857
+ nn.GELU(),
858
+
859
+ nn.Conv2d(64, 128, kernel_size=3, padding=1),
860
+ nn.GELU(),
861
+
862
+ nn.Conv2d(128, 128, kernel_size=3, stride=2, padding=1),
863
+ nn.GELU(),
864
+
865
+ nn.Conv2d(128, 256, kernel_size=3, padding=1),
866
+ nn.GELU(),
867
+
868
+ nn.Conv2d(256, 256, kernel_size=3, stride=2, padding=1),
869
+ nn.GELU(),
870
+
871
+ nn.Conv2d(256, 512, kernel_size=3, padding=1),
872
+ nn.GELU(),
873
+
874
+ nn.Conv2d(512, 512, kernel_size=3, stride=2, padding=1),
875
+ nn.GELU(),
876
+
877
+ nn.AdaptiveAvgPool2d(1),
878
+ nn.Conv2d(512, 1024, kernel_size=1),
879
+ nn.GELU(),
880
+ nn.Conv2d(1024, 1, kernel_size=1)
881
+ )
882
+
883
+ def forward(self, x):
884
+ batch_size = x.size(0)
885
+ return self.net(x).view(batch_size)
886
+
887
+ def compute_gradient_penalty(D, real_samples, fake_samples):
888
+ alpha = torch.randn(real_samples.size(0), 1, 1, 1)
889
+ if torch.cuda.is_available():
890
+ alpha = alpha.cuda()
891
+
892
+ interpolates = (alpha * real_samples + ((1 - alpha) * fake_samples)).requires_grad_(True)
893
+ d_interpolates = D(interpolates)
894
+ fake = torch.ones(d_interpolates.size())
895
+ if torch.cuda.is_available():
896
+ fake = fake.cuda()
897
+
898
+ gradients = torch.autograd.grad(
899
+ outputs=d_interpolates,
900
+ inputs=interpolates,
901
+ grad_outputs=fake,
902
+ create_graph=True,
903
+ retain_graph=True,
904
+ only_inputs=True,
905
+ )[0]
906
+ gradients = gradients.view(gradients.size(0), -1)
907
+ gradient_penalty = ((gradients.norm(2, dim=1) - 1) ** 2).mean()
908
+ return gradient_penalty
909
+
910
+ if __name__ == '__main__':
911
+ upscale = 1
912
+ window_size = 7
913
+ height = (110 // upscale // window_size + 1) * window_size
914
+ width = (110 // upscale // window_size + 1) * window_size
915
+ model = Generator(upscale=upscale, img_size=(height, width),
916
+ window_size=window_size, img_range=1., depths=[6, 6, 6, 6],
917
+ embed_dim=60, num_heads=[6, 6, 6, 6], mlp_ratio=4, upsampler='nearest+conv')
918
+ print(model)
919
+ # print(height, width, model.flops() / 1e9)
920
+
921
+ x = torch.randn((1, 3, height, width))
922
+ x = model(x)
923
+ print(x.shape)
nets/resnest/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from .resnest import *
2
+ from .ablation import *
nets/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
nets/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)
nets/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
nets/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
+
utils/__init__.py ADDED
File without changes
utils/callbacks.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import torch
4
+ import matplotlib
5
+ matplotlib.use('Agg')
6
+ import scipy.signal
7
+ from matplotlib import pyplot as plt
8
+ from torch.utils.tensorboard import SummaryWriter
9
+
10
+
11
+ class LossHistory():
12
+ def __init__(self, log_dir, model, input_shape):
13
+ self.log_dir = log_dir
14
+
15
+ os.makedirs(self.log_dir)
16
+ self.writer = SummaryWriter(self.log_dir)
17
+ try:
18
+ for m in model:
19
+ dummy_input = torch.randn(2, 3, input_shape[0], input_shape[1])
20
+ self.writer.add_graph(m, dummy_input)
21
+ except:
22
+ pass
23
+
24
+ def append_loss(self, epoch, **kwargs):
25
+ if not os.path.exists(self.log_dir):
26
+ os.makedirs(self.log_dir)
27
+
28
+ for key, value in kwargs.items():
29
+ if not hasattr(self, key):
30
+ setattr(self, key, [])
31
+ #---------------------------------#
32
+ # 为列表添加数值
33
+ #---------------------------------#
34
+ getattr(self, key).append(value)
35
+
36
+ #---------------------------------#
37
+ # 写入txt
38
+ #---------------------------------#
39
+ with open(os.path.join(self.log_dir, key + ".txt"), 'a') as f:
40
+ f.write(str(value))
41
+ f.write("\n")
42
+
43
+ #---------------------------------#
44
+ # 写入tensorboard
45
+ #---------------------------------#
46
+ self.writer.add_scalar(key, value, epoch)
47
+
48
+ self.loss_plot(**kwargs)
49
+
50
+ def loss_plot(self, **kwargs):
51
+ plt.figure()
52
+
53
+ for key, value in kwargs.items():
54
+ losses = getattr(self, key)
55
+ plt.plot(range(len(losses)), losses, linewidth = 2, label = key)
56
+
57
+ plt.grid(True)
58
+ plt.xlabel('Epoch')
59
+ plt.ylabel('Loss')
60
+ plt.legend(loc="upper right")
61
+
62
+ plt.savefig(os.path.join(self.log_dir, "epoch_loss.png"))
63
+
64
+ plt.cla()
65
+ plt.close("all")
utils/dataloader.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ from PIL import Image
4
+ from torch.utils.data.dataset import Dataset
5
+
6
+ from utils.utils import cvtColor, preprocess_input
7
+
8
+
9
+ class CycleGanDataset(Dataset):
10
+ def __init__(self, annotation_lines_A, annotation_lines_B, input_shape):
11
+ super(CycleGanDataset, self).__init__()
12
+
13
+ self.annotation_lines_A = annotation_lines_A
14
+ self.annotation_lines_B = annotation_lines_B
15
+ self.length_A = len(self.annotation_lines_A)
16
+ self.length_B = len(self.annotation_lines_B)
17
+
18
+ self.input_shape = input_shape
19
+
20
+ def __len__(self):
21
+ return max(self.length_A, self.length_B)
22
+
23
+ def __getitem__(self, index):
24
+ index_A = index % self.length_A
25
+ image_A = Image.open(self.annotation_lines_A[index_A].split(';')[1].split()[0])
26
+ image_A = cvtColor(image_A).resize([self.input_shape[1], self.input_shape[0]], Image.BICUBIC)
27
+ image_A = np.array(image_A, dtype=np.float32)
28
+ image_A = np.transpose(preprocess_input(image_A), (2, 0, 1))
29
+
30
+ index_B = index % self.length_B
31
+ image_B = Image.open(self.annotation_lines_B[index_B].split(';')[1].split()[0])
32
+ image_B = cvtColor(image_B).resize([self.input_shape[1], self.input_shape[0]], Image.BICUBIC)
33
+ image_B = np.array(image_B, dtype=np.float32)
34
+ image_B = np.transpose(preprocess_input(image_B), (2, 0, 1))
35
+ return image_A, image_B
36
+
37
+ def CycleGan_dataset_collate(batch):
38
+ images_A = []
39
+ images_B = []
40
+ for image_A, image_B in batch:
41
+ images_A.append(image_A)
42
+ images_B.append(image_B)
43
+ images_A = torch.from_numpy(np.array(images_A, np.float32))
44
+ images_B = torch.from_numpy(np.array(images_B, np.float32))
45
+ return images_A, images_B
utils/utils.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import itertools
2
+ import math
3
+ from functools import partial
4
+
5
+ import matplotlib.pyplot as plt
6
+ import numpy as np
7
+ import torch
8
+ from PIL import Image
9
+
10
+
11
+ #---------------------------------------------------------#
12
+ # 将图像转换成RGB图像,防止灰度图在预测时报错。
13
+ # 代码仅仅支持RGB图像的预测,所有其它类型的图像都会转化成RGB
14
+ #---------------------------------------------------------#
15
+ def cvtColor(image):
16
+ if len(np.shape(image)) == 3 and np.shape(image)[2] == 3:
17
+ return image
18
+ else:
19
+ image = image.convert('RGB')
20
+ return image
21
+
22
+ #---------------------------------------------------#
23
+ # 对输入图像进行resize
24
+ #---------------------------------------------------#
25
+ def resize_image(image, size, letterbox_image):
26
+ iw, ih = image.size
27
+ w, h = size
28
+ if letterbox_image:
29
+ scale = min(w/iw, h/ih)
30
+ nw = int(iw*scale)
31
+ nh = int(ih*scale)
32
+
33
+ image = image.resize((nw,nh), Image.BICUBIC)
34
+ new_image = Image.new('RGB', size, (128, 128, 128))
35
+ new_image.paste(image, ((w-nw)//2, (h-nh)//2))
36
+ return new_image, nw, nh
37
+ else:
38
+ new_image = image.resize((w, h), Image.BICUBIC)
39
+ return new_image, None, None
40
+
41
+ #----------------------------------------#
42
+ # 预处理训练图片
43
+ #----------------------------------------#
44
+ def preprocess_input(x):
45
+ x /= 255
46
+ x -= 0.5
47
+ x /= 0.5
48
+ return x
49
+
50
+ def postprocess_output(x):
51
+ x *= 0.5
52
+ x += 0.5
53
+ x *= 255
54
+ return x
55
+
56
+ def show_result(num_epoch, G_model_A2B_train, G_model_B2A_train, images_A, images_B):
57
+ with torch.no_grad():
58
+ fake_image_B = G_model_A2B_train(images_A)
59
+ fake_image_A = G_model_B2A_train(images_B)
60
+
61
+ fig, ax = plt.subplots(2, 2)
62
+
63
+ ax = ax.flatten()
64
+ for j in itertools.product(range(4)):
65
+ ax[j].get_xaxis().set_visible(False)
66
+ ax[j].get_yaxis().set_visible(False)
67
+
68
+ ax[0].cla()
69
+ ax[0].imshow(np.transpose(np.uint8(postprocess_output(images_A.cpu().numpy()[0])), [1, 2, 0]))
70
+
71
+ ax[1].cla()
72
+ ax[1].imshow(np.transpose(np.clip(fake_image_B.cpu().numpy()[0] * 0.5 + 0.5, 0, 1), [1,2,0]))
73
+
74
+ ax[2].cla()
75
+ ax[2].imshow(np.transpose(np.uint8(postprocess_output(images_B.cpu().numpy()[0])), [1, 2, 0]))
76
+
77
+ ax[3].cla()
78
+ ax[3].imshow(np.transpose(np.clip(fake_image_A.cpu().numpy()[0] * 0.5 + 0.5, 0, 1), [1,2,0]))
79
+
80
+ label = 'Epoch {0}'.format(num_epoch)
81
+ fig.text(0.5, 0.04, label, ha='center')
82
+ plt.savefig("results/train_out/epoch_" + str(num_epoch) + "_results.png")
83
+ plt.close('all') #避免内存泄漏
84
+
85
+ def show_config(**kwargs):
86
+ print('Configurations:')
87
+ print('-' * 70)
88
+ print('|%25s | %40s|' % ('keys', 'values'))
89
+ print('-' * 70)
90
+ for key, value in kwargs.items():
91
+ print('|%25s | %40s|' % (str(key), str(value)))
92
+ print('-' * 70)
93
+
94
+ #---------------------------------------------------#
95
+ # 获得学习率
96
+ #---------------------------------------------------#
97
+ def get_lr(optimizer):
98
+ for param_group in optimizer.param_groups:
99
+ return param_group['lr']
100
+
101
+ def get_lr_scheduler(lr_decay_type, lr, min_lr, total_iters, warmup_iters_ratio = 0.05, warmup_lr_ratio = 0.1, no_aug_iter_ratio = 0.05, step_num = 10):
102
+ def yolox_warm_cos_lr(lr, min_lr, total_iters, warmup_total_iters, warmup_lr_start, no_aug_iter, iters):
103
+ if iters <= warmup_total_iters:
104
+ # lr = (lr - warmup_lr_start) * iters / float(warmup_total_iters) + warmup_lr_start
105
+ lr = (lr - warmup_lr_start) * pow(iters / float(warmup_total_iters), 2) + warmup_lr_start
106
+ elif iters >= total_iters - no_aug_iter:
107
+ lr = min_lr
108
+ else:
109
+ lr = min_lr + 0.5 * (lr - min_lr) * (
110
+ 1.0 + math.cos(math.pi* (iters - warmup_total_iters) / (total_iters - warmup_total_iters - no_aug_iter))
111
+ )
112
+ return lr
113
+
114
+ def step_lr(lr, decay_rate, step_size, iters):
115
+ if step_size < 1:
116
+ raise ValueError("step_size must above 1.")
117
+ n = iters // step_size
118
+ out_lr = lr * decay_rate ** n
119
+ return out_lr
120
+
121
+ if lr_decay_type == "cos":
122
+ warmup_total_iters = min(max(warmup_iters_ratio * total_iters, 1), 3)
123
+ warmup_lr_start = max(warmup_lr_ratio * lr, 1e-6)
124
+ no_aug_iter = min(max(no_aug_iter_ratio * total_iters, 1), 15)
125
+ func = partial(yolox_warm_cos_lr ,lr, min_lr, total_iters, warmup_total_iters, warmup_lr_start, no_aug_iter)
126
+ else:
127
+ decay_rate = (min_lr / lr) ** (1 / (step_num - 1))
128
+ step_size = total_iters / step_num
129
+ func = partial(step_lr, lr, decay_rate, step_size)
130
+
131
+ return func
132
+
133
+ def set_optimizer_lr(optimizer, lr_scheduler_func, epoch):
134
+ lr = lr_scheduler_func(epoch)
135
+ for param_group in optimizer.param_groups:
136
+ param_group['lr'] = lr
utils/utils_fit.py ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import torch.nn.functional as F
4
+ from tqdm import tqdm
5
+ from nets.cyclegan import compute_gradient_penalty
6
+ from utils.utils import get_lr, show_result
7
+
8
+
9
+ def fit_one_epoch(G_model_A2B_train, G_model_B2A_train, D_model_A_train, D_model_B_train, G_model_A2B, G_model_B2A, D_model_A, D_model_B, VGG_feature_model, ResNeSt_model, loss_history,
10
+ G_optimizer, D_optimizer_A, D_optimizer_B, BCE_loss, L1_loss, Face_loss, epoch, epoch_step, gen, Epoch, cuda, fp16, scaler, save_period, save_dir, photo_save_step, local_rank=0):
11
+ G_total_loss = 0
12
+ D_total_loss_A = 0
13
+ D_total_loss_B = 0
14
+
15
+ if local_rank == 0:
16
+ print('Start Train')
17
+ pbar = tqdm(total=epoch_step,desc=f'Epoch {epoch + 1}/{Epoch}',postfix=dict,mininterval=0.3)
18
+ for iteration, batch in enumerate(gen):
19
+ if iteration >= epoch_step:
20
+ break
21
+
22
+ images_A, images_B = batch[0], batch[1]
23
+ batch_size = images_A.size()[0]
24
+ y_real = torch.ones(batch_size)
25
+ y_fake = torch.zeros(batch_size)
26
+
27
+ with torch.no_grad():
28
+ if cuda:
29
+ images_A, images_B, y_real, y_fake = images_A.cuda(local_rank), images_B.cuda(local_rank), y_real.cuda(local_rank), y_fake.cuda(local_rank)
30
+
31
+ if not fp16:
32
+ #---------------------------------#
33
+ # 训练生成器A2B和B2A
34
+ #---------------------------------#
35
+ G_optimizer.zero_grad()
36
+
37
+ Same_B = G_model_A2B_train(images_B)
38
+ loss_identity_B = L1_loss(Same_B, images_B)
39
+
40
+ Same_A = G_model_B2A_train(images_A)
41
+ loss_identity_A = L1_loss(Same_A, images_A)
42
+
43
+ fake_B = G_model_A2B_train(images_A)
44
+ pred_real = D_model_B_train(images_B)
45
+ pred_fake = D_model_B_train(fake_B)
46
+ pred_rf = pred_real - pred_fake.mean()
47
+ pred_fr = pred_fake - pred_real.mean()
48
+ D_train_loss_rf = BCE_loss(pred_rf, y_fake)
49
+ D_train_loss_fr = BCE_loss(pred_fr, y_real)
50
+ loss_GAN_A2B = (D_train_loss_rf + D_train_loss_fr) / 2
51
+
52
+ fake_A = G_model_B2A_train(images_B)
53
+ pred_real = D_model_A_train(images_A)
54
+ pred_fake = D_model_A_train(fake_A)
55
+ pred_rf = pred_real - pred_fake.mean()
56
+ pred_fr = pred_fake - pred_real.mean()
57
+ D_train_loss_rf = BCE_loss(pred_rf, y_fake)
58
+ D_train_loss_fr = BCE_loss(pred_fr, y_real)
59
+ loss_GAN_B2A = (D_train_loss_rf + D_train_loss_fr) / 2
60
+
61
+ recovered_A = G_model_B2A_train(fake_B)
62
+ loss_cycle_ABA = L1_loss(recovered_A, images_A)
63
+
64
+ loss_per_ABA = L1_loss(VGG_feature_model(recovered_A), VGG_feature_model(images_A))
65
+
66
+ recovered_A_face = F.interpolate(recovered_A, size=(112, 112), mode='bicubic', align_corners=True)
67
+ images_A_face = F.interpolate(images_A, size=(112, 112), mode='bicubic', align_corners=True)
68
+ loss_face_ABA = torch.mean(1. - Face_loss(ResNeSt_model(recovered_A_face), ResNeSt_model(images_A_face)))
69
+
70
+ recovered_B = G_model_A2B_train(fake_A)
71
+ loss_cycle_BAB = L1_loss(recovered_B, images_B)
72
+
73
+ loss_per_BAB = L1_loss(VGG_feature_model(recovered_B), VGG_feature_model(images_B))
74
+
75
+ recovered_B_face = F.interpolate(recovered_B, size=(112, 112), mode='bicubic', align_corners=True)
76
+ images_B_face = F.interpolate(images_B, size=(112, 112), mode='bicubic', align_corners=True)
77
+ loss_face_BAB = torch.mean(1. - Face_loss(ResNeSt_model(recovered_B_face), ResNeSt_model(images_B_face)))
78
+
79
+ G_loss = loss_identity_A * 5.0 + loss_identity_B * 5.0 + loss_GAN_A2B + loss_GAN_B2A + loss_per_ABA * 2.5 \
80
+ + loss_per_BAB *2.5 + loss_cycle_ABA * 10.0 + loss_cycle_BAB * 10.0 + loss_face_ABA * 5 + loss_face_BAB * 5
81
+ G_loss.backward()
82
+ G_optimizer.step()
83
+
84
+ #---------------------------------#
85
+ # 训练评价器A
86
+ #---------------------------------#
87
+ D_optimizer_A.zero_grad()
88
+ pred_real = D_model_A_train(images_A)
89
+ pred_fake = D_model_A_train(fake_A.detach())
90
+ pred_rf = pred_real - pred_fake.mean()
91
+ pred_fr = pred_fake - pred_real.mean()
92
+ D_train_loss_rf = BCE_loss(pred_rf, y_real)
93
+ D_train_loss_fr = BCE_loss(pred_fr, y_fake)
94
+ gradient_penalty = compute_gradient_penalty(D_model_A_train, images_A, fake_A.detach())
95
+
96
+ D_loss_A = 10 * gradient_penalty + (D_train_loss_rf + D_train_loss_fr) / 2
97
+ D_loss_A.backward()
98
+ D_optimizer_A.step()
99
+
100
+ #---------------------------------#
101
+ # 训��评价器B
102
+ #---------------------------------#
103
+ D_optimizer_B.zero_grad()
104
+
105
+ pred_real = D_model_B_train(images_B)
106
+ pred_fake = D_model_B_train(fake_B.detach())
107
+ pred_rf = pred_real - pred_fake.mean()
108
+ pred_fr = pred_fake - pred_real.mean()
109
+ D_train_loss_rf = BCE_loss(pred_rf, y_real)
110
+ D_train_loss_fr = BCE_loss(pred_fr, y_fake)
111
+ gradient_penalty = compute_gradient_penalty(D_model_B_train, images_B, fake_B.detach())
112
+
113
+ D_loss_B = 10 * gradient_penalty + (D_train_loss_rf + D_train_loss_fr) / 2
114
+ D_loss_B.backward()
115
+ D_optimizer_B.step()
116
+
117
+ else:
118
+ from torch.cuda.amp import autocast
119
+
120
+ #---------------------------------#
121
+ # 训练生成器A2B和B2A
122
+ #---------------------------------#
123
+ with autocast():
124
+ G_optimizer.zero_grad()
125
+ Same_B = G_model_A2B_train(images_B)
126
+ loss_identity_B = L1_loss(Same_B, images_B)
127
+
128
+ Same_A = G_model_B2A_train(images_A)
129
+ loss_identity_A = L1_loss(Same_A, images_A)
130
+
131
+ fake_B = G_model_A2B_train(images_A)
132
+ pred_real = D_model_B_train(images_B)
133
+ pred_fake = D_model_B_train(fake_B)
134
+ pred_rf = pred_real - pred_fake.mean()
135
+ pred_fr = pred_fake - pred_real.mean()
136
+ D_train_loss_rf = BCE_loss(pred_rf, y_fake)
137
+ D_train_loss_fr = BCE_loss(pred_fr, y_real)
138
+ loss_GAN_A2B = (D_train_loss_rf + D_train_loss_fr) / 2
139
+
140
+ fake_A = G_model_B2A_train(images_B)
141
+ pred_real = D_model_A_train(images_A)
142
+ pred_fake = D_model_A_train(fake_A)
143
+ pred_rf = pred_real - pred_fake.mean()
144
+ pred_fr = pred_fake - pred_real.mean()
145
+ D_train_loss_rf = BCE_loss(pred_rf, y_fake)
146
+ D_train_loss_fr = BCE_loss(pred_fr, y_real)
147
+ loss_GAN_B2A = (D_train_loss_rf + D_train_loss_fr) / 2
148
+
149
+ recovered_A = G_model_B2A_train(fake_B)
150
+ loss_cycle_ABA = L1_loss(recovered_A, images_A)
151
+ recovered_A_face = F.interpolate(recovered_A, size=(112, 112), mode='bicubic', align_corners=True)
152
+ images_A_face = F.interpolate(images_A, size=(112, 112), mode='bicubic', align_corners=True)
153
+ loss_face_ABA = torch.mean(1. - Face_loss(ResNeSt_model(recovered_A_face), ResNeSt_model(images_A_face)))
154
+
155
+ recovered_B = G_model_A2B_train(fake_A)
156
+ loss_cycle_BAB = L1_loss(recovered_B, images_B)
157
+ recovered_B_face = F.interpolate(recovered_B, size=(112, 112), mode='bicubic', align_corners=True)
158
+ images_B_face = F.interpolate(images_B, size=(112, 112), mode='bicubic', align_corners=True)
159
+ loss_face_BAB = torch.mean(1. - Face_loss(ResNeSt_model(recovered_B_face), ResNeSt_model(images_B_face)))
160
+
161
+ G_loss = loss_identity_A * 5.0 + loss_identity_B * 5.0 + loss_GAN_A2B + loss_GAN_B2A \
162
+ + loss_cycle_ABA * 10.0 + loss_cycle_BAB * 10.0 + loss_face_ABA * 5 + loss_face_BAB * 5
163
+ #----------------------#
164
+ # 反向传播
165
+ #----------------------#
166
+ scaler.scale(G_loss).backward()
167
+ scaler.step(G_optimizer)
168
+ scaler.update()
169
+
170
+ #---------------------------------#
171
+ # 训练评价器A
172
+ #---------------------------------#
173
+ with autocast():
174
+ D_optimizer_A.zero_grad()
175
+ pred_real = D_model_A_train(images_A)
176
+ pred_fake = D_model_A_train(fake_A.detach())
177
+ pred_rf = pred_real - pred_fake.mean()
178
+ pred_fr = pred_fake - pred_real.mean()
179
+ D_train_loss_rf = BCE_loss(pred_rf, y_real)
180
+ D_train_loss_fr = BCE_loss(pred_fr, y_fake)
181
+ gradient_penalty = compute_gradient_penalty(D_model_A_train, images_A, fake_A.detach())
182
+
183
+ D_loss_A = 10 * gradient_penalty + (D_train_loss_rf + D_train_loss_fr) / 2
184
+ #----------------------#
185
+ # 反向传播
186
+ #----------------------#
187
+ scaler.scale(D_loss_A).backward()
188
+ scaler.step(D_optimizer_A)
189
+ scaler.update()
190
+
191
+ #---------------------------------#
192
+ # 训练评价器B
193
+ #---------------------------------#
194
+ with autocast():
195
+ D_optimizer_B.zero_grad()
196
+
197
+ pred_real = D_model_B_train(images_B)
198
+ pred_fake = D_model_B_train(fake_B.detach())
199
+ pred_rf = pred_real - pred_fake.mean()
200
+ pred_fr = pred_fake - pred_real.mean()
201
+ D_train_loss_rf = BCE_loss(pred_rf, y_real)
202
+ D_train_loss_fr = BCE_loss(pred_fr, y_fake)
203
+ gradient_penalty = compute_gradient_penalty(D_model_B_train, images_B, fake_B.detach())
204
+
205
+ D_loss_B = 10 * gradient_penalty + (D_train_loss_rf + D_train_loss_fr) / 2
206
+ #----------------------#
207
+ # 反向传播
208
+ #----------------------#
209
+ scaler.scale(D_loss_B).backward()
210
+ scaler.step(D_optimizer_B)
211
+ scaler.update()
212
+
213
+ G_total_loss += G_loss.item()
214
+ D_total_loss_A += D_loss_A.item()
215
+ D_total_loss_B += D_loss_B.item()
216
+
217
+ if local_rank == 0:
218
+ pbar.set_postfix(**{'G_loss' : G_total_loss / (iteration + 1),
219
+ 'D_loss_A' : D_total_loss_A / (iteration + 1),
220
+ 'D_loss_B' : D_total_loss_B / (iteration + 1),
221
+ 'lr' : get_lr(G_optimizer)})
222
+ pbar.update(1)
223
+
224
+ if iteration % photo_save_step == 0:
225
+ show_result(epoch + 1, G_model_A2B, G_model_B2A, images_A, images_B)
226
+
227
+ G_total_loss = G_total_loss / epoch_step
228
+ D_total_loss_A = D_total_loss_A / epoch_step
229
+ D_total_loss_B = D_total_loss_B / epoch_step
230
+
231
+ if local_rank == 0:
232
+ pbar.close()
233
+ print('Epoch:'+ str(epoch + 1) + '/' + str(Epoch))
234
+ print('G Loss: %.4f || D Loss A: %.4f || D Loss B: %.4f ' % (G_total_loss, D_total_loss_A, D_total_loss_B))
235
+ loss_history.append_loss(epoch + 1, G_total_loss = G_total_loss, D_total_loss_A = D_total_loss_A, D_total_loss_B = D_total_loss_B)
236
+
237
+ #-----------------------------------------------#
238
+ # 保存权值
239
+ #-----------------------------------------------#
240
+ if (epoch + 1) % save_period == 0 or epoch + 1 == Epoch:
241
+ torch.save(G_model_A2B.state_dict(), os.path.join(save_dir, 'G_model_A2B_Epoch%d-GLoss%.4f-DALoss%.4f-DBLoss%.4f.pth'%(epoch + 1, G_total_loss, D_total_loss_A, D_total_loss_B)))
242
+ torch.save(G_model_B2A.state_dict(), os.path.join(save_dir, 'G_model_B2A_Epoch%d-GLoss%.4f-DALoss%.4f-DBLoss%.4f.pth'%(epoch + 1, G_total_loss, D_total_loss_A, D_total_loss_B)))
243
+ torch.save(D_model_A.state_dict(), os.path.join(save_dir, 'D_model_A_Epoch%d-GLoss%.4f-DALoss%.4f-DBLoss%.4f.pth'%(epoch + 1, G_total_loss, D_total_loss_A, D_total_loss_B)))
244
+ torch.save(D_model_B.state_dict(), os.path.join(save_dir, 'D_model_B_Epoch%d-GLoss%.4f-DALoss%.4f-DBLoss%.4f.pth'%(epoch + 1, G_total_loss, D_total_loss_A, D_total_loss_B)))
245
+
246
+ torch.save(G_model_A2B.state_dict(), os.path.join(save_dir, "G_model_A2B_last_epoch_weights.pth"))
247
+ torch.save(G_model_B2A.state_dict(), os.path.join(save_dir, "G_model_B2A_last_epoch_weights.pth"))
248
+ torch.save(D_model_A.state_dict(), os.path.join(save_dir, "D_model_A_last_epoch_weights.pth"))
249
+ torch.save(D_model_B.state_dict(), os.path.join(save_dir, "D_model_B_last_epoch_weights.pth"))