-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.py
356 lines (337 loc) · 16.1 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
import torch.optim as optim
from net.network import SwinJSCC
from data.datasets import get_loader
from utils import *
torch.backends.cudnn.benchmark = True
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
import torch
from datetime import datetime
import torch.nn as nn
import argparse
from loss.distortion import *
import time
import torchvision
parser = argparse.ArgumentParser(description='SwinJSCC')
parser.add_argument('--training', action='store_true',
help='training or testing')
parser.add_argument('--trainset', type=str, default='DIV2K',
choices=['CIFAR10', 'DIV2K'],
help='train dataset name')
parser.add_argument('--testset', type=str, default='ffhq',
choices=['kodak', 'CLIC21', 'ffhq'],
help='specify the testset for HR models')
parser.add_argument('--distortion-metric', type=str, default='MSE',
choices=['MSE', 'MS-SSIM'],
help='evaluation metrics')
parser.add_argument('--model', type=str, default='SwinJSCC_w/_SAandRA',
choices=['SwinJSCC_w/o_SAandRA', 'SwinJSCC_w/_SA', 'SwinJSCC_w/_RA', 'SwinJSCC_w/_SAandRA'],
help='SwinJSCC model or SwinJSCC without channel ModNet or rate ModNet')
parser.add_argument('--channel-type', type=str, default='awgn',
choices=['awgn', 'rayleigh'],
help='wireless channel model, awgn or rayleigh')
parser.add_argument('--C', type=str, default='96',
help='bottleneck dimension')
parser.add_argument('--multiple-snr', type=str, default='10',
help='random or fixed snr')
parser.add_argument('--model_size', type=str, default='base',
choices=['small', 'base', 'large'], help='SwinJSCC model size')
args = parser.parse_args()
class config():
seed = 42
pass_channel = True
CUDA = True
device = torch.device("cuda:0")
norm = False
# logger
print_step = 100
plot_step = 10000
filename = datetime.now().__str__()[:-7]
workdir = './history/{}'.format(filename)
log = workdir + '/Log_{}.log'.format(filename)
samples = workdir + '/samples'
models = workdir + '/models'
logger = None
# training details
normalize = False
learning_rate = 0.0001
tot_epoch = 10000000
if args.trainset == 'CIFAR10':
save_model_freq = 5
image_dims = (3, 32, 32)
train_data_dir = "/media/D/Dataset/CIFAR10/"
test_data_dir = "/media/D/Dataset/CIFAR10/"
batch_size = 128
downsample = 2
channel_number = int(args.C)
encoder_kwargs = dict(
img_size=(image_dims[1], image_dims[2]), patch_size=2, in_chans=3,
embed_dims=[128, 256], depths=[2, 4], num_heads=[4, 8], C=channel_number,
window_size=2, mlp_ratio=4., qkv_bias=True, qk_scale=None,
norm_layer=nn.LayerNorm, patch_norm=True,
)
decoder_kwargs = dict(
img_size=(image_dims[1], image_dims[2]),
embed_dims=[256, 128], depths=[4, 2], num_heads=[8, 4], C=channel_number,
window_size=2, mlp_ratio=4., qkv_bias=True, qk_scale=None,
norm_layer=nn.LayerNorm, patch_norm=True,
)
elif args.trainset == 'DIV2K':
save_model_freq = 100
image_dims = (3, 256, 256)
# train_data_dir = ["/media/D/Dataset/HR_Image_dataset/"]
base_path = "/media/D/Dataset/HR_Image_dataset/"
if args.testset == 'kodak':
test_data_dir = ["/media/D/Dataset/kodak/"]
elif args.testset == 'CLIC21':
test_data_dir = ["/media/D/Dataset/HR_Image_dataset/clic2021/test/"]
elif args.testset == 'ffhq':
test_data_dir = ["/media/D/yangke/SwinJSCC/data/ffhq/"]
train_data_dir = [base_path + '/clic2020/**',
base_path + '/clic2021/train',
base_path + '/clic2021/valid',
base_path + '/clic2022/val',
base_path + '/DIV2K_train_HR',
base_path + '/DIV2K_valid_HR']
batch_size = 16
downsample = 4
if args.model == 'SwinJSCC_w/o_SAandRA' or args.model == 'SwinJSCC_w/_SA':
channel_number = int(args.C)
else:
channel_number = None
if args.model_size == 'small':
encoder_kwargs = dict(
img_size=(image_dims[1], image_dims[2]), patch_size=2, in_chans=3,
embed_dims=[128, 192, 256, 320], depths=[2, 2, 2, 2], num_heads=[4, 6, 8, 10], C=channel_number,
window_size=8, mlp_ratio=4., qkv_bias=True, qk_scale=None,
norm_layer=nn.LayerNorm, patch_norm=True,
)
decoder_kwargs = dict(
img_size=(image_dims[1], image_dims[2]),
embed_dims=[320, 256, 192, 128], depths=[2, 2, 2, 2], num_heads=[10, 8, 6, 4], C=channel_number,
window_size=8, mlp_ratio=4., qkv_bias=True, qk_scale=None,
norm_layer=nn.LayerNorm, patch_norm=True,
)
elif args.model_size == 'base':
encoder_kwargs = dict(
img_size=(image_dims[1], image_dims[2]), patch_size=2, in_chans=3,
embed_dims=[128, 192, 256, 320], depths=[2, 2, 6, 2], num_heads=[4, 6, 8, 10], C=channel_number,
window_size=8, mlp_ratio=4., qkv_bias=True, qk_scale=None,
norm_layer=nn.LayerNorm, patch_norm=True,
)
decoder_kwargs = dict(
img_size=(image_dims[1], image_dims[2]),
embed_dims=[320, 256, 192, 128], depths=[2, 6, 2, 2], num_heads=[10, 8, 6, 4], C=channel_number,
window_size=8, mlp_ratio=4., qkv_bias=True, qk_scale=None,
norm_layer=nn.LayerNorm, patch_norm=True,
)
elif args.model_size =='large':
encoder_kwargs = dict(
img_size=(image_dims[1], image_dims[2]), patch_size=2, in_chans=3,
embed_dims=[128, 192, 256, 320], depths=[2, 2, 18, 2], num_heads=[4, 6, 8, 10], C=channel_number,
window_size=8, mlp_ratio=4., qkv_bias=True, qk_scale=None,
norm_layer=nn.LayerNorm, patch_norm=True,
)
decoder_kwargs = dict(
img_size=(image_dims[1], image_dims[2]),
embed_dims=[320, 256, 192, 128], depths=[2, 18, 2, 2], num_heads=[10, 8, 6, 4], C=channel_number,
window_size=8, mlp_ratio=4., qkv_bias=True, qk_scale=None,
norm_layer=nn.LayerNorm, patch_norm=True,
)
if args.trainset == 'CIFAR10':
CalcuSSIM = MS_SSIM(window_size=3, data_range=1., levels=4, channel=3).cuda()
else:
CalcuSSIM = MS_SSIM(data_range=1., levels=4, channel=3).cuda()
def load_weights(model_path):
pretrained = torch.load(model_path)
net.load_state_dict(pretrained, strict=True)
del pretrained
def train_one_epoch(args):
net.train()
elapsed, losses, psnrs, msssims, cbrs, snrs = [AverageMeter() for _ in range(6)]
metrics = [elapsed, losses, psnrs, msssims, cbrs, snrs]
global global_step
if args.trainset == 'CIFAR10':
for batch_idx, (input, label) in enumerate(train_loader):
start_time = time.time()
global_step += 1
input = input.cuda()
recon_image, CBR, SNR, mse, loss_G = net(input)
loss = loss_G
optimizer.zero_grad()
loss.backward()
optimizer.step()
elapsed.update(time.time() - start_time)
losses.update(loss.item())
cbrs.update(CBR)
snrs.update(SNR)
if mse.item() > 0:
psnr = 10 * (torch.log(255. * 255. / mse) / np.log(10))
psnrs.update(psnr.item())
msssim = 1 - CalcuSSIM(input, recon_image.clamp(0., 1.)).mean().item()
msssims.update(msssim)
else:
psnrs.update(100)
msssims.update(100)
if (global_step % config.print_step) == 0:
process = (global_step % train_loader.__len__()) / (train_loader.__len__()) * 100.0
log = (' | '.join([
f'Epoch {epoch}',
f'Step [{global_step % train_loader.__len__()}/{train_loader.__len__()}={process:.2f}%]',
f'Time {elapsed.val:.3f}',
f'Loss {losses.val:.3f} ({losses.avg:.3f})',
f'CBR {cbrs.val:.4f} ({cbrs.avg:.4f})',
f'SNR {snrs.val:.1f} ({snrs.avg:.1f})',
f'PSNR {psnrs.val:.3f} ({psnrs.avg:.3f})',
f'MSSSIM {msssims.val:.3f} ({msssims.avg:.3f})',
f'Lr {cur_lr}',
]))
logger.info(log)
for i in metrics:
i.clear()
else:
for batch_idx, input in enumerate(train_loader):
start_time = time.time()
global_step += 1
input = input.cuda()
recon_image, CBR, SNR, mse, loss_G = net(input)
loss = loss_G
optimizer.zero_grad()
loss.backward()
optimizer.step()
elapsed.update(time.time() - start_time)
losses.update(loss.item())
cbrs.update(CBR)
snrs.update(SNR)
if mse.item() > 0:
psnr = 10 * (torch.log(255. * 255. / mse) / np.log(10))
psnrs.update(psnr.item())
msssim = 1 - CalcuSSIM(input, recon_image.clamp(0., 1.)).mean().item()
msssims.update(msssim)
else:
psnrs.update(100)
msssims.update(100)
if (global_step % config.print_step) == 0:
process = (global_step % train_loader.__len__()) / (train_loader.__len__()) * 100.0
log = (' | '.join([
f'Epoch {epoch}',
f'Step [{global_step % train_loader.__len__()}/{train_loader.__len__()}={process:.2f}%]',
f'Time {elapsed.val:.3f}',
f'Loss {losses.val:.3f} ({losses.avg:.3f})',
f'CBR {cbrs.val:.4f} ({cbrs.avg:.4f})',
f'SNR {snrs.val:.1f} ({snrs.avg:.1f})',
f'PSNR {psnrs.val:.3f} ({psnrs.avg:.3f})',
f'MSSSIM {msssims.val:.3f} ({msssims.avg:.3f})',
f'Lr {cur_lr}',
]))
logger.info(log)
for i in metrics:
i.clear()
for i in metrics:
i.clear()
def test():
config.isTrain = False
net.eval()
elapsed, psnrs, msssims, snrs, cbrs = [AverageMeter() for _ in range(5)]
metrics = [elapsed, psnrs, msssims, snrs, cbrs]
multiple_snr = args.multiple_snr.split(",")
for i in range(len(multiple_snr)):
multiple_snr[i] = int(multiple_snr[i])
channel_number = args.C.split(",")
for i in range(len(channel_number)):
channel_number[i] = int(channel_number[i])
results_snr = np.zeros((len(multiple_snr), len(channel_number)))
results_cbr = np.zeros((len(multiple_snr), len(channel_number)))
results_psnr = np.zeros((len(multiple_snr), len(channel_number)))
results_msssim = np.zeros((len(multiple_snr), len(channel_number)))
for i, SNR in enumerate(multiple_snr):
for j, rate in enumerate(channel_number):
with torch.no_grad():
if args.trainset == 'CIFAR10':
for batch_idx, (input, label) in enumerate(test_loader):
start_time = time.time()
input = input.cuda()
recon_image, CBR, SNR, mse, loss_G = net(input, SNR, rate)
elapsed.update(time.time() - start_time)
cbrs.update(CBR)
snrs.update(SNR)
if mse.item() > 0:
psnr = 10 * (torch.log(255. * 255. / mse) / np.log(10))
psnrs.update(psnr.item())
msssim = 1 - CalcuSSIM(input, recon_image.clamp(0., 1.)).mean().item()
msssims.update(msssim)
else:
psnrs.update(100)
msssims.update(100)
log = (' | '.join([
f'Time {elapsed.val:.3f}',
f'CBR {cbrs.val:.4f} ({cbrs.avg:.4f})',
f'SNR {snrs.val:.1f}',
f'PSNR {psnrs.val:.3f} ({psnrs.avg:.3f})',
f'MSSSIM {msssims.val:.3f} ({msssims.avg:.3f})',
f'Lr {cur_lr}',
]))
logger.info(log)
else:
for batch_idx, batch in enumerate(test_loader):
input, names = batch
start_time = time.time()
input = input.cuda()
recon_image, CBR, SNR, mse, loss_G = net(input, SNR, rate)
torchvision.utils.save_image(recon_image,
os.path.join("/media/D/yangke/SwinJSCC/data/", f"recon/{names[0]}"))
elapsed.update(time.time() - start_time)
cbrs.update(CBR)
snrs.update(SNR)
if mse.item() > 0:
psnr = 10 * (torch.log(255. * 255. / mse) / np.log(10))
psnrs.update(psnr.item())
msssim = 1 - CalcuSSIM(input, recon_image.clamp(0., 1.)).mean().item()
msssims.update(msssim)
MSSSIM = -10 * np.math.log10(1 - msssim)
print(MSSSIM)
else:
psnrs.update(100)
msssims.update(100)
log = (' | '.join([
f'Time {elapsed.val:.3f}',
f'CBR {cbrs.val:.4f} ({cbrs.avg:.4f})',
f'SNR {snrs.val:.1f}',
f'PSNR {psnrs.val:.3f} ({psnrs.avg:.3f})',
f'MSSSIM {msssims.val:.3f} ({msssims.avg:.3f})',
f'Lr {cur_lr}',
]))
logger.info(log)
results_snr[i, j] = snrs.avg
results_cbr[i, j] = cbrs.avg
results_psnr[i, j] = psnrs.avg
results_msssim[i, j] = msssims.avg
for t in metrics:
t.clear()
print("SNR: {}".format(results_snr.tolist()))
print("CBR: {}".format(results_cbr.tolist()))
print("PSNR: {}".format(results_psnr.tolist()))
print("MS-SSIM: {}".format(results_msssim.tolist()))
print("Finish Test!")
if __name__ == '__main__':
seed_torch()
logger = logger_configuration(config, save_log=False)
logger.info(config.__dict__)
torch.manual_seed(seed=config.seed)
net = SwinJSCC(args, config)
model_path = "/media/D/yangke/SwinJSCC/checkpoint/SwinJSCC_w_SAandRA_AWGN_HRimage_cbr_psnr_snr.model"
load_weights(model_path)
net = net.cuda()
model_params = [{'params': net.parameters(), 'lr': 0.0001}]
train_loader, test_loader = get_loader(args, config)
cur_lr = config.learning_rate
optimizer = optim.Adam(model_params, lr=cur_lr)
global_step = 0
steps_epoch = global_step // train_loader.__len__()
if args.training:
for epoch in range(steps_epoch, config.tot_epoch):
train_one_epoch(args)
if (epoch + 1) % config.save_model_freq == 0:
save_model(net, save_path=config.models + '/{}_EP{}.model'.format(config.filename, epoch + 1))
test()
else:
test()