forked from nhduong/guided_demoireing_net
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
1728 lines (1427 loc) · 72.2 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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'''
PyTorch source code for "Multiscale Guided Coarse-to-Fine Network for Screenshot Demoiréing"
Project page: https://nhduong.github.io/guided_demoireing_net/
'''
import argparse
import os
import shutil
import math
from enum import Enum
import random
import platform
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data
import torchvision
import torchvision.transforms as transforms
from torch.utils.data import Dataset
from natsort import natsorted
from glob import glob
import torch.nn.functional as F
import numpy as np
from PIL import Image
from PIL import ImageFile
from tqdm import tqdm
import datetime
import sys
from skimage.metrics import peak_signal_noise_ratio as ski_psnr
from skimage.metrics import structural_similarity as ski_ssim
from math import log10
import lpips
from math import exp
import cv2
import logging
import traceback
from torch.utils.tensorboard import SummaryWriter
from accelerate import Accelerator
import warnings
warnings.simplefilter('ignore')
def parse():
parser = argparse.ArgumentParser(description='PyTorch Demoireing Training')
parser.add_argument('--data_path', default='', type=str,
help='data path')
parser.add_argument('--train_dir', default='', type=str,
help='train dir name')
parser.add_argument('--test_dir', default='', type=str,
help='test dir name')
parser.add_argument('--moire_dir', default='', type=str,
help='moire dir name')
parser.add_argument('--clean_dir', default='', type=str,
help='clean dir name')
parser.add_argument('--data_name', default='', type=str,
help='dataset name')
parser.add_argument('--exp_name', default='spl', type=str,
help='experiment name (default: spl)')
parser.add_argument('--note', default='rev_1', type=str,
help='notes (default: rev_1)')
parser.add_argument('--adaloss', action='store_true',
help='Uses adaptive loss.')
parser.add_argument('--affine', action='store_true',
help='Uses affine transformation.')
parser.add_argument('--l1loss', action='store_true',
help='Uses L1 loss.')
parser.add_argument('--perloss', action='store_true',
help='Uses perceptual loss.')
parser.add_argument('-j', '--workers', default=4, type=int, metavar='N',
help='number of data loading workers (default: 4)')
parser.add_argument('--epochs', default=1000, type=int, metavar='N',
help='number of total epochs to run')
parser.add_argument('--start_epoch', default=0, type=int, metavar='N',
help='manual epoch number (useful on restarts)')
parser.add_argument('-b', '--batch_size', default=2, type=int,
metavar='N', help='mini-batch size per process (default: 2)')
parser.add_argument('--test_batch_size', default=1, type=int,
metavar='N', help='test mini-batch size per process (default: 1)')
parser.add_argument('--lr', '--learning_rate', default=0.0002, type=float,
metavar='LR', help='Initial learning rate. Will be scaled by <global batch size>/2: args.lr = args.lr*float(args.batch_size*args.world_size)/2.')
parser.add_argument('--eta_min', default=0.000001, type=float,
metavar='ETA_MIN', help='Learning rate at the end of a cycle. Will be scaled by <global batch size>/2: args.eta_min = args.eta_min*float(args.batch_size*args.world_size)/2.')
parser.add_argument('--ada_lamb', default=5.0, type=float,
help='ada lamb (default: 5.0)')
parser.add_argument('--ada_eps', default=1.0, type=float,
help='ada eps (default: 1.0)')
parser.add_argument('--ada_eps_2', default=1.0, type=float,
help='ada eps 2 (default: 1.0)')
parser.add_argument('--num_branches', default=3, type=int,
help='number of network branches (default: 3)')
parser.add_argument('--init_weights', action='store_true',
help='initialize weights.')
parser.add_argument('--T_0', default=50, type=int,
metavar='T_0', help='The number of epochs of the first learning cycle (default: 50)')
parser.add_argument('--print_freq', '-p', default=1000, type=int,
metavar='N', help='print frequency (default: 1000)')
parser.add_argument('--resume', default='', type=str, metavar='PATH',
help='path to a checkpoint .pth.tar')
parser.add_argument('-e', '--evaluate', dest='evaluate', action='store_true',
help='evaluate model on validation set')
parser.add_argument('--calc_mets', action='store_true',
help='Calculates metrics during training. Enabling this could slow down the program.')
parser.add_argument('--calc_val_losses', action='store_true',
help='Calculates validation losses during training. Enabling this could slow down the program.')
parser.add_argument('--calc_train_mets', action='store_true',
help='Calculates metrics during training. Enabling this could slow down the program.')
parser.add_argument('--dont_calc_mets_at_all', action='store_true',
help='Does not calculate metrics at all. Enabling this could speed up the program.')
parser.add_argument('--dont_calc_train_mets', action='store_true',
help='Does not calculate metrics during training. Enabling this could speed up the program.')
parser.add_argument('--log2file', action='store_true',
help='export all logs to a file.')
parser.add_argument('--seed', default=123, type=int,
help='seed for initializing training. ')
args = parser.parse_args()
return args
def main():
# get user inputs
args = parse()
# random seed
if args.seed is not None:
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
torch.cuda.manual_seed_all(args.seed)
cudnn.deterministic = False
cudnn.benchmark = True
warnings.warn('You have chosen to seed training. '
'This will turn on the CUDNN deterministic setting, '
'which can slow down your training considerably! '
'You may see unexpected behavior when restarting '
'from checkpoints.')
# HunggingFace accelerator
accelerator = Accelerator()
device = accelerator.device
# evaluation metrics
global best_psnr, cor_ssim, best_epoch
best_psnr = 0
cor_ssim = 0
best_epoch = -1
# working directory
time_id = get_current_time()
log_dir = os.path.join("outputs", args.exp_name, args.data_name, "[" + args.exp_name + "]_[" + args.data_name + "]_[" + args.note + "]_[" + time_id + "]_[GPU_" + os.environ["CUDA_VISIBLE_DEVICES"] + "]_" + "[" + platform.node() + "]")
logs_path = os.path.join(os.path.join(log_dir, "tb"), "train")
logs_path_val = os.path.join(os.path.join(log_dir, "tb"), "val")
os.makedirs(logs_path, exist_ok=True)
os.makedirs(logs_path_val, exist_ok=True)
os.makedirs(os.path.join(log_dir, "cp"), exist_ok=True)
# tensorboard logs
writer = SummaryWriter(log_dir=logs_path, flush_secs=1)
writer_val = SummaryWriter(log_dir=logs_path_val, flush_secs=1)
print(">>> Tensorboard logs saved to: {}".format(logs_path))
print(">>> Tensorboard logs saved to: {}".format(logs_path_val))
log_fn = os.path.join(log_dir, args.exp_name + "_" + args.data_name + "_" + args.note + "_" + time_id + ".log")
if args.log2file:
sys.stdout = open(log_fn, "w")
sys.stderr = sys.stdout
logging.basicConfig(filename=log_fn, filemode="a")
print(">>> Logs saved to: {}".format(log_fn))
writer_val.add_text("start_time", time_id, 0)
writer_val.flush()
# starting time
t0 = datetime.datetime.now()
# print args to console
print("===========================")
print(args)
print("===========================")
proc_id = os.getpid()
print(">>> proccess ID:", proc_id)
print("\nCUDNN VERSION: {}\n".format(torch.backends.cudnn.version()))
# adding logs
args.init_date = "[" + time_id + "]"
args.proc_id = proc_id
args.app = "[" + args.exp_name + "_" + args.data_name + "]_[" + args.note + "]"
args.gpu = os.environ["CUDA_VISIBLE_DEVICES"]
args.node = platform.node()
args.path = log_dir
# PyTorch device
# device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# create model
print("=> creating model...")
model = my_model(
affine=args.affine,
num_branches=args.num_branches,
).to(device)
# initialize weights
if args.init_weights:
model._initialize_weights()
# define loss functions, optimizer, and learning rate scheduler
criterion_1 = AttL1Loss(lamb=args.ada_lamb, eps=args.ada_eps, eps_2=args.ada_eps_2).to(device)
criterion_1.print_params()
criterion_2 = VGGPerceptualLoss().to(device)
optimizer = torch.optim.Adam(model.parameters(), args.lr, betas=(0.9, 0.999))
print(optimizer)
scheduler = torch.optim.lr_scheduler.LinearLR(
optimizer,
start_factor=1, end_factor=args.eta_min / args.lr,
total_iters=args.T_0 - 1,
)
print(scheduler)
for ggg in optimizer.param_groups:
ggg['lr'] = args.lr
# evaluation metrics
compute_metrics = create_metrics(args, device=device)
# moire data loaders
train_dataset = MoireDataset(
data_path=args.data_path,
sub_dir=args.train_dir,
moire_dir=args.moire_dir, clean_dir=args.clean_dir,
data_name=args.data_name,
is_training=True,
transform=None,
adaloss=args.adaloss,
)
val_dataset = MoireDataset(
data_path=args.data_path,
sub_dir=args.test_dir,
moire_dir=args.moire_dir, clean_dir=args.clean_dir,
data_name=args.data_name,
is_training=False,
transform=None,
adaloss=False, # no adaptive loss for validation
)
print("args.batch_size", args.batch_size)
print("args.test_batch_size", args.test_batch_size)
train_loader = torch.utils.data.DataLoader(
train_dataset, batch_size=args.batch_size, shuffle=True,
num_workers=args.workers, pin_memory=True)
val_loader = torch.utils.data.DataLoader(
val_dataset, batch_size=args.test_batch_size, shuffle=False,
num_workers=args.workers, pin_memory=True)
# initialize accelerator
model, optimizer, train_loader, val_loader, scheduler = accelerator.prepare(model, optimizer, train_loader, val_loader, scheduler)
# optionally resume from a checkpoint
if os.path.isfile(args.resume):
print("=> loading checkpoint '{}'".format(args.resume))
checkpoint = torch.load(args.resume, map_location = lambda storage, loc: storage.cuda())
print("=> loading model")
model.load_state_dict(checkpoint['state_dict'], strict=False)
try:
scheduler.load_state_dict(checkpoint['scheduler'])
except:
print(">>> scheduler not loaded")
pass
try:
optimizer.load_state_dict(checkpoint['optimizer'])
except:
print(">>> optimizer not loaded")
for ggg in optimizer.param_groups:
ggg['lr'] = scheduler.get_last_lr()[0]
print(">>> lr reset to {}".format(scheduler.get_last_lr()[0]))
pass
# optimizer.param_groups[0]['capturable'] = True
print("=> loaded checkpoint '{}'".format(args.resume))
if args.evaluate:
val_loss, val_lossl1, val_lossper, val_psnr, val_ssim, val_lossl1_norm = validate(val_loader, model, device, criterion_1, criterion_2, t0, args.start_epoch - 1, args, writer_val, compute_metrics)
return
else:
print("=> no checkpoint found at '{}'".format(args.resume))
# start training
epoch = args.start_epoch
print(">>> start epoch: {}".format(epoch))
args.evaluate = args.calc_mets
print(">>> args.evaluate: {}".format(args.evaluate))
try:
while epoch < args.epochs:
# reset learning rate
if epoch % args.T_0 == 0: # epoch 50, 100, ...
for ggg in optimizer.param_groups:
ggg['lr'] = args.lr
# reset learning rate scheduler
scheduler = torch.optim.lr_scheduler.LinearLR(
optimizer,
start_factor=1, end_factor=args.eta_min / args.lr,
total_iters=args.T_0 - 1,
)
print(scheduler)
lr = optimizer.param_groups[0]["lr"]
writer_val.add_scalar('z/lr', lr, epoch)
writer_val.flush()
# training
train_loss, train_lossl1, train_lossper, train_psnr, train_ssim, train_lossl1_norm = train(accelerator, train_loader, model, device, criterion_1, criterion_2, optimizer, epoch, args, t0, lr, writer, compute_metrics)
# tensorboard logs
writer.add_scalar('loss/loss', train_loss, epoch)
writer.add_scalar('loss/lossl1', train_lossl1, epoch)
writer.add_scalar('loss/lossl1_norm', train_lossl1_norm, epoch)
writer.add_scalar('loss/lossper', train_lossper, epoch)
if train_psnr > 0 or train_ssim > 0:
writer.add_scalar('met/psnr', train_psnr, epoch)
writer.add_scalar('met/ssim', train_ssim, epoch)
writer.flush()
# validation
if not args.dont_calc_mets_at_all:
if (epoch + 1) % round(args.T_0 / 2) == 0 or epoch % args.T_0 == 0 or args.evaluate:
val_loss, val_lossl1, val_lossper, val_psnr, val_ssim, val_lossl1_norm = validate(val_loader, model, device, criterion_1, criterion_2, t0, epoch, args, writer_val, compute_metrics)
else:
val_loss = val_lossl1 = val_lossper = val_psnr = val_ssim = val_lossl1_norm = 0
# tensorboard logs
if val_loss > 0 or val_lossl1 > 0 or val_lossl1_norm > 0 or val_lossper > 0 or val_psnr > 0 or val_ssim > 0:
writer_val.add_scalar('loss/loss', val_loss, epoch)
writer_val.add_scalar('loss/lossl1', val_lossl1, epoch)
writer_val.add_scalar('loss/lossl1_norm', val_lossl1_norm, epoch)
writer_val.add_scalar('loss/lossper', val_lossper, epoch)
writer_val.add_scalar('met/psnr', val_psnr, epoch)
writer_val.add_scalar('met/ssim', val_ssim, epoch)
try:
# model params
for name, param in model.named_parameters():
writer_val.add_histogram("param/" + name, param.clone().cpu().data.numpy(), epoch)
if param.grad is not None:
writer_val.add_histogram("grad/" + name, param.grad.cpu(), epoch)
except:
pass
writer.flush()
writer_val.flush()
# learning rate scheduling
scheduler.step()
# check if is best
is_best = val_psnr > best_psnr
best_psnr = max(val_psnr, best_psnr)
if is_best:
best_epoch = epoch
best_psnr = val_psnr
cor_ssim = val_ssim
writer_val.add_text('best', 'best val PSNR {0} | val SSIM {1}\n'.format(best_psnr, cor_ssim), epoch)
writer_val.flush()
# save checkpoint
save_checkpoint({
'state_dict': model.state_dict(),
'best_psnr': best_psnr,
'cor_ssim': cor_ssim,
'optimizer' : optimizer.state_dict(),
'scheduler' : scheduler.state_dict(),
}, is_best, log_dir, "{:04d}".format(epoch))
# print to console
print(
'## train PSNR {0} | train SSIM {1}\n'
'>> best val PSNR {2} | val SSIM {3}\n'.format(train_psnr, train_ssim, best_psnr, cor_ssim)
)
# next epoch
epoch += 1
# training finished!
writer_val.add_text("finished_time", get_current_time(), 0)
writer_val.flush()
writer_val.close()
writer.close()
print("finished!")
except Exception as e:
logging.error(traceback.format_exc())
def train(accelerator, train_loader, model, device, criterion_1, criterion_2, optimizer, epoch, args, t0, lr, writer, compute_metrics):
"""
The function `train` trains a model using a given train loader, computes various losses, and updates
the model parameters using SGD optimization.
:param train_loader: The train_loader is a data loader object that provides batches of training
data. It is used to iterate over the training dataset during each epoch of training
:param model: The model is the neural network model that you are training. It takes the moire image
as input and outputs the predicted clean image
:param device: The "device" parameter is used to specify the device (CPU or GPU) on which the model
and data should be loaded. It is typically a torch.device object
:param criterion_1: The criterion_1 is the loss function used to compute the L1 loss between the
model's output and the clean image. It is typically a function that takes the output and target
tensors as inputs and returns the loss value
:param criterion_2: The `criterion_2` parameter is the loss function used for the perceptual loss.
It is a function that takes the model output and the ground truth clean image as inputs and returns
the loss value
:param optimizer: The optimizer is an object that implements the optimization algorithm. It is used
to update the model's parameters based on the computed gradients
:param epoch: The current epoch number of the training process
:param args: The `args` parameter is a namespace object that contains various arguments and
hyperparameters for the training process. It is used to configure the behavior of the training loop
and the model
:param t0: The variable `t0` is the starting time of the training process. It is used to calculate
the elapsed time for each epoch
:param lr: The learning rate used for optimization
:param writer: The `writer` parameter is an instance of `torch.utils.tensorboard.SummaryWriter`
which is used to write the training progress and visualizations to TensorBoard
:param compute_metrics: The `compute_metrics` parameter is a function that is used to compute
metrics such as PSNR and SSIM. It takes two arguments: the output image and the ground truth image.
The function should return the computed metrics
:return: the average values of the losses (total loss, l1 loss, perceptual loss), PSNR, SSIM, and
normalized l1 loss.
"""
# training meters
losses = AverageMeter()
lossl1 = AverageMeter()
lossl1_norm = AverageMeter()
lossper = AverageMeter()
psnr = AverageMeter()
ssim = AverageMeter()
loss_l1_1 = torch.tensor(0.0).to(device)
norm_loss_l1_1 = torch.tensor(0.0).to(device)
loss_l1_2 = torch.tensor(0.0).to(device)
norm_loss_l1_2 = torch.tensor(0.0).to(device)
loss_l1_3 = torch.tensor(0.0).to(device)
norm_loss_l1_3 = torch.tensor(0.0).to(device)
loss_per = torch.tensor(0.0).to(device)
current_psnr = torch.tensor(0.0).to(device)
current_ssim = torch.tensor(0.0).to(device)
# switch to train mode
model.train()
# number of samples in the data loader
train_loader_len = len(train_loader) * args.batch_size
proc_items = 0
print(">>> number of train samples: ", train_loader_len)
with tqdm(total=train_loader_len, dynamic_ncols=True, bar_format="[train] {percentage:3.0f}%|{bar:10}| {n_fmt}/{total_fmt} [{elapsed}<{remaining},{rate_fmt}{postfix}] {desc}", desc="E:%03d | P:%.4f | lr:%.6e | L:%.2f | L1:%.2f | L1n:%.2f | Lp:%.2f | S:%.4f (%s)" % (epoch, psnr.avg, optimizer.param_groups[0]["lr"], losses.avg, lossl1.avg, lossl1_norm.avg, lossper.avg, ssim.avg, str(datetime.datetime.now() - t0).split(".")[0]), ascii="-#") as pbar:
for i_batch, data in enumerate(train_loader):
# move data to the same device as model
moire_img = data["moire"].to(device)
clean_img = data["clean"].to(device)
clean_freq = data["clean_freq"].to(device)
# compute pixel rarity (based on "histogram")
if clean_freq.shape[1] == 1:
clean_freq = None
else:
clean_freq = clean_freq.long()
for ib in range(clean_img.shape[0]):
freq_its = clean_freq[ib]
bins = torch.bincount(freq_its)
clean_freq[ib] = bins[freq_its.long()]
clean_freq = clean_freq.reshape(clean_img.shape[0], 1, clean_img.shape[2], clean_img.shape[3])
clean_freq = clean_freq.float()
clean_freq /= clean_img.shape[2] * clean_img.shape[3]
# blur
kersize = int(min(clean_img.shape[2], clean_img.shape[3]) / 68)
if kersize % 2 == 0:
kersize += 1
clean_freq = transforms.GaussianBlur(kernel_size=(kersize, kersize), sigma=(5.0, 5.0))(clean_freq)
# multi-scale ground truths
clean_img_2 = F.interpolate(clean_img, scale_factor=0.5, mode='bilinear', align_corners=False)
clean_img_3 = F.interpolate(clean_img, scale_factor=0.25, mode='bilinear', align_corners=False)
if args.num_branches >= 4:
clean_img_4 = F.interpolate(clean_img, scale_factor=0.125, mode='bilinear', align_corners=False)
if args.num_branches >= 5:
clean_img_5 = F.interpolate(clean_img, scale_factor=0.0625, mode='bilinear', align_corners=False)
try:
clean_freq_2 = F.interpolate(clean_freq, scale_factor=0.5, mode='bilinear', align_corners=False)
clean_freq_3 = F.interpolate(clean_freq, scale_factor=0.25, mode='bilinear', align_corners=False)
if args.num_branches >= 4:
clean_freq_4 = F.interpolate(clean_freq, scale_factor=0.125, mode='bilinear', align_corners=False)
if args.num_branches >= 5:
clean_freq_5 = F.interpolate(clean_freq, scale_factor=0.0625, mode='bilinear', align_corners=False)
except:
clean_freq_2 = None
clean_freq_3 = None
if args.num_branches >= 4:
clean_freq_4 = None
if args.num_branches >= 5:
clean_freq_5 = None
# compute outputs
if args.num_branches == 3:
output, output_2, output_3 = model(moire_img)
elif args.num_branches == 4:
output, output_2, output_3, output_4 = model(moire_img)
elif args.num_branches == 5:
output, output_2, output_3, output_4, output_5 = model(moire_img)
# l1 norm
if args.l1loss:
loss_l1_1, norm_loss_l1_1 = criterion_1(output, clean_img, clean_freq, max_lr=args.lr, min_lr=args.eta_min, lr=lr)
loss_l1_2, norm_loss_l1_2 = criterion_1(output_2, clean_img_2, clean_freq_2, max_lr=args.lr, min_lr=args.eta_min, lr=lr)
loss_l1_3, norm_loss_l1_3 = criterion_1(output_3, clean_img_3, clean_freq_3, max_lr=args.lr, min_lr=args.eta_min, lr=lr)
if args.num_branches >= 4:
loss_l1_4, norm_loss_l1_4 = criterion_1(output_4, clean_img_4, clean_freq_4, max_lr=args.lr, min_lr=args.eta_min, lr=lr)
if args.num_branches >= 5:
loss_l1_5, norm_loss_l1_5 = criterion_1(output_5, clean_img_5, clean_freq_5, max_lr=args.lr, min_lr=args.eta_min, lr=lr)
loss_l1 = loss_l1_1 + loss_l1_2 + loss_l1_3
norm_loss_l1 = norm_loss_l1_1 + norm_loss_l1_2 + norm_loss_l1_3
if args.num_branches >= 4:
loss_l1 += loss_l1_4
norm_loss_l1 += norm_loss_l1_4
if args.num_branches >= 5:
loss_l1 += loss_l1_5
norm_loss_l1 += norm_loss_l1_5
# perceptual loss
if args.perloss:
loss_per = criterion_2(output, clean_img, feature_layers=[2]) + \
criterion_2(output_2, clean_img_2, feature_layers=[2]) + \
criterion_2(output_3, clean_img_3, feature_layers=[2])
if args.num_branches >= 4:
loss_per += criterion_2(output_4, clean_img_4, feature_layers=[2])
if args.num_branches >= 5:
loss_per += criterion_2(output_5, clean_img_5, feature_layers=[2])
# total loss
loss = loss_l1 + loss_per
# compute gradient and do SGD step
optimizer.zero_grad()
accelerator.backward(loss)
optimizer.step()
# measure PSNR and SSIM
if not args.dont_calc_mets_at_all and args.calc_train_mets and not args.dont_calc_train_mets:
if (epoch + 1) % round(args.T_0 / 2) == 0 or epoch % args.T_0 == 0 or args.evaluate:
with torch.no_grad():
try:
# _, current_psnr, current_ssim = compute_metrics.compute(torch.clamp(output, 0, 1), clean_img)
_, current_psnr, current_ssim = compute_metrics.compute(output, clean_img)
except Exception as e:
pass
# update meters
losses.update(loss.item(), moire_img.size(0))
lossl1.update(loss_l1.item(), moire_img.size(0))
lossl1_norm.update(norm_loss_l1.item(), moire_img.size(0))
lossper.update(loss_per.item(), moire_img.size(0))
try:
psnr.update(current_psnr.item(), moire_img.size(0))
ssim.update(current_ssim.item(), moire_img.size(0))
except:
psnr.update(current_psnr, moire_img.size(0))
ssim.update(current_ssim, moire_img.size(0))
# update progress bar
proc_items += moire_img.size(0)
if train_loader_len > 0:
if (i_batch == train_loader_len - 1) or (i_batch % max(5, round(train_loader_len / args.print_freq)) == 0):
pbar.set_description_str("E:%03d | P:%.4f | lr:%.6e | L:%.2f | L1:%.2f | L1n:%.2f | Lp:%.2f | S:%.4f (%s)" % (epoch, psnr.avg, optimizer.param_groups[0]["lr"], losses.avg, lossl1.avg, lossl1_norm.avg, lossper.avg, ssim.avg, str(datetime.datetime.now() - t0).split(".")[0]), refresh=False)
pbar.update(proc_items)
proc_items = 0
# tensorboard images
with torch.no_grad():
num_dis_imgs = min(6, args.batch_size)
if args.num_branches == 3:
num_imgs_per_row = 5
dis_text = "0/in_gt_out1_out2_out3"
elif args.num_branches == 4:
num_imgs_per_row = 6
dis_text = "0/in_gt_out1_out2_out3_out4"
elif args.num_branches == 5:
num_imgs_per_row = 7
dis_text = "0/in_gt_out1_out2_out3_out4_out5"
# re-scale outputs to save space
output_2 = F.interpolate(output_2, size=(output.shape[2], output.shape[3]), mode="bilinear", align_corners=False)
output_3 = F.interpolate(output_3, size=(output.shape[2], output.shape[3]), mode="bilinear", align_corners=False)
if args.num_branches >= 4:
output_4 = F.interpolate(output_4, size=(output.shape[2], output.shape[3]), mode="bilinear", align_corners=False)
if args.num_branches >= 5:
output_5 = F.interpolate(output_5, size=(output.shape[2], output.shape[3]), mode="bilinear", align_corners=False)
# add images to tensorboard
imgs = []
for i_id in np.arange(0, num_dis_imgs):
imgs.append(moire_img[i_id])
imgs.append(torch.clamp(output[i_id], 0, 1))
imgs.append(torch.clamp(output_2[i_id], 0, 1))
imgs.append(torch.clamp(output_3[i_id], 0, 1))
if args.num_branches >= 4:
imgs.append(torch.clamp(output_4[i_id], 0, 1))
if args.num_branches >= 5:
imgs.append(torch.clamp(output_5[i_id], 0, 1))
imgs.append(clean_img[i_id])
grid = torchvision.utils.make_grid(imgs, num_imgs_per_row)
writer.add_image(dis_text, grid, epoch)
writer.flush()
return losses.avg, lossl1.avg, lossper.avg, psnr.avg, ssim.avg, lossl1_norm.avg
def validate(val_loader, model, device, criterion_1, criterion_2, t0, epoch, args, writer, compute_metrics):
"""
The function `validate` is used to evaluate the performance of a model on a validation dataset,
calculating various metrics such as loss, PSNR, and SSIM, and visualizing the input, ground truth,
and output images using TensorBoard.
:param val_loader: The validation data loader, which provides batches of data for validation
:param model: The `model` parameter is the neural network model that will be used for validation. It
should be an instance of a PyTorch model class
:param device: The "device" parameter is used to specify the device (CPU or GPU) on which the model
and data should be loaded. It is typically a torch.device object
:param criterion_1: The `criterion_1` parameter is the loss function used to compute the L1 loss
between the model's output and the clean image. It is typically a function that takes the output and
target tensors as inputs and returns the loss value
:param criterion_2: The `criterion_2` parameter is the loss function used to calculate the
perceptual loss. It is a function that takes the output of the model and the clean image as inputs
and returns the loss value
:param t0: The parameter `t0` is not explicitly defined in the code snippet you provided. It is
likely defined elsewhere in your code. Please provide more information or the definition of `t0` for
further assistance
:param epoch: The current epoch number
:param args: The `args` parameter is a dictionary or object that contains various configuration
settings for the validation process. It likely includes settings such as the batch size, number of
branches, data name, whether to use L1 loss or perceptual loss, and other parameters specific to the
model being used
:param writer: The `writer` parameter is an instance of `torch.utils.tensorboard.SummaryWriter`
which is used to write the training and validation metrics to TensorBoard. It is used to visualize
the training progress and monitor the performance of the model
:param compute_metrics: The `compute_metrics` parameter is a function that is used to compute the
metrics (PSNR and SSIM) between the output of the model and the clean image. It takes two arguments:
the output tensor and the clean image tensor. The function should return the metrics as
floating-point numbers
:return: the average values of the losses (total loss, l1 loss, perceptual loss), PSNR (Peak
Signal-to-Noise Ratio), SSIM (Structural Similarity Index), and normalized l1 loss.
"""
# validation meters
losses = AverageMeter()
lossl1 = AverageMeter()
lossl1_norm = AverageMeter()
lossper = AverageMeter()
psnr = AverageMeter()
ssim = AverageMeter()
loss_l1_1 = torch.tensor(0.0).to(device)
norm_loss_l1_1 = torch.tensor(0.0).to(device)
loss_per = torch.tensor(0.0).to(device)
current_psnr = torch.tensor(0.0).to(device)
current_ssim = torch.tensor(0.0).to(device)
# number of samples in the data loader
proc_items = 0
val_loader_len = len(val_loader) * args.test_batch_size
print(">>> number of val samples: ", val_loader_len)
# random image id for tensorboard
ran_img_id = random.randint(0, len(val_loader) - 1)
print(">>> ran_img_id: ", ran_img_id)
val_moire_img = None
val_clean_img = None
val_output = None
# switch to evaluate mode
model.eval()
with torch.no_grad():
with tqdm(total=val_loader_len, dynamic_ncols=True, bar_format="> [val] {percentage:3.0f}%|{bar:10}| {n_fmt}/{total_fmt} [{elapsed}<{remaining},{rate_fmt}{postfix}] {desc}", desc="E:%03d | P:%.4f | L:%.2f | L1:%.2f | L1n:%.2f | Lp:%.2f | S:%.4f (%s)" % (epoch, psnr.avg, losses.avg, lossl1.avg, lossl1_norm.avg, lossper.avg, ssim.avg, str(datetime.datetime.now() - t0).split(".")[0]), ascii="-#") as pbar:
for i_batch, data in enumerate(val_loader):
# move data to the same device as model
moire_img = data["moire"].to(device)
clean_img = data["clean"].to(device)
# image padding for multi-scale inference
_, _, h, w = moire_img.size()
if args.data_name == "fhdmi":
if args.num_branches == 3:
w_pad = (math.ceil(w/32)*32 - w) // 2
h_pad = (math.ceil(h/32)*32 - h) // 2
elif args.num_branches == 4:
w_pad = (math.ceil(w/64)*64 - w) // 2
h_pad = (math.ceil(h/64)*64 - h) // 2
elif args.num_branches == 5:
w_pad = (math.ceil(w/128)*128 - w) // 2
h_pad = (math.ceil(h/128)*128 - h) // 2
else:
w_pad = (math.ceil(w/32)*32 - w) // 2
h_pad = (math.ceil(h/32)*32 - h) // 2
moire_img = img_pad(moire_img, w_r=w_pad, h_r=h_pad)
# compute output
if args.num_branches == 3:
output, _, _ = model(moire_img)
elif args.num_branches == 4:
output, _, _, _ = model(moire_img)
elif args.num_branches == 5:
output, _, _, _, _ = model(moire_img)
# remove padding
if h_pad != 0:
output = output[:, :, h_pad:-h_pad, :]
if w_pad != 0:
output = output[:, :, :, w_pad:-w_pad]
# l1 norm
if args.l1loss and args.calc_val_losses:
loss_l1_1, norm_loss_l1_1 = criterion_1(output, clean_img)
loss_l1 = loss_l1_1
norm_loss_l1 = norm_loss_l1_1
# perceptual loss
if args.perloss and args.calc_val_losses:
loss_per = criterion_2(output, clean_img, feature_layers=[2])
# total loss
loss = loss_l1 + loss_per
# save images for tensorboard visualization
if i_batch == ran_img_id:
val_moire_img = moire_img.detach().cpu()
val_clean_img = clean_img.detach().cpu()
val_output = output.detach().cpu()
# measure PSNR and SSIM
if not args.dont_calc_mets_at_all:
if (epoch + 1) % round(args.T_0 / 2) == 0 or epoch % args.T_0 == 0 or args.evaluate:
try:
_, current_psnr, current_ssim = compute_metrics.compute(output, clean_img)
except Exception as e:
pass
# update meters
losses.update(loss, moire_img.size(0))
lossl1.update(loss_l1, moire_img.size(0))
lossl1_norm.update(norm_loss_l1, moire_img.size(0))
lossper.update(loss_per, moire_img.size(0))
psnr.update(current_psnr, moire_img.size(0))
ssim.update(current_ssim, moire_img.size(0))
# update progress bar
proc_items += moire_img.size(0)
if val_loader_len > 0:
if (i_batch == val_loader_len - 1) or (i_batch % max(5, round(val_loader_len / args.print_freq)) == 0):
pbar.set_description_str("E:%03d | P:%.4f | L:%.2f | L1:%.2f | L1n:%.2f | Lp:%.2f | S:%.4f (%s)" % (epoch, psnr.avg, losses.avg, lossl1.avg, lossl1_norm.avg, lossper.avg, ssim.avg, str(datetime.datetime.now() - t0).split(".")[0]), refresh=False)
pbar.update(proc_items)
proc_items = 0
# if i_batch > 1:
# break
print('## val PSNR {psnr.avg:.5f} | val SSIM {ssim.avg:.5f}'.format(psnr=psnr, ssim=ssim))
# tensorboard images
try:
num_dis_imgs = min(6, args.test_batch_size)
_, _, img_h, img_w = val_moire_img.shape
# resize images to save space
val_clean_img = F.interpolate(val_clean_img, size=(img_h, img_w), mode="bilinear", align_corners=False)
val_output = F.interpolate(val_output, size=(img_h, img_w), mode="bilinear", align_corners=False)
imgs = torch.cat(
(
val_moire_img[:num_dis_imgs],
val_clean_img[:num_dis_imgs],
torch.clamp(val_output[:num_dis_imgs], 0, 1),
),
dim=0
)
grid = torchvision.utils.make_grid(imgs, num_dis_imgs)
writer.add_image("in_gt_out", grid, epoch)
writer.flush()
except:
logging.warning(traceback.format_exc())
pass
return losses.avg, lossl1.avg, lossper.avg, psnr.avg, ssim.avg, lossl1_norm.avg
def gaussian(window_size, sigma):
gauss = torch.Tensor([exp(-(x - window_size//2)**2/float(2*sigma**2)) for x in range(window_size)])
return gauss/gauss.sum()
def create_window(window_size, channel=1):
_1D_window = gaussian(window_size, 1.5).unsqueeze(1)
_2D_window = _1D_window.mm(_1D_window.t()).float().unsqueeze(0).unsqueeze(0)
window = _2D_window.expand(channel, 1, window_size, window_size).contiguous()
return window
def ssim(img1, img2, window_size=11, window=None, size_average=True, full=False, val_range=None):
# Value range can be different from 255. Other common ranges are 1 (sigmoid) and 2 (tanh).
if val_range is None:
if torch.max(img1) > 128:
max_val = 255
else:
max_val = 1
if torch.min(img1) < -0.5:
min_val = -1
else:
min_val = 0
L = max_val - min_val
else:
L = val_range
padd = 0
(_, channel, height, width) = img1.size()
if window is None:
real_size = min(window_size, height, width)
window = create_window(real_size, channel=channel).to(img1.device)
mu1 = F.conv2d(img1, window, padding=padd, groups=channel)
mu2 = F.conv2d(img2, window, padding=padd, groups=channel)
mu1_sq = mu1.pow(2)
mu2_sq = mu2.pow(2)
mu1_mu2 = mu1 * mu2
sigma1_sq = F.conv2d(img1 * img1, window, padding=padd, groups=channel) - mu1_sq
sigma2_sq = F.conv2d(img2 * img2, window, padding=padd, groups=channel) - mu2_sq
sigma12 = F.conv2d(img1 * img2, window, padding=padd, groups=channel) - mu1_mu2
C1 = (0.01 * L) ** 2
C2 = (0.03 * L) ** 2
v1 = 2.0 * sigma12 + C2
v2 = sigma1_sq + sigma2_sq + C2
cs = torch.mean(v1 / v2) # contrast sensitivity
ssim_map = ((2 * mu1_mu2 + C1) * v1) / ((mu1_sq + mu2_sq + C1) * v2)
if size_average:
ret = ssim_map.mean()
else:
ret = ssim_map.mean(1).mean(1).mean(1)
if full:
return ret, cs
return ret
# Classes to re-use window
class SSIM(torch.nn.Module):
"""
Fast pytorch implementation for SSIM, referred from
"https://github.com/jorge-pessoa/pytorch-msssim/blob/master/pytorch_msssim/__init__.py"
"""
def __init__(self, window_size=11, size_average=True, val_range=None):
super(SSIM, self).__init__()
self.window_size = window_size
self.size_average = size_average
self.val_range = val_range
# Assume 1 channel for SSIM
self.channel = 1
self.window = create_window(window_size)
def forward(self, img1, img2):
(_, channel, _, _) = img1.size()
if channel == self.channel and self.window.dtype == img1.dtype:
window = self.window
else:
window = create_window(self.window_size, channel).to(img1.device).type(img1.dtype)
self.window = window
self.channel = channel
return ssim(img1, img2, window=window, window_size=self.window_size, size_average=self.size_average)
class PSNR(torch.nn.Module):
def __init__(self):
super(PSNR, self).__init__()
def forward(self, img1, img2):
psnr = -10*torch.log10(torch.mean((img1-img2)**2))
return psnr
def generate_1d_gaussian_kernel():
return cv2.getGaussianKernel(11, 1.5)
def generate_2d_gaussian_kernel():
kernel = generate_1d_gaussian_kernel()
return np.outer(kernel, kernel.transpose())
def generate_3d_gaussian_kernel():
kernel = generate_1d_gaussian_kernel()
window = generate_2d_gaussian_kernel()
return np.stack([window * k for k in kernel], axis=0)
class MATLAB_SSIM(torch.nn.Module):
def __init__(self, device='cpu'):
super(MATLAB_SSIM, self).__init__()
self.device = device
conv3d = torch.nn.Conv3d(1, 1, (11, 11, 11), stride=1, padding=(5, 5, 5), bias=False, padding_mode='replicate')
conv3d.weight.requires_grad = False
conv3d.weight[0, 0, :, :, :] = torch.tensor(generate_3d_gaussian_kernel())
self.conv3d = conv3d.to(device)
conv2d = torch.nn.Conv2d(1, 1, (11, 11), stride=1, padding=(5, 5), bias=False, padding_mode='replicate')
conv2d.weight.requires_grad = False
conv2d.weight[0, 0, :, :] = torch.tensor(generate_2d_gaussian_kernel())
self.conv2d = conv2d.to(device)
def forward(self, img1, img2):
assert len(img1.shape) == len(img2.shape)
with torch.no_grad():
img1 = torch.tensor(img1).to(self.device).float()
img2 = torch.tensor(img2).to(self.device).float()
if len(img1.shape) == 2:
conv = self.conv2d
elif len(img1.shape) == 3:
conv = self.conv3d
else:
raise not NotImplementedError('only support 2d / 3d images.')
return self._ssim(img1, img2, conv)
def _ssim(self, img1, img2, conv):
img1 = img1.unsqueeze(0).unsqueeze(0)
img2 = img2.unsqueeze(0).unsqueeze(0)
C1 = (0.01 * 255) ** 2
C2 = (0.03 * 255) ** 2
mu1 = conv(img1)
mu2 = conv(img2)
mu1_sq = mu1 ** 2
mu2_sq = mu2 ** 2
mu1_mu2 = mu1 * mu2
sigma1_sq = conv(img1 ** 2) - mu1_sq
sigma2_sq = conv(img2 ** 2) - mu2_sq
sigma12 = conv(img1 * img2) - mu1_mu2
ssim_map = ((2 * mu1_mu2 + C1) *
(2 * sigma12 + C2)) / ((mu1_sq + mu2_sq + C1) *
(sigma1_sq + sigma2_sq + C2))
return float(ssim_map.mean())
def tensor2img(tensor, out_type=np.uint8, min_max=(0, 1)):
tensor = tensor.squeeze().float().cpu().clamp_(*min_max)
tensor = (tensor - min_max[0]) / (min_max[1] - min_max[0])
n_dim = tensor.dim()
if n_dim == 4: