forked from victorca25/traiNNer
-
Notifications
You must be signed in to change notification settings - Fork 8
/
CustomTrainClass.py
1341 lines (1105 loc) · 70.8 KB
/
CustomTrainClass.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
import yaml
import cv2
with open("config.yaml", "r") as ymlfile:
cfg = yaml.safe_load(ymlfile)
from loss.loss import FocalFrequencyLoss, feature_matching_loss, FrobeniusNormLoss, LapLoss, CharbonnierLoss, GANLoss, GradientPenaltyLoss, HFENLoss, TVLoss, GradientLoss, ElasticLoss, RelativeL1, L1CosineSim, ClipL1, MaskedL1Loss, MultiscalePixelLoss, FFTloss, OFLoss, L1_regularization, ColorLoss, AverageLoss, GPLoss, CPLoss, SPL_ComputeWithTrace, SPLoss, Contextual_Loss, StyleLoss
from loss.metrics import *
from torchvision.utils import save_image
from torch.autograd import Variable
import pytorch_lightning as pl
from tensorboardX import SummaryWriter
writer = SummaryWriter(logdir=cfg['path']['log_path'])
from init import weights_init
import os
import numpy as np
if cfg['train']['diffaug'] == True:
from loss.diffaug import DiffAugment
if cfg['network_G']['CEM'] == True:
from arch.CEM import CEMnet
class CustomTrainClass(pl.LightningModule):
def __init__(self):
super().__init__()
############################
# generators with one output, no AMP means nan loss during training
if cfg['network_G']['netG'] == 'RRDB_net':
from arch.rrdb_arch import RRDBNet
self.netG = RRDBNet(in_nc=cfg['network_G']['in_nc'], out_nc=cfg['network_G']['out_nc'], nf=cfg['network_G']['nf'], nb=cfg['network_G']['nb'], gc=cfg['network_G']['gc'], upscale=cfg['scale'], norm_type=cfg['network_G']['norm_type'],
act_type=cfg['network_G']['net_act'], mode=cfg['network_G']['mode'], upsample_mode=cfg['network_G']['upsample_mode'], convtype=cfg['network_G']['convtype'],
finalact=cfg['network_G']['finalact'], gaussian_noise=cfg['network_G']['gaussian'], plus=cfg['network_G']['plus'],
nr=cfg['network_G']['nr'])
# DFNet
elif cfg['network_G']['netG'] == 'DFNet':
from arch.DFNet_arch import DFNet
self.netG = DFNet(c_img=cfg['network_G']['c_img'], c_mask=cfg['network_G']['c_mask'], c_alpha=cfg['network_G']['c_alpha'],
mode=cfg['network_G']['mode'], norm=cfg['network_G']['norm'], act_en=cfg['network_G']['act_en'], act_de=cfg['network_G']['act_de'],
en_ksize=cfg['network_G']['en_ksize'], de_ksize=cfg['network_G']['de_ksize'],
blend_layers=cfg['network_G']['blend_layers'], conv_type=cfg['network_G']['conv_type'])
# AdaFill
elif cfg['network_G']['netG'] == 'AdaFill':
from arch.AdaFill_arch import InpaintNet
self.netG = InpaintNet()
# MEDFE (batch_size: 1, no AMP)
elif cfg['network_G']['netG'] == 'MEDFE':
from arch.MEDFE_arch import MEDFEGenerator
self.netG = MEDFEGenerator()
# RFR
# conv_type = partial or deform
# Warning: One testrun with deform resulted in Nan errors after ~60k iterations. It is also very slow.
# 'partial' is recommended, since this is what the official implementation does use.
elif cfg['network_G']['netG'] == 'RFR':
from arch.RFR_arch import RFRNet
self.netG = RFRNet(conv_type=cfg['network_G']['conv_type'])
# LBAM
elif cfg['network_G']['netG'] == 'LBAM':
from arch.LBAM_arch import LBAMModel
self.netG = LBAMModel(inputChannels=cfg['network_G']['inputChannels'], outputChannels=cfg['network_G']['outputChannels'])
# DMFN
elif cfg['network_G']['netG'] == 'DMFN':
from arch.DMFN_arch import InpaintingGenerator
self.netG = InpaintingGenerator(in_nc=4, out_nc=3,nf=64,n_res=8,
norm='in', activation='relu')
# partial
elif cfg['network_G']['netG'] == 'Partial':
from arch.partial_arch import Model
self.netG = Model()
# RN
elif cfg['network_G']['netG'] == 'RN':
from arch.RN_arch import G_Net, rn_initialize_weights
self.netG = G_Net(input_channels=cfg['network_G']['input_channels'], residual_blocks=cfg['network_G']['residual_blocks'], threshold=cfg['network_G']['threshold'])
# using rn init to avoid errors
if self.global_step == 0:
RN_arch = rn_initialize_weights(self.netG, scale=0.1)
# DSNet
elif cfg['network_G']['netG'] == 'DSNet':
from arch.DSNet_arch import DSNet
self.netG = DSNet(layer_size=cfg['network_G']['layer_sizenr'], input_channels=cfg['network_G']['input_channels'], upsampling_mode=cfg['network_G']['upsampling_mode'])
# context_encoder
elif cfg['network_G']['netG'] == 'context_encoder':
from arch.context_encoder_arch import Net_G
self.netG = Net_G()
# MANet
elif cfg['network_G']['netG'] == 'MANet':
from arch.MANet_arch import PConvUNet
self.netG = PConvUNet()
# GPEN
elif cfg['network_G']['netG'] == 'GPEN':
from arch.GPEN_arch import FullGenerator
self.netG = FullGenerator(input_channels = cfg['network_G']['input_channels'], style_dim = cfg['network_G']['style_dim'],
n_mlp = cfg['network_G']['n_mlp'], channel_multiplier = cfg['network_G']['channel_multiplier'],
blur_kernel = cfg['network_G']['blur_kernel'], lr_mlp = cfg['network_G']['lr_mlp'])
# comodgan
elif cfg['network_G']['netG'] == 'comodgan':
from arch.comodgan_arch import Generator
self.netG = Generator(dlatent_size = cfg['network_G']['dlatent_size'], num_channels = cfg['network_G']['num_channels'], resolution = cfg['network_G']['resolution'], fmap_base = cfg['network_G']['fmap_base'], fmap_decay = cfg['network_G']['fmap_decay'], fmap_min = cfg['network_G']['fmap_min'], fmap_max = cfg['network_G']['fmap_max'], randomize_noise = cfg['network_G']['randomize_noise'], architecture = cfg['network_G']['architecture'], nonlinearity = cfg['network_G']['nonlinearity'], resample_kernel = cfg['network_G']['resample_kernel'], fused_modconv = cfg['network_G']['fused_modconv'], pix2pix = cfg['network_G']['pix2pix'], dropout_rate = cfg['network_G']['dropout_rate'], cond_mod = cfg['network_G']['cond_mod'], style_mod = cfg['network_G']['style_mod'], noise_injection = cfg['network_G']['noise_injection'])
# Experimental
#DSNetRRDB
elif cfg['network_G']['netG'] == 'DSNetRRDB':
from arch.experimental.DSNetRRDB_arch import DSNetRRDB
self.netG = DSNetRRDB(layer_size=8, input_channels=3, upsampling_mode='nearest',
in_nc=4, out_nc=3, nf=128, nb=8, gc=32, upscale=1, norm_type=None,
act_type='leakyrelu', mode='CNA', upsample_mode='upconv', convtype='Conv2D',
finalact=None, gaussian_noise=True, plus=False,
nr=3)
# DSNetDeoldify
elif cfg['network_G']['netG'] == 'DSNetDeoldify':
from arch.experimental.DSNetDeoldify_arch import DSNetDeoldify
self.netG = DSNetDeoldify()
elif cfg['network_G']['netG'] == 'lightweight_gan':
from arch.experimental.lightweight_gan_arch import Generator
self.netG = Generator(image_size=cfg['network_G']['image_size'],
latent_dim = cfg['network_G']['latent_dim'],
fmap_max = cfg['network_G']['fmap_max'],
fmap_inverse_coef = cfg['network_G']['fmap_inverse_coef'],
transparent = cfg['network_G']['transparent'],
greyscale = cfg['network_G']['greyscale'],
freq_chan_attn = cfg['network_G']['freq_chan_attn'])
elif cfg['network_G']['netG'] == 'SimpleFontGenerator512':
from arch.experimental.lightweight_gan_arch import SimpleFontGenerator512
self.netG = SimpleFontGenerator512(image_size=cfg['network_G']['image_size'],
latent_dim = cfg['network_G']['latent_dim'],
fmap_max = cfg['network_G']['fmap_max'],
fmap_inverse_coef = cfg['network_G']['fmap_inverse_coef'],
transparent = cfg['network_G']['transparent'],
greyscale = cfg['network_G']['greyscale'],
freq_chan_attn = cfg['network_G']['freq_chan_attn'])
elif cfg['network_G']['netG'] == 'SimpleFontGenerator256':
from arch.experimental.lightweight_gan_arch import SimpleFontGenerator256
self.netG = SimpleFontGenerator256(image_size=cfg['network_G']['image_size'],
latent_dim = cfg['network_G']['latent_dim'],
fmap_max = cfg['network_G']['fmap_max'],
fmap_inverse_coef = cfg['network_G']['fmap_inverse_coef'],
transparent = cfg['network_G']['transparent'],
greyscale = cfg['network_G']['greyscale'],
freq_chan_attn = cfg['network_G']['freq_chan_attn'])
############################
# generators with two outputs
# deepfillv1
elif cfg['network_G']['netG'] == 'deepfillv1':
from arch.deepfillv1_arch import InpaintSANet
self.netG = InpaintSANet()
# deepfillv2
# conv_type = partial or deform
elif cfg['network_G']['netG'] == 'deepfillv2':
from arch.deepfillv2_arch import GatedGenerator
self.netG = GatedGenerator(in_channels=cfg['network_G']['in_channels'], out_channels=cfg['network_G']['out_channels'],
latent_channels=cfg['network_G']['latent_channels'], pad_type=cfg['network_G']['pad_type'], activation=cfg['network_G']['activation'], norm=cfg['network_G']['norm'], conv_type = cfg['network_G']['conv_type'])
# Adaptive
# [Warning] Adaptive does not like PatchGAN, Multiscale and ResNet.
elif cfg['network_G']['netG'] == 'Adaptive':
from arch.Adaptive_arch import PyramidNet
self.netG = PyramidNet(in_channels=cfg['network_G']['in_channels'], residual_blocks=cfg['network_G']['residual_blocks'], init_weights=cfg['network_G']['init_weights'])
############################
# exotic generators
# Pluralistic
elif cfg['network_G']['netG'] == 'Pluralistic':
from arch.Pluralistic_arch import PluralisticGenerator
self.netG = PluralisticGenerator(ngf_E=cfg['network_G']['ngf_E'], z_nc_E=cfg['network_G']['z_nc_E'], img_f_E=cfg['network_G']['img_f_E'], layers_E=cfg['network_G']['layers_E'], norm_E=cfg['network_G']['norm_E'], activation_E=cfg['network_G']['activation_E'],
ngf_G=cfg['network_G']['ngf_G'], z_nc_G=cfg['network_G']['z_nc_G'], img_f_G=cfg['network_G']['img_f_G'], L_G=cfg['network_G']['L_G'], output_scale_G=cfg['network_G']['output_scale_G'], norm_G=cfg['network_G']['norm_G'], activation_G=cfg['network_G']['activation_G'])
# EdgeConnect
elif cfg['network_G']['netG'] == 'EdgeConnect':
from arch.EdgeConnect_arch import EdgeConnectModel
#conv_type_edge: 'normal' # normal | partial | deform (has no spectral_norm)
self.netG = EdgeConnectModel(residual_blocks_edge=cfg['network_G']['residual_blocks_edge'],
residual_blocks_inpaint=cfg['network_G']['residual_blocks_inpaint'], use_spectral_norm=cfg['network_G']['use_spectral_norm'],
conv_type_edge=cfg['network_G']['conv_type_edge'], conv_type_inpaint=cfg['network_G']['conv_type_inpaint'])
# FRRN
elif cfg['network_G']['netG'] == 'FRRN':
from arch.FRRN_arch import FRRNet
self.netG = FRRNet()
# PRVS
elif cfg['network_G']['netG'] == 'PRVS':
from arch.PRVS_arch import PRVSNet
self.netG = PRVSNet()
# CSA
elif cfg['network_G']['netG'] == 'CSA':
from arch.CSA_arch import InpaintNet
self.netG = InpaintNet(c_img=cfg['network_G']['c_img'], norm=cfg['network_G']['norm'], act_en=cfg['network_G']['act_en'],
act_de=cfg['network_G']['network_G'])
# deoldify
elif cfg['network_G']['netG'] == 'deoldify':
from arch.Deoldify_arch import Unet34
self.netG = Unet34()
# GLEAN (does init itself)
elif cfg['network_G']['netG'] == 'GLEAN':
from arch.GLEAN_arch import GLEANStyleGANv2
if cfg['network_G']['pretrained'] == False:
self.netG = GLEANStyleGANv2(in_size=cfg['network_G']['in_size'], out_size=cfg['network_G']['out_size'],
img_channels=cfg['network_G']['img_channels'], img_channels_out=cfg['network_G']['img_channels_out'], rrdb_channels=cfg['network_G']['rrdb_channels'], num_rrdbs=cfg['network_G']['num_rrdbs'],
style_channels=cfg['network_G']['style_channels'], num_mlps=cfg['network_G']['num_mlps'], channel_multiplier=cfg['network_G']['channel_multiplier'],
blur_kernel=cfg['network_G']['blur_kernel'], lr_mlp=cfg['network_G']['lr_mlp'], default_style_mode=cfg['network_G']['default_style_mode'],
eval_style_mode=cfg['network_G']['eval_style_mode'], mix_prob=cfg['network_G']['mix_prob'], pretrained=None, bgr2rgb=cfg['network_G']['bgr2rgb'])
else:
# using stylegan pretrain
self.netG = GLEANStyleGANv2(in_size=cfg['network_G']['in_size'], out_size=cfg['network_G']['out_size'],
img_channels=cfg['network_G']['img_channels'], img_channels_out=cfg['network_G']['img_channels_out'], rrdb_channels=cfg['network_G']['rrdb_channels'], num_rrdbs=cfg['network_G']['num_rrdbs'],
style_channels=cfg['network_G']['style_channels'], num_mlps=cfg['network_G']['num_mlps'], channel_multiplier=cfg['network_G']['channel_multiplier'],
blur_kernel=cfg['network_G']['blur_kernel'], lr_mlp=cfg['network_G']['lr_mlp'], default_style_mode=cfg['network_G']['default_style_mode'],
eval_style_mode=cfg['network_G']['eval_style_mode'], mix_prob=cfg['network_G']['mix_prob'], pretrained=dict(ckpt_path='http://download.openmmlab.com/mmgen/stylegan2/official_weights/stylegan2-ffhq-config-f-official_20210327_171224-bce9310c.pth', prefix='generator_ema'), bgr2rgb=cfg['network_G']['bgr2rgb'])
# srflow (weight init?)
elif cfg['network_G']['netG'] == 'srflow':
from arch.SRFlowNet_arch import SRFlowNet
self.netG = SRFlowNet(in_nc=cfg['network_G']['in_nc'], out_nc=cfg['network_G']['out_nc'],
nf=cfg['network_G']['nf'], nb=cfg['network_G']['nb'], scale=cfg['scale'], K=cfg['network_G']['flow']['K'], step=None)
from arch.SRFlowNet_arch import get_z
# DFDNet
elif cfg['network_G']['netG'] == 'DFDNet':
from arch.DFDNet_arch import UNetDictFace
self.netG = UNetDictFace(64)
# GFPGAN (error with init?)
elif cfg['network_G']['netG'] == 'GFPGAN':
from arch.GFPGAN_arch import GFPGANv1
self.netG = GFPGANv1(input_channels=cfg['network_G']['input_channels'], output_channels=cfg['network_G']['output_channels'], out_size=cfg['network_G']['out_size'], num_style_feat=cfg['network_G']['num_style_feat'],channel_multiplier=cfg['network_G']['channel_multiplier'],resample_kernel=cfg['network_G']['resample_kernel'],decoder_load_path=cfg['network_G']['decoder_load_path'],
fix_decoder=cfg['network_G']['fix_decoder'], num_mlp=cfg['network_G']['num_mlp'],lr_mlp=cfg['network_G']['lr_mlp'],input_is_latent=cfg['network_G']['input_is_latent'],
different_w=cfg['network_G']['different_w'], narrow=cfg['network_G']['narrow'],sft_half=cfg['network_G']['sft_half'])
elif cfg['network_G']['netG'] == 'CAIN':
from arch.CAIN_arch import CAIN
self.netG = CAIN(cfg['network_G']['depth'])
elif cfg['network_G']['netG'] == 'rife':
from arch.rife_arch import IFNet
self.netG = IFNet()
elif cfg['network_G']['netG'] == 'RRIN':
from arch.RRIN_arch import Net
self.netG = Net()
elif cfg['network_G']['netG'] == 'ABME':
from arch.ABME_arch import ABME
self.netG = ABME()
elif cfg['network_G']['netG'] == 'EDSC':
from arch.EDSC_arch import Network
self.netG = Network()
elif cfg['network_G']['netG'] == 'CTSDG':
from arch.CTSDG_arch import Generator
self.netG = Generator()
elif cfg['network_G']['netG'] == 'MST':
from arch.MST_arch import InpaintGateGenerator
self.netG = InpaintGateGenerator()
elif cfg['network_G']['netG'] == 'lama':
from arch.lama_arch import FFCResNetGenerator
self.netG = FFCResNetGenerator(4, 3)
if cfg['path']['checkpoint_path'] is None and cfg['network_G']['netG'] != 'GLEAN' and cfg['network_G']['netG'] != 'srflow' and cfg['network_G']['netG'] != 'GFPGAN':
if self.global_step == 0:
#if self.trainer.global_step == 0:
weights_init(self.netG, 'kaiming')
print("Generator weight init complete.")
############################
if cfg['network_G']['CEM'] == True:
CEM_conf = CEMnet.Get_CEM_Conf(cfg['scale'])
CEM_conf.sigmoid_range_limit = cfg['network_G']['sigmoid_range_limit']
if CEM_conf.sigmoid_range_limit:
CEM_conf.input_range = [-1,1] if z_norm else [0,1]
kernel = None # note: could pass a kernel here, but None will use default cubic kernel
self.CEM_net = CEMnet.CEMnet(CEM_conf, upscale_kernel=kernel)
self.CEM_net.WrapArchitecture(only_padders=True)
self.netG = self.CEM_net.WrapArchitecture(self.netG, training_patch_size=cfg['datasets']['train']['HR_size'])
############################
# discriminators
# size refers to input shape of tensor
if cfg['network_D']['netD'] == 'context_encoder':
from arch.discriminators import context_encoder
self.netD = context_encoder()
# VGG
elif cfg['network_D']['netD'] == 'VGG':
from arch.discriminators import Discriminator_VGG
self.netD = Discriminator_VGG(size=cfg['network_D']['size'], in_nc=cfg['network_D']['in_nc'], base_nf=cfg['network_D']['base_nf'], norm_type=cfg['network_D']['norm_type'], act_type=cfg['network_D']['act_type'], mode=cfg['network_D']['mode'], convtype=cfg['network_D']['convtype'], arch=cfg['network_D']['arch'])
elif cfg['network_D']['netD'] == 'VGG_fea':
from arch.discriminators import Discriminator_VGG_fea
self.netD = Discriminator_VGG_fea(size=cfg['network_D']['size'], in_nc=cfg['network_D']['in_nc'], base_nf=cfg['network_D']['base_nf'], norm_type=cfg['network_D']['norm_type'], act_type=cfg['network_D']['act_type'], mode=cfg['network_D']['mode'], convtype=cfg['network_D']['convtype'],
arch=cfg['network_D']['arch'], spectral_norm=cfg['network_D']['spectral_norm'], self_attention = cfg['network_D']['self_attention'], max_pool=cfg['network_D']['max_pool'], poolsize = cfg['network_D']['poolsize'])
elif cfg['network_D']['netD'] == 'Discriminator_VGG_128_SN':
from arch.discriminators import Discriminator_VGG_128_SN
self.netD = Discriminator_VGG_128_SN()
elif cfg['network_D']['netD'] == 'VGGFeatureExtractor':
from arch.discriminators import VGGFeatureExtractor
self.netD = VGGFeatureExtractor(feature_layer=cfg['feature_layer']['feature_layer'],use_bn=cfg['network_D']['use_bn'],use_input_norm=cfg['network_D']['use_input_norm'],device=torch.device(cfg['network_D']['device']),z_norm=cfg['network_D']['z_norm'])
# PatchGAN
elif cfg['network_D']['netD'] == 'NLayerDiscriminator':
from arch.discriminators import NLayerDiscriminator
self.netD = NLayerDiscriminator(input_nc=cfg['network_D']['input_nc'], ndf=cfg['network_D']['ndf'], n_layers=cfg['network_D']['n_layers'], norm_layer=cfg['network_D']['norm_layer'],
use_sigmoid=cfg['network_D']['use_sigmoid'], getIntermFeat=cfg['network_D']['getIntermFeat'], patch=cfg['network_D']['patch'], use_spectral_norm=cfg['network_D']['use_spectral_norm'])
# Multiscale
elif cfg['network_D']['netD'] == 'MultiscaleDiscriminator':
from arch.discriminators import MultiscaleDiscriminator
self.netD = MultiscaleDiscriminator(input_nc=cfg['network_D']['input_nc'], ndf=cfg['network_D']['ndf'], n_layers=cfg['network_D']['n_layers'], norm_layer=cfg['network_D']['norm_layer'],
use_sigmoid=cfg['network_D']['use_sigmoid'], num_D=cfg['network_D']['num_D'], getIntermFeat=cfg['network_D']['getIntermFeat'])
# ResNet
#elif cfg['network_D']['netD'] == 'Discriminator_ResNet_128':
# from arch.discriminators import Discriminator_ResNet_128
# self.netD = Discriminator_ResNet_128(in_nc=cfg['network_D']['in_nc'], base_nf=cfg['network_D']['base_nf'], norm_type=cfg['network_D']['norm_type'], act_type=cfg['network_D']['act_type'], mode=cfg['network_D']['mode'])
elif cfg['network_D']['netD'] == 'ResNet101FeatureExtractor':
from arch.discriminators import ResNet101FeatureExtractor
self.netD = ResNet101FeatureExtractor(use_input_norm=cfg['network_D']['use_input_norm'], device=torch.device(cfg['network_D']['device']), z_norm=cfg['network_D']['z_norm'])
# MINC
elif cfg['network_D']['netD'] == 'MINCNet':
from arch.discriminators import MINCNet
self.netD = MINCNet()
# Pixel
elif cfg['network_D']['netD'] == 'PixelDiscriminator':
from arch.discriminators import PixelDiscriminator
self.netD = PixelDiscriminator(input_nc=cfg['network_D']['input_nc'], ndf=cfg['network_D']['ndf'], norm_layer=cfg['network_D']['norm_layer'])
# EfficientNet
elif cfg['network_D']['netD'] == 'EfficientNet':
from efficientnet_pytorch import EfficientNet
self.netD = EfficientNet.from_pretrained(cfg['network_D']['EfficientNet_pretrain'], num_classes=cfg['network_D']['num_classes'])
# mobilenetV3
elif cfg['network_D']['netD'] == "mobilenetV3":
from arch.mobilenetv3_arch import MobileNetV3
self.netD = MobileNetV3(n_class=cfg['network_D']['n_class'], mode=cfg['network_D']['mode'], input_size=cfg['network_D']['input_size'])
# resnet
elif cfg['network_D']['netD'] == 'resnet':
if cfg['network_D']['pretrain'] == False:
if cfg['network_D']['resnet_arch'] == 'resnet50':
from arch.resnet_arch import resnet50
self.netD = resnet50(num_classes=cfg['network_D']['num_classes'], pretrain=cfg['network_D']['pretrain'])
elif cfg['network_D']['resnet_arch'] == 'resnet101':
from arch.resnet_arch import resnet101
self.netD = resnet101(num_classes=cfg['network_D']['num_classes'], pretrain=cfg['network_D']['pretrain'])
elif cfg['network_D']['resnet_arch'] == 'resnet152':
from arch.resnet_arch import resnet152
self.netD = resnet152(num_classes=cfg['network_D']['num_classes'], pretrain=cfg['network_D']['pretrain'])
weights_init(self.netG, 'kaiming')
print("Discriminator weight init complete.")
if cfg['network_D']['pretrain'] == True:
# loading a pretrained network does not work by default, the amount of classes need to be adjusted in the final layer
import torchvision.models as models
if cfg['network_D']['resnet_arch'] == 'resnet50':
pretrained_model = models.resnet50(pretrained = True)
elif cfg['network_D']['resnet_arch'] == 'resnet101':
pretrained_model = models.resnet101(pretrained = True)
elif cfg['network_D']['resnet_arch'] == 'resnet152':
pretrained_model = models.resnet152(pretrained = True)
IN_FEATURES = pretrained_model.fc.in_features
OUTPUT_DIM = cfg['network_D']['num_classes']
fc = nn.Linear(IN_FEATURES, OUTPUT_DIM)
pretrained_model.fc = fc
from arch.resnet_arch import ResNet, Bottleneck
from collections import namedtuple
ResNetConfig = namedtuple('ResNetConfig', ['block', 'n_blocks', 'channels'])
if cfg['network_D']['resnet_arch'] == 'resnet50':
from arch.resnet_arch import resnet50
resnet50_config = ResNetConfig(block = Bottleneck,
n_blocks = [3, 4, 6, 3],
channels = [64, 128, 256, 512])
self.netD = ResNet(resnet50_config, OUTPUT_DIM)
elif cfg['network_D']['resnet_arch'] == 'resnet101':
from arch.resnet_arch import resnet101
resnet101_config = ResNetConfig(block = Bottleneck,
n_blocks = [3, 4, 23, 3],
channels = [64, 128, 256, 512])
self.netD = ResNet(resnet101_config, OUTPUT_DIM)
elif cfg['network_D']['resnet_arch'] == 'resnet152':
from arch.resnet_arch import resnet152
resnet152_config = ResNetConfig(block = Bottleneck,
n_blocks = [3, 8, 36, 3],
channels = [64, 128, 256, 512])
self.netD = ResNet(resnet152_config, OUTPUT_DIM)
self.netD.load_state_dict(pretrained_model.state_dict())
print("Resnet pretrain loaded.")
# ResNeSt
# ["resnest50", "resnest101", "resnest200", "resnest269"]
elif cfg['network_D']['netD'] == 'ResNeSt':
if cfg['network_D']['ResNeSt_pretrain'] == 'resnest50':
from arch.discriminators import resnest50
self.netD = resnest50(pretrained=cfg['network_D']['pretrained'], num_classes=cfg['network_D']['num_classes'])
elif cfg['network_D']['ResNeSt_pretrain'] == 'resnest101':
from arch.discriminators import resnest101
self.netD = resnest101(pretrained=cfg['network_D']['pretrained'], num_classes=cfg['network_D']['num_classes'])
elif cfg['network_D']['ResNeSt_pretrain'] == 'resnest200':
from arch.discriminators import resnest200
self.netD = resnest200(pretrained=cfg['network_D']['pretrained'], num_classes=cfg['network_D']['num_classes'])
elif cfg['network_D']['ResNeSt_pretrain'] == 'resnest269':
from arch.discriminators import resnest269
self.netD = resnest269(pretrained=cfg['network_D']['pretrained'], num_classes=cfg['network_D']['num_classes'])
# need fixing
#FileNotFoundError: [Errno 2] No such file or directory: '../experiments/pretrained_models/VGG16minc_53.pth'
#self.netD = MINCFeatureExtractor(feature_layer=34, use_bn=False, use_input_norm=True, device=torch.device('cpu'))
# Transformer (Warning: uses own init!)
elif cfg['network_D']['netD'] == 'TranformerDiscriminator':
from arch.discriminators import TranformerDiscriminator
self.netD = TranformerDiscriminator(img_size=cfg['network_D']['img_size'], patch_size=cfg['network_D']['patch_size'], in_chans=cfg['network_D']['in_chans'], num_classes=cfg['network_D']['num_classes'], embed_dim=cfg['network_D']['embed_dim'], depth=cfg['network_D']['depth'],
num_heads=cfg['network_D']['num_heads'], mlp_ratio=cfg['network_D']['mlp_ratio'], qkv_bias=cfg['network_D']['qkv_bias'], qk_scale=cfg['network_D']['qk_scale'], drop_rate=cfg['network_D']['drop_rate'], attn_drop_rate=cfg['network_D']['attn_drop_rate'],
drop_path_rate=cfg['network_D']['drop_path_rate'], hybrid_backbone=cfg['network_D']['hybrid_backbone'], norm_layer=cfg['network_D']['norm_layer'])
#############################################
elif cfg['network_D']['netD'] == 'ViT':
from vit_pytorch import ViT
self.netD = ViT(
image_size = cfg['network_D']['image_size'],
patch_size = cfg['network_D']['patch_size'],
num_classes = cfg['network_D']['num_classes'],
dim = cfg['network_D']['dim'],
depth = cfg['network_D']['depth'],
heads = cfg['network_D']['heads'],
mlp_dim = cfg['network_D']['mlp_dim'],
dropout = cfg['network_D']['dropout'],
emb_dropout = cfg['network_D']['emb_dropout']
)
elif cfg['network_D']['netD'] == 'DeepViT':
from vit_pytorch.deepvit import DeepViT
self.netD = DeepViT(
image_size = cfg['network_D']['image_size'],
patch_size = cfg['network_D']['patch_size'],
num_classes = cfg['network_D']['num_classes'],
dim = cfg['network_D']['dim'],
depth = cfg['network_D']['depth'],
heads = cfg['network_D']['heads'],
mlp_dim = cfg['network_D']['mlp_dim'],
dropout = cfg['network_D']['dropout'],
emb_dropout = cfg['network_D']['emb_dropout']
)
#############################################
# RepVGG-A0, RepVGG-A1, RepVGG-A2, RepVGG-B0, RepVGG-B1, RepVGG-B1g2, RepVGG-B1g4,
# RepVGG-B2, RepVGG-B2g2, RepVGG-B2g4, RepVGG-B3, RepVGG-B3g2, RepVGG-B3g4
elif cfg['network_D']['netD'] == 'RepVGG':
if cfg['network_D']['RepVGG_arch'] == 'RepVGG-A0':
from arch.RepVGG_arch import create_RepVGG_A0
self.netD = create_RepVGG_A0(deploy=False, num_classes=cfg['network_D']['num_classes'])
elif cfg['network_D']['RepVGG_arch'] == 'RepVGG-A1':
from arch.RepVGG_arch import create_RepVGG_A1
self.netD = create_RepVGG_A1(deploy=False, num_classes=cfg['network_D']['num_classes'])
elif cfg['network_D']['RepVGG_arch'] == 'RepVGG-A2':
from arch.RepVGG_arch import create_RepVGG_A2
self.netD = create_RepVGG_A2(deploy=False, num_classes=cfg['network_D']['num_classes'])
elif cfg['network_D']['RepVGG_arch'] == 'RepVGG-B0':
from arch.RepVGG_arch import create_RepVGG_B0
self.netD = create_RepVGG_B0(deploy=False, num_classes=cfg['network_D']['num_classes'])
elif cfg['network_D']['RepVGG_arch'] == 'RepVGG-B1':
from arch.RepVGG_arch import create_RepVGG_B1
self.netD = create_RepVGG_B1(deploy=False, num_classes=cfg['network_D']['num_classes'])
elif cfg['network_D']['RepVGG_arch'] == 'RepVGG-B1g2':
from arch.RepVGG_arch import create_RepVGG_B1g2
self.netD = create_RepVGG_B1g2(deploy=False, num_classes=cfg['network_D']['num_classes'])
elif cfg['network_D']['RepVGG_arch'] == 'RepVGG-B1g4':
from arch.RepVGG_arch import create_RepVGG_B1g4
self.netD = create_RepVGG_B1g4(deploy=False, num_classes=cfg['network_D']['num_classes'])
elif cfg['network_D']['RepVGG_arch'] == 'RepVGG-B2':
from arch.RepVGG_arch import create_RepVGG_B2
self.netD = create_RepVGG_B2(deploy=False, num_classes=cfg['network_D']['num_classes'])
elif cfg['network_D']['RepVGG_arch'] == 'RepVGG-B2g2':
from arch.RepVGG_arch import create_RepVGG_B2g2
self.netD = create_RepVGG_B2g2(deploy=False, num_classes=cfg['network_D']['num_classes'])
elif cfg['network_D']['RepVGG_arch'] == 'RepVGG-B2g4':
from arch.RepVGG_arch import create_RepVGG_B2g4
self.netD = create_RepVGG_B2g4(deploy=False, num_classes=cfg['network_D']['num_classes'])
elif cfg['network_D']['RepVGG_arch'] == 'RepVGG-B3':
from arch.RepVGG_arch import create_RepVGG_B3
self.netD = create_RepVGG_B3(deploy=False, num_classes=cfg['network_D']['num_classes'])
elif cfg['network_D']['RepVGG_arch'] == 'RepVGG-B3g2':
from arch.RepVGG_arch import create_RepVGG_B3g2
self.netD = create_RepVGG_B3g2(deploy=False, num_classes=cfg['network_D']['num_classes'])
elif cfg['network_D']['RepVGG_arch'] == 'RepVGG-B3g4':
from arch.RepVGG_arch import create_RepVGG_B3g4
self.netD = create_RepVGG_B3g4(deploy=False, num_classes=cfg['network_D']['num_classes'])
#############################################
elif cfg['network_D']['netD'] == 'squeezenet':
from arch.squeezenet_arch import SqueezeNet
self.netD = SqueezeNet(num_classes=cfg['network_D']['num_classes'], version=cfg['network_D']['version'])
#############################################
elif cfg['network_D']['netD'] == 'SwinTransformer':
from swin_transformer_pytorch import SwinTransformer
self.netD = SwinTransformer(
hidden_dim=cfg['network_D']['hidden_dim'],
layers=cfg['network_D']['layers'],
heads=cfg['network_D']['heads'],
channels=cfg['network_D']['channels'],
num_classes=cfg['network_D']['num_classes'],
head_dim=cfg['network_D']['head_dim'],
window_size=cfg['network_D']['window_size'],
downscaling_factors=cfg['network_D']['downscaling_factors'],
relative_pos_embedding=cfg['network_D']['relative_pos_embedding']
)
# NFNet
elif cfg['network_D']['netD'] == 'NFNet':
from arch.NFNet_arch import NFNet
self.netD = NFNet(
num_classes=cfg['network_D']['num_classes'],
variant=cfg['network_D']['variant'],
stochdepth_rate=cfg['network_D']['stochdepth_rate'],
alpha=cfg['network_D']['alpha'],
se_ratio=cfg['network_D']['se_ratio'],
activation=cfg['network_D']['activation']
)
elif cfg['network_D']['netD'] == 'lvvit':
from arch.lvvit_arch import LV_ViT
self.netD = LV_ViT( img_size=cfg['network_D']['img_size'], patch_size=cfg['network_D']['patch_size'], in_chans=cfg['network_D']['in_chans'], num_classes=cfg['network_D']['num_classes'], embed_dim=cfg['network_D']['embed_dim'], depth=cfg['network_D']['depth'],
num_heads=cfg['network_D']['num_heads'], mlp_ratio=cfg['network_D']['mlp_ratio'], qkv_bias=cfg['network_D']['qkv_bias'], qk_scale=cfg['network_D']['qk_scale'], drop_rate=cfg['network_D']['drop_rate'], attn_drop_rate=cfg['network_D']['attn_drop_rate'],
drop_path_rate=cfg['network_D']['drop_path_rate'], drop_path_decay=cfg['network_D']['drop_path_decay'], hybrid_backbone=cfg['network_D']['hybrid_backbone'], norm_layer=nn.LayerNorm, p_emb=cfg['network_D']['p_emb'], head_dim = cfg['network_D']['head_dim'],
skip_lam =cfg['network_D']['skip_lam'],order=cfg['network_D']['order'], mix_token=cfg['network_D']['mix_token'], return_dense=cfg['network_D']['return_dense'])
elif cfg['network_D']['netD'] == 'timm':
import timm
self.netD = timm.create_model(cfg['network_D']['timm_model'], num_classes=1, pretrained=True)
elif cfg['network_D']['netD'] == 'resnet3d':
from arch.resnet3d_arch import generate_model
self.netD = generate_model(cfg['network_D']['model_depth'])
elif cfg['network_D']['netD'] == 'FFCNLayerDiscriminator':
from arch.lama_arch import FFCNLayerDiscriminator
self.netD = FFCNLayerDiscriminator(3)
elif cfg['network_D']['netD'] == 'effV2':
if cfg['network_D']['size'] == "s":
from arch.efficientnetV2_arch import effnetv2_s
self.netD = effnetv2_s()
elif cfg['network_D']['size'] == "m":
from arch.efficientnetV2_arch import effnetv2_m
self.netD = effnetv2_m()
elif cfg['network_D']['size'] == "l":
from arch.efficientnetV2_arch import effnetv2_l
self.netD = effnetv2_l()
elif cfg['network_D']['size'] == "xl":
from arch.efficientnetV2_arch import effnetv2_xl
self.netD = effnetv2_xl()
elif cfg['network_D']['netD'] == 'x_transformers':
from x_transformers import ViTransformerWrapper, Encoder
self.netD = ViTransformerWrapper(
image_size = cfg['network_D']['image_size'],
patch_size = cfg['network_D']['patch_size'],
num_classes = 1,
attn_layers = Encoder(
dim = cfg['network_D']['dim'],
depth = cfg['network_D']['depth'],
heads = cfg['network_D']['heads'],
)
)
# only doing init, if not 'TranformerDiscriminator', 'EfficientNet', 'ResNeSt', 'resnet', 'ViT', 'DeepViT', 'mobilenetV3'
# should probably be rewritten
if cfg['network_D']['netD'] == 'resnet3d' or cfg['network_D']['netD'] == 'NFNet' or cfg['network_D']['netD'] == 'context_encoder' or cfg['network_D']['netD'] == 'VGG' or cfg['network_D']['netD'] == 'VGG_fea' or cfg['network_D']['netD'] == 'Discriminator_VGG_128_SN' or cfg['network_D']['netD'] == 'VGGFeatureExtractor' or cfg['network_D']['netD'] == 'NLayerDiscriminator' or cfg['network_D']['netD'] == 'MultiscaleDiscriminator' or cfg['network_D']['netD'] == 'Discriminator_ResNet_128' or cfg['network_D']['netD'] == 'ResNet101FeatureExtractor' or cfg['network_D']['netD'] == 'MINCNet' or cfg['network_D']['netD'] == 'PixelDiscriminator' or cfg['network_D']['netD'] == 'ResNeSt' or cfg['network_D']['netD'] == 'RepVGG' or cfg['network_D']['netD'] == 'squeezenet' or cfg['network_D']['netD'] == 'SwinTransformer':
if self.global_step == 0:
weights_init(self.netD, 'kaiming')
print("Discriminator weight init complete.")
# loss functions
self.l1 = nn.L1Loss()
if cfg['train']['loss_f'] == 'L1Loss':
loss_f = torch.nn.L1Loss()
elif cfg['train']['loss_f'] == 'L1CosineSim':
loss_f = L1CosineSim(loss_lambda=cfg['train']['loss_lambda'], reduction=cfg['train']['reduction_L1CosineSim'])
self.HFENLoss = HFENLoss(loss_f=loss_f, kernel=cfg['train']['kernel'], kernel_size=cfg['train']['kernel_size'], sigma = cfg['train']['sigma'], norm = cfg['train']['norm'])
self.ElasticLoss = ElasticLoss(a=cfg['train']['a'], reduction=cfg['train']['reduction_elastic'])
self.RelativeL1 = RelativeL1(eps=cfg['train']['eps'], reduction=cfg['train']['reduction_realtive'])
self.L1CosineSim = L1CosineSim(loss_lambda=cfg['train']['loss_lambda'], reduction=cfg['train']['reduction_L1CosineSim'])
self.ClipL1 = ClipL1(clip_min=cfg['train']['clip_min'], clip_max=cfg['train']['clip_max'])
if cfg['train']['loss_f_fft'] == 'L1Loss':
loss_f_fft = torch.nn.L1Loss
elif cfg['train']['loss_f_fft'] == 'L1CosineSim':
loss_f_fft = L1CosineSim(loss_lambda=cfg['train']['loss_lambda'], reduction=cfg['train']['reduction_L1CosineSim'])
self.FFTloss = FFTloss(loss_f = loss_f_fft, reduction=cfg['train']['reduction_fft'])
self.OFLoss = OFLoss()
self.GPLoss = GPLoss(trace=cfg['train']['trace'], spl_denorm=cfg['train']['spl_denorm'])
self.CPLoss = CPLoss(rgb=cfg['train']['rgb'], yuv=cfg['train']['yuv'], yuvgrad=cfg['train']['yuvgrad'], trace=cfg['train']['trace'], spl_denorm=cfg['train']['spl_denorm'], yuv_denorm=cfg['train']['yuv_denorm'])
self.StyleLoss = StyleLoss()
self.TVLoss = TVLoss(tv_type=cfg['train']['tv_type'], p = cfg['train']['p'])
self.Contextual_Loss = Contextual_Loss(cfg['train']['layers_weights'], crop_quarter=cfg['train']['crop_quarter'], max_1d_size=cfg['train']['max_1d_size'],
distance_type = cfg['train']['distance_type'], b=cfg['train']['b'], band_width=cfg['train']['band_width'],
use_vgg = cfg['train']['use_vgg'], net = cfg['train']['net_contextual'], calc_type = cfg['train']['calc_type'], use_timm = cfg['train']['use_timm'], timm_model = cfg['train']['timm_model'])
self.MSELoss = torch.nn.MSELoss()
self.L1Loss = nn.L1Loss()
self.BCELogits = torch.nn.BCEWithLogitsLoss()
self.BCE = torch.nn.BCELoss()
self.FFLoss = FocalFrequencyLoss()
# perceptual loss
from arch.networks_basic import PNetLin
self.perceptual_loss = PNetLin(pnet_rand=cfg['train']['pnet_rand'], pnet_tune=cfg['train']['pnet_tune'], pnet_type=cfg['train']['pnet_type'],
use_dropout=cfg['train']['use_dropout'], spatial=cfg['train']['spatial'], version=cfg['train']['version'], lpips=cfg['train']['lpips'])
model_path = os.path.abspath('loss/lpips_weights/v0.1/%s.pth'%(cfg['train']['pnet_type']))
print('Loading model from: %s'%model_path)
self.perceptual_loss.load_state_dict(torch.load(model_path, map_location=torch.device(self.device)), strict=False)
for param in self.perceptual_loss.parameters():
param.requires_grad = False
self.ColorLoss = ColorLoss()
self.FrobeniusNormLoss = FrobeniusNormLoss()
self.GradientLoss = GradientLoss()
self.MultiscalePixelLoss = MultiscalePixelLoss()
self.SPLoss = SPLoss()
# pytorch loss
self.HuberLoss = nn.HuberLoss()
self.SmoothL1Loss = nn.SmoothL1Loss()
self.SoftMarginLoss = nn.SoftMarginLoss()
self.LapLoss = LapLoss()
# metrics
self.psnr_metric = PSNR()
self.ssim_metric = SSIM()
self.ae_metric = AE()
self.mse_metric = MSE()
# logging
if 'PSNR' in cfg['train']['metrics']:
self.val_psnr = []
if 'SSIM' in cfg['train']['metrics']:
self.val_ssim = []
if 'MSE' in cfg['train']['metrics']:
self.val_mse = []
if 'LPIPS' in cfg['train']['metrics']:
self.val_lpips = []
self.iter_check = 0
def forward(self, image, masks):
return self.netG(image, masks)
#def training_step(self, train_batch, batch_idx):
def training_step(self, train_batch, batch_idx, optimizer_idx=0):
# iteration count is sometimes broken, adding a check and manual increment
# only increment if generator gets trained (loop gets called a second time for discriminator)
if self.trainer.global_step != 0:
if optimizer_idx == 0 and self.iter_check == self.trainer.global_step:
self.trainer.global_step += 1
self.iter_check = self.trainer.global_step
# inpainting:
# train_batch[0][0] = batch_size
# train_batch[0] = masked
# train_batch[1] = mask (lr)
# train_batch[2] = original
# train_batch[3] = edge
# train_batch[4] = grayscale
# super resolution
# train_batch[0] = Null
# train_batch[1] = lr
# train_batch[2] = hr
# train_batch[3] = landmarks (DFDNet)
# frame interpolation
# train_batch[0] = 1st frame
# train_batch[1] = 3st frame
# train_batch[2] = 2st frame, gets generated
if cfg['datasets']['train']['mode'] == 'DS_inpaint_tiled_batch' or cfg['datasets']['train']['mode'] == 'DS_lrhr_batch_oft':
# reducing dimension
train_batch[0] = torch.squeeze(train_batch[0], 0)
train_batch[1] = torch.squeeze(train_batch[1], 0)
train_batch[2] = torch.squeeze(train_batch[2], 0)
if cfg['network_G']['netG'] == 'CTSDG':
train_batch[3] = torch.squeeze(train_batch[3], 0)
# train generator
############################
if cfg['network_G']['netG'] == 'CTSDG':
# input_image, input_edge, mask
out, projected_image, projected_edge = self.netG(train_batch[0], train_batch[3], train_batch[1])
if cfg['network_G']['netG'] == 'lama' or cfg['network_G']['netG'] == 'MST' or cfg['network_G']['netG'] == 'MANet' or cfg['network_G']['netG'] == 'context_encoder' or cfg['network_G']['netG'] == 'DFNet' or cfg['network_G']['netG'] == 'AdaFill' or cfg['network_G']['netG'] == 'MEDFE' or cfg['network_G']['netG'] == 'RFR' or cfg['network_G']['netG'] == 'LBAM' or cfg['network_G']['netG'] == 'DMFN' or cfg['network_G']['netG'] == 'Partial' or cfg['network_G']['netG'] == 'RN' or cfg['network_G']['netG'] == 'RN' or cfg['network_G']['netG'] == 'DSNet' or cfg['network_G']['netG'] == 'DSNetRRDB' or cfg['network_G']['netG'] == 'DSNetDeoldify':
# generate fake (1 output)
out = self(train_batch[0],train_batch[1])
# masking, taking original content from HR
out = train_batch[0]*(train_batch[1])+out*(1-train_batch[1])
############################
if cfg['network_G']['netG'] == 'deepfillv1' or cfg['network_G']['netG'] == 'deepfillv2' or cfg['network_G']['netG'] == 'Adaptive':
# generate fake (2 outputs)
out, other_img = self(train_batch[0],train_batch[1])
# masking, taking original content from HR
out = train_batch[0]*(train_batch[1])+out*(1-train_batch[1])
############################
# exotic generators
# CSA
if cfg['network_G']['netG'] == 'CSA':
coarse_result, out, csa, csa_d = self(train_batch[0],train_batch[1])
# masking, taking original content from HR
out = train_batch[0]*(train_batch[1])+out*(1-train_batch[1])
# EdgeConnect
# train_batch[3] = edges
# train_batch[4] = grayscale
if cfg['network_G']['netG'] == 'EdgeConnect':
out, other_img = self.netG(train_batch[0], train_batch[3], train_batch[4], train_batch[1])
# masking, taking original content from HR
out = train_batch[0]*(train_batch[1])+out*(1-train_batch[1])
# PVRS
if cfg['network_G']['netG'] == 'PVRS':
out, _ ,edge_small, edge_big = self.netG(train_batch[0], train_batch[1], train_batch[3])
# masking, taking original content from HR
out = train_batch[0]*(train_batch[1])+out*(1-train_batch[1])
# FRRN
if cfg['network_G']['netG'] == 'FRRN':
out, mid_x, mid_mask = self(train_batch[0], train_batch[1])
# masking, taking original content from HR
out = train_batch[0]*(train_batch[1])+out*(1-train_batch[1])
# deoldify
if cfg['network_G']['netG'] == 'deoldify':
out = self.netG(train_batch[0])
############################
# if frame interpolation
if cfg['network_G']['netG'] == 'CAIN' or cfg['network_G']['netG'] == 'rife' or cfg['network_G']['netG'] == 'RRIN' or cfg['network_G']['netG'] == 'ABME' or cfg['network_G']['netG'] == 'EDSC':
out = self.netG(train_batch[0], train_batch[1])
# ESRGAN / GLEAN / GPEN / comodgan / lightweight_gan / SimpleFontGenerator256 / SimpleFontGenerator512
if cfg['network_G']['netG'] == "SimpleFontGenerator512" or cfg['network_G']['netG'] == "SimpleFontGenerator256" or cfg['network_G']['netG'] == 'lightweight_gan' or cfg['network_G']['netG'] == 'RRDB_net' or cfg['network_G']['netG'] == 'GLEAN' or cfg['network_G']['netG'] == 'GPEN' or cfg['network_G']['netG'] == 'comodgan':
if cfg['datasets']['train']['mode'] == 'DS_inpaint' or cfg['datasets']['train']['mode'] == 'DS_inpaint_tiled' or cfg['datasets']['train']['mode'] == 'DS_inpaint_tiled_batch':
# masked test with inpaint dataloader
tmp = torch.cat([train_batch[0], train_batch[1]],1)
out = self.netG(tmp)
out = train_batch[0]*(train_batch[1])+out*(1-train_batch[1])
else:
# normal dataloader
out = self.netG(train_batch[1])
# # unpad images if using CEM
if cfg['network_G']['CEM'] == True:
out = self.CEM_net.HR_unpadder(out)
train_batch[2] = self.CEM_net.HR_unpadder(train_batch[2])
# GFPGAN
if cfg['network_G']['netG'] == 'GFPGAN':
if cfg['datasets']['train']['mode'] == 'DS_inpaint' or cfg['datasets']['train']['mode'] == 'DS_inpaint_tiled' or cfg['datasets']['train']['mode'] == 'DS_inpaint_tiled_batch':
# masked test with inpaint dataloader
tmp = torch.cat([train_batch[0], train_batch[1]],1)
out, _ = self.netG(tmp)
out = train_batch[0]*(train_batch[1])+out*(1-train_batch[1])
else:
out, _ = self.netG(train_batch[1])
if cfg['network_G']['netG'] == 'srflow':
# freeze rrdb in the beginning
if self.trainer.global_step < cfg['network_G']['freeze_iter']:
self.netG.set_rrdb_training(False)
else:
self.netG.set_rrdb_training(True)
z, nll, y_logits = self.netG(gt=train_batch[2], lr=train_batch[1], reverse=False)
out, logdet = self.netG(lr=train_batch[1], z=z, eps_std=0, reverse=True, reverse_with_grad=True)
#out = torch.clamp(out, 0, 1) # forcing out to be between 0 and 1
# DFDNet
if cfg['network_G']['netG'] == 'DFDNet':
out = self.netG(train_batch[1], part_locations=train_batch[3])
# range [-1, 1] to [0, 1]
out = out + 1
out = out - out.min()
out = out / (out.max() - out.min())
# train generator
if optimizer_idx == 0:
############################
# loss calculation
total_loss = 0
if cfg['train']['L1Loss_weight'] > 0:
L1Loss_forward = cfg['train']['L1Loss_weight']*self.L1Loss(out, train_batch[2])
total_loss += L1Loss_forward
writer.add_scalar('loss/L1', L1Loss_forward, self.trainer.global_step)
if cfg['train']['HFEN_weight'] > 0:
HFENLoss_forward = cfg['train']['HFEN_weight']*self.HFENLoss(out, train_batch[2])
total_loss += HFENLoss_forward
writer.add_scalar('loss/HFEN', HFENLoss_forward, self.trainer.global_step)
if cfg['train']['Elatic_weight'] > 0:
ElasticLoss_forward = cfg['train']['Elatic_weight']*self.ElasticLoss(out, train_batch[2])
total_loss += ElasticLoss_forward
writer.add_scalar('loss/Elastic', ElasticLoss_forward, self.trainer.global_step)
if cfg['train']['Relative_l1_weight'] > 0:
RelativeL1_forward = cfg['train']['Relative_l1_weight']*self.RelativeL1(out, train_batch[2])
total_loss += RelativeL1_forward
writer.add_scalar('loss/RelativeL1', RelativeL1_forward, self.trainer.global_step)
if cfg['train']['L1CosineSim_weight'] > 0:
L1CosineSim_forward = cfg['train']['L1CosineSim_weight']*self.L1CosineSim(out, train_batch[2])
total_loss += L1CosineSim_forward
writer.add_scalar('loss/L1CosineSim', L1CosineSim_forward, self.trainer.global_step)
if cfg['train']['ClipL1_weight'] > 0:
ClipL1_forward = cfg['train']['ClipL1_weight']*self.ClipL1(out, train_batch[2])
total_loss += ClipL1_forward
writer.add_scalar('loss/ClipL1', ClipL1_forward, self.trainer.global_step)
if cfg['train']['FFTLoss_weight'] > 0:
FFTloss_forward = cfg['train']['FFTLoss_weight']*self.FFTloss(out, train_batch[2])
total_loss += FFTloss_forward
writer.add_scalar('loss/FFT', FFTloss_forward, self.trainer.global_step)
if cfg['train']['OFLoss_weight'] > 0:
OFLoss_forward = cfg['train']['OFLoss_weight']*self.OFLoss(out)
total_loss += OFLoss_forward
writer.add_scalar('loss/OF', OFLoss_forward, self.trainer.global_step)
if cfg['train']['GPLoss_weight'] > 0:
GPLoss_forward = cfg['train']['GPLoss_weight']*self.GPLoss(out, train_batch[2])
total_loss += GPLoss_forward
writer.add_scalar('loss/GP', GPLoss_forward, self.trainer.global_step)
if cfg['train']['CPLoss_weight'] > 0:
CPLoss_forward = cfg['train']['CPLoss_weight']*self.CPLoss(out, train_batch[2])
total_loss += CPLoss_forward
writer.add_scalar('loss/CP', CPLoss_forward, self.trainer.global_step)
if cfg['train']['Contexual_weight'] > 0:
Contextual_Loss_forward = cfg['train']['Contexual_weight']*self.Contextual_Loss(out, train_batch[2])
total_loss += Contextual_Loss_forward
writer.add_scalar('loss/contextual', Contextual_Loss_forward, self.trainer.global_step)
if cfg['train']['StyleLoss_weight'] > 0:
style_forward = cfg['train']['StyleLoss_weight']*self.StyleLoss(out, train_batch[2])
total_loss += style_forward
writer.add_scalar('loss/style', style_forward, self.trainer.global_step)
if cfg['train']['TVLoss_weight'] > 0:
tv_forward = cfg['train']['TVLoss_weight']*self.TVLoss(out)
total_loss += tv_forward
writer.add_scalar('loss/tv', tv_forward, self.trainer.global_step)
if cfg['train']['perceptual_weight'] > 0:
self.perceptual_loss.to(self.device)
if cfg['train']['diffaug'] == True:
tmp = self.perceptual_loss(in0=DiffAugment(out, cfg['train']['policy']), in1=DiffAugment(train_batch[2], cfg['train']['policy']))
else:
tmp = self.perceptual_loss(in0=out, in1=train_batch[2])
perceptual_loss = cfg['train']['perceptual_weight'] * tmp
writer.add_scalar('loss/perceptual', perceptual_loss, self.trainer.global_step)
total_loss +=perceptual_loss
if cfg['train']['MSE_weight'] > 0:
MSE_forward = cfg['train']['MSE_weight']*self.MSELoss(out, train_batch[2])
total_loss += MSE_forward
writer.add_scalar('loss/MSE', MSE_forward, self.trainer.global_step)
if cfg['train']['BCE_weight'] > 0:
BCELogits_forward = cfg['train']['BCE_weight']*self.BCELogits(out, train_batch[2])
total_loss += BCELogits_forward
writer.add_scalar('loss/BCELogits', BCELogits_forward, self.trainer.global_step)
if cfg['train']['Huber_weight'] > 0:
Huber_forward = cfg['train']['Huber_weight']*self.HuberLoss(out, train_batch[2])
total_loss += Huber_forward
writer.add_scalar('loss/Huber', Huber_forward, self.trainer.global_step)
if cfg['train']['SmoothL1_weight'] > 0:
SmoothL1_forward = cfg['train']['SmoothL1_weight']*self.SmoothL1Loss(out, train_batch[2])
total_loss += SmoothL1_forward
writer.add_scalar('loss/SmoothL1', SmoothL1_forward, self.trainer.global_step)
if cfg['train']['Lap_weight'] > 0:
Lap_forward = cfg['train']['Lap_weight']*(self.LapLoss(out, train_batch[2])).mean()
total_loss += Lap_forward
writer.add_scalar('loss/Lap', Lap_forward, self.trainer.global_step)
if cfg['train']['ColorLoss_weight'] > 0:
ColorLoss_forward = cfg['train']['ColorLoss_weight']*(self.ColorLoss(out, train_batch[2]))
total_loss += ColorLoss_forward
writer.add_scalar('loss/ColorLoss', ColorLoss_forward, self.trainer.global_step)
if cfg['train']['FrobeniusNormLoss_weight'] > 0:
FrobeniusNormLoss_forward = cfg['train']['FrobeniusNormLoss_weight']*(self.FrobeniusNormLoss(out, train_batch[2]))
total_loss += FrobeniusNormLoss_forward
writer.add_scalar('loss/FrobeniusNormLoss', FrobeniusNormLoss_forward, self.trainer.global_step)
if cfg['train']['GradientLoss_weight'] > 0:
GradientLoss_forward = cfg['train']['GradientLoss_weight']*(self.GradientLoss(out, train_batch[2]))
total_loss += GradientLoss_forward
writer.add_scalar('loss/GradientLoss', GradientLoss_forward, self.trainer.global_step)
if cfg['train']['MultiscalePixelLoss_weight'] > 0:
MultiscalePixelLoss_forward = cfg['train']['MultiscalePixelLoss_weight']*(self.MultiscalePixelLoss(out, train_batch[2]))
total_loss += MultiscalePixelLoss_forward
writer.add_scalar('loss/MultiscalePixelLoss', MultiscalePixelLoss_forward, self.trainer.global_step)
if cfg['train']['SPLoss_weight'] > 0:
SPLoss_forward = cfg['train']['SPLoss_weight']*(self.SPLoss(out, train_batch[2]))
total_loss += SPLoss_forward
writer.add_scalar('loss/SPLoss', SPLoss_forward, self.trainer.global_step)
if cfg['train']['FFLoss_weight'] > 0:
FFLoss_forward = cfg['train']['FFLoss_weight']*(self.FFLoss(out, train_batch[2]))
total_loss += FFLoss_forward
writer.add_scalar('loss/FFLoss', FFLoss_forward, self.trainer.global_step)
#########################
# exotic loss
# if model has two output, also calculate loss for such an image
# example with just l1 loss
if cfg['network_G']['netG'] == 'deepfillv1' or cfg['network_G']['netG'] == 'deepfillv2' or cfg['network_G']['netG'] == 'Adaptive':