-
Notifications
You must be signed in to change notification settings - Fork 6
/
PIH_train.py
1265 lines (1066 loc) · 43.8 KB
/
PIH_train.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
# Copyright 2023 Adobe. All rights reserved.
# This file is licensed to you under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. You may obtain a copy
# of the License at http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software distributed under
# the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
# OF ANY KIND, either express or implied. See the License for the specific language
# governing permissions and limitations under the License.
import os
import re
from glob import glob
from optparse import OptionParser
import sys
import numpy as np
import torch
from torch.utils.data import DataLoader
from dataset import DataCompositeGAN, DataCompositeGAN_iharmony
from model import (
Model,
Model_Composite,
Model_UNet,
Model_Composite_PL,
Model_Composite_PL_NoBG,
)
from tqdm import tqdm
from torch import Tensor
import utils.networks as networks
from utils.unet_dis import UNetDiscriminatorSN
import random
import torchvision.transforms as T
import torchvision.transforms.functional as F
def get_args():
parser = OptionParser()
parser.add_option("--datadir", "--dd", help="Directory contains 2D images.")
parser.add_option(
"-g",
"--gpu_id",
dest="gpu_id",
type="int",
help="GPU number, default is None (-g 0 means use gpu 0)",
)
parser.add_option(
"-f",
"--features",
default=3,
type="int",
help="Dimension of the feature space.",
)
parser.add_option(
"--frequency",
default=1,
type="int",
help="frequency to update discriminator",
)
parser.add_option(
"--learning-rate",
"--lr",
default=1e-5,
type="float",
help="learning rate for the model",
)
parser.add_option(
"--learning-rate-d",
"--lrd",
default=1e-5,
type="float",
help="learning rate for the discriminator model",
)
parser.add_option(
"--batchsize",
"--bs",
dest="batchsize",
default=4,
type="int",
help="batch size for training",
)
parser.add_option(
"--workers",
default=16,
type="int",
help="Dimension of the feature space.",
)
parser.add_option(
"-e", "--epochs", default=20000, type="int", help="Number of epochs to train"
)
parser.add_option(
"--force_train_from_scratch",
"--overwrite",
action="store_true",
help="If specified, training will start from scratch."
" Otherwise, latest checkpoint (if any) will be used",
)
parser.add_option(
"--multi_GPU",
"--distribuited",
action="store_true",
help="If specified, training will use multiple GPU.",
)
parser.add_option(
"--unet",
action="store_true",
help="If specified, training will use UNet.",
)
parser.add_option(
"--unetmask",
action="store_true",
help="If specified, training will use unet mask.",
)
parser.add_option(
"--reconloss",
action="store_true",
help="If specified, training will use reconloss on the mask.",
)
parser.add_option(
"--ratioconstrain",
action="store_true",
help="If specified, training will use reconloss on the mask.",
)
parser.add_option(
"--inputdim",
default=3,
type="int",
help="Dimension of the input image.",
)
parser.add_option(
"--sgd",
action="store_true",
help="If specified, training will use SGD Optimizer.",
)
parser.add_option(
"--pixel",
action="store_true",
help="If specified, using pixel discrinimator.",
)
parser.add_option(
"--unetd",
action="store_true",
help="If specified, using unet discrinimator.",
)
parser.add_option(
"--unetdnoskip",
action="store_true",
help="If specified, not using skip connection for unet discrinimator.",
)
parser.add_option(
"--tempdir",
"--tp",
default="tmp",
help="temp dir for saving intermediate results during the training.",
)
parser.add_option(
"--trainingratio",
default=1,
type="float",
help="Ratio for the training data. (e.g., 0.1 indicates using 10 percent of the data for training)",
)
parser.add_option(
"--ganlossmask",
action="store_true",
help="If specified, will use gan loss for mask.",
)
parser.add_option(
"--lut",
action="store_true",
help="If specified, will use lut as last step.",
)
parser.add_option(
"--nocurve",
action="store_true",
help="If specified, will not use curve.",
)
parser.add_option(
"--piecewiselinear",
action="store_true",
help="If specified, will not piecewiselinear.",
)
parser.add_option(
"--pairaugment",
action="store_true",
help="If specified, will use paired augmentation.",
)
parser.add_option(
"--purepairaugment",
action="store_true",
help="If specified, will use paired augmentation.",
)
parser.add_option(
"--lowdim",
action="store_true",
help="If specified, will use low dim dis.",
)
parser.add_option(
"--nosigmoid",
action="store_true",
help="If specified, will not use sigmoid.",
)
parser.add_option(
"--inputdimD",
default=3,
type="int",
help="Dimension of the input image for D.",
)
parser.add_option(
"--lut-dim",
default=8,
type="int",
help="Dimension of the LUT.",
)
parser.add_option(
"--pl-dim",
default=32,
type="int",
help="Dimension of the PIL.",
)
parser.add_option(
"--warmup",
default=0,
type="int",
help="Warmup to initialize.",
)
parser.add_option(
"--reconratio",
default=0,
type="float",
help="Ratio for self reconstruction. (e.g., 0.1 indicates using 10 percent of the data for self reconsruction)",
)
parser.add_option(
"--reconweight",
default=0.5,
type="float",
help="wight for self reconstruction.",
)
parser.add_option(
"--reconwithgan",
action="store_true",
help="If specified, will add adversarial loss for the recon training.",
)
parser.add_option(
"--augreconweight",
action="store_true",
help="If specified, will add augmentation on the recon weight.",
)
parser.add_option(
"--losstype",
default=0,
type="int",
help="Loss function type, with the argument augreconweight. 0: lambda*gan 1:lamda*gan+(1-lambda)*l1, scale dis 2:lamda*gan + (1-lamda)*l1, not scale dis",
)
parser.add_option(
"--masking",
action="store_true",
help="If specified, will using masking.",
)
parser.add_option(
"--brush",
action="store_true",
help="If specified, will using brush.",
)
parser.add_option(
"--onlyupsample",
action="store_true",
help="If specified, will only use upsampling.",
)
parser.add_option(
"--aggupsample",
action="store_true",
help="If specified, will only use aggressive upsamling, use with only upsample.",
)
parser.add_option(
"--lessskip",
action="store_true",
help="If specified, will only use aggressive upsamling, use with only upsample.",
)
parser.add_option(
"--nosig",
action="store_true",
help="If specified, will using nosig.",
)
parser.add_option(
"--maskconvkernel",
default=1,
type="int",
help="maskconvkernel.",
)
parser.add_option(
"--maskoffset",
default=0.5,
type="float",
help="maskoffset.",
)
parser.add_option(
"--swap",
action="store_true",
help="If specified, will using nosig.",
)
parser.add_option(
"--colorjitter",
action="store_true",
help="If specified, will use colorjitter.",
)
parser.add_option(
"--joint",
action="store_true",
help="If specified, will use joint-training.",
)
parser.add_option(
"--pihnetbool",
action="store_true",
help="If specified, will use pihnet.",
)
parser.add_option(
"--vitbool",
action="store_true",
help="If specified, will use vit.",
)
parser.add_option(
"--effbool",
action="store_true",
help="If specified, will use efficientnet v2 - m.",
)
parser.add_option(
"--onlysaveg",
action="store_true",
help="If specified, will only save g.",
)
parser.add_option(
"--iharmdata",
action="store_true",
help="If specified, will only save g.",
)
parser.add_option(
"--scheduler",
action="store_true",
help="If specified, will only save g.",
)
parser.add_option(
"--returnraw",
action="store_true",
help="If specified, will return raw",
)
parser.add_option(
"--twoinputs",
action="store_true",
help="If specified, will use only composite and mask as inputs",
)
parser.add_option(
"--depthmap",
action="store_true",
help="If specified, will use only composite and mask as inputs",
)
parser.add_option(
"--bgshadow",
action="store_true",
help="If specified, will use only composite and mask as inputs",
)
parser.add_option(
"--ibn",
action="store_true",
help="If specified, will use instance batch normalization",
)
parser.add_option(
"--dual",
action="store_true",
help="If specified, will use dual gainmaps",
)
parser.add_option(
"--nosubmask",
action="store_true",
help="If specified, will use dual gainmaps",
)
parser.add_option(
"--lowres",
action="store_true",
help="If specified, will use low res for training",
)
parser.add_option(
"--lightmodel",
action="store_true",
help="If specified, will use lightmodel",
)
parser.add_option("--maskingcp", help="Directory for masking checkpoint")
(options, args) = parser.parse_args()
return options
class Trainer:
def __init__(self):
self.args = get_args()
# self.device = torch.device(f"cuda:{self.args.gpu_id}")
self.device = torch.device(f"cuda")
print("Using device:", self.device)
self.checkpoint_directory = os.path.join(os.getcwd(), "checkpoints")
os.makedirs(self.checkpoint_directory, exist_ok=True)
if self.args.iharmdata:
self.dataset = DataCompositeGAN_iharmony(
self.args.datadir,
self.args.trainingratio,
augment=self.args.pairaugment,
colorjitter=self.args.colorjitter,
return_raw=self.args.returnraw,
lowres=self.args.lowres,
)
else:
self.dataset = DataCompositeGAN(
self.args.datadir,
self.args.trainingratio,
augment=self.args.pairaugment,
colorjitter=self.args.colorjitter,
lowres=self.args.lowres,
return_raw=self.args.returnraw,
ratio_constrain=self.args.ratioconstrain
)
self.dataloader = DataLoader(
self.dataset,
self.args.batchsize,
shuffle=True,
num_workers=self.args.workers,
prefetch_factor=8,
drop_last=True,
)
self.data_length = len(self.dataset)
if self.args.unet:
self.model = Model_UNet(input=self.args.inputdim)
else:
if self.args.piecewiselinear:
if self.args.twoinputs:
self.model = Model_Composite_PL_NoBG(
dim=self.args.pl_dim,
sigmoid=(not self.args.nosigmoid),
scaling=self.args.augreconweight,
masking=self.args.masking,
brush=self.args.brush,
nosig=self.args.nosig,
onlyupsample=self.args.onlyupsample,
maskoffset=self.args.maskoffset,
maskconvkernel=self.args.maskconvkernel,
swap=self.args.swap,
lut=self.args.lut,
lutdim=self.args.lut_dim,
joint=self.args.joint,
PIHNet_bool=self.args.pihnetbool,
Vit_bool=self.args.vitbool,
Eff_bool=self.args.effbool,
aggupsample=self.args.aggupsample,
lowres=self.args.lowres,
)
else:
self.model = Model_Composite_PL(
dim=self.args.pl_dim,
sigmoid=(not self.args.nosigmoid),
scaling=self.args.augreconweight,
masking=self.args.masking,
brush=self.args.brush,
nosig=self.args.nosig,
onlyupsample=self.args.onlyupsample,
maskoffset=self.args.maskoffset,
maskconvkernel=self.args.maskconvkernel,
swap=self.args.swap,
lut=self.args.lut,
lutdim=self.args.lut_dim,
joint=self.args.joint,
PIHNet_bool=self.args.pihnetbool,
Vit_bool=self.args.vitbool,
Eff_bool=self.args.effbool,
aggupsample=self.args.aggupsample,
depthmap=self.args.depthmap,
bgshadow=self.args.bgshadow,
ibn=self.args.ibn,
dual=self.args.dual,
lowres=self.args.lowres,
light=self.args.lightmodel,
)
else:
if self.args.lut:
self.model = Model_Composite(
feature_dim=self.args.features,
LUT=True,
LUTdim=self.args.lut_dim,
curve=not self.args.nocurve,
)
else:
self.model = Model_Composite(feature_dim=self.args.features)
num_parameters = sum(p.numel() for p in self.model.parameters() if p.requires_grad)
print("Number of parameters:", num_parameters)
if self.args.pixel:
self.model_D = networks.define_D(3, 64, "pixel")
else:
if self.args.unetd:
print("Input dim for discriminator: %d" % (self.args.inputdimD))
if self.args.unetdnoskip:
print("No Skip connection!")
self.model_D = UNetDiscriminatorSN(
input_dim=self.args.inputdimD,
skip_connection=False,
Low_dim=self.args.lowdim,
lessskip=self.args.lessskip,
)
else:
print("With Skip connection!")
self.model_D = UNetDiscriminatorSN(
input_dim=self.args.inputdimD,
Low_dim=self.args.lowdim,
lessskip=self.args.lessskip,
lowres=self.args.lowres,
)
else:
self.model_D = networks.define_D(3, 64, "n_layers", 3)
if torch.cuda.device_count() > 1 and self.args.multi_GPU:
print("Let's use", torch.cuda.device_count(), "GPUs!")
# dim = 0 [30, xxx] -> [10, ...], [10, ...], [10, ...] on 3 GPUs
self.model = torch.nn.DataParallel(self.model)
self.model_D = torch.nn.DataParallel(self.model_D)
self.model.to(self.device)
self.model_D.to(self.device)
self.criterion_GAN = networks.GANLoss(
"vanilla", gan_loss_mask=self.args.ganlossmask
).to(self.device)
if self.args.twoinputs:
print("Using 2 inputs, only composite and mask")
else:
print("Using 3 inputs, bg, composite and mask")
if self.args.ganlossmask:
print("Using GAN Loss Mask")
else:
print("Not using GAN Loss Mask")
if self.args.reconwithgan:
print(
"Using l1+gan for pair recon! l1 weight = %f" % (self.args.reconweight)
)
else:
print("Using gan for pair recon!")
print("recon ratio: %f" % (self.args.reconratio))
if self.args.augreconweight:
print(
"Using augmented recon weight, reconweight*ganloss + L1 loss, ranging from 0 - 1"
)
print("Using loss type:%d" % (self.args.losstype))
# if self.args.reconloss:
self.reconloss = torch.nn.L1Loss()
self.optimizer = torch.optim.Adam(
self.model.parameters(), lr=self.args.learning_rate
)
if self.args.scheduler:
self.scheduler = torch.optim.lr_scheduler.MultiStepLR(
self.optimizer, milestones=[20, 40, 60], gamma=0.5
) # learning rate decay
# print("current lr:",self.scheduler.get_lr())
if self.args.sgd:
print("Using SGD")
self.optimizer_D = torch.optim.SGD(
self.model_D.parameters(), lr=self.args.learning_rate_d, momentum=0.9
)
else:
print("Using Adam")
self.optimizer_D = torch.optim.Adam(
self.model_D.parameters(), lr=self.args.learning_rate_d
)
if self.args.scheduler:
self.scheduler_D = torch.optim.lr_scheduler.MultiStepLR(
self.optimizer_D, milestones=[20, 40, 60], gamma=0.5
) # learning rate decay
# print("current lr:",self.scheduler.get_lr())
self.start_epoch = 1
if not self.args.force_train_from_scratch:
self.restore_model()
else:
input("Training from scratch. Are you sure? (Ctrl+C to kill):")
if self.args.masking:
if self.args.maskingcp:
self.restore_mask_model()
else:
print("Using Joint training")
def load_matched_state_dict(self, model, state_dict, print_stats=True):
"""
Only loads weights that matched in key and shape. Ignore other weights.
"""
num_matched, num_total = 0, 0
curr_state_dict = model.state_dict()
for key in curr_state_dict.keys():
num_total += 1
if (
key in state_dict
and curr_state_dict[key].shape == state_dict[key].shape
):
curr_state_dict[key] = state_dict[key]
num_matched += 1
model.load_state_dict(curr_state_dict)
if print_stats:
print(f"Loaded state_dict: {num_matched}/{num_total} matched")
def restore_mask_model(self):
"""Restore latest model checkpoint (if any) and continue training from there."""
checkpoint_path = self.args.maskingcp
checkpoint = torch.load(checkpoint_path, map_location=self.device)
self.load_matched_state_dict(self.model, checkpoint["state_dict"])
# self.model.Resnet_no_grad()
def restore_model(self):
"""Restore latest model checkpoint (if any) and continue training from there."""
checkpoint_path = sorted(
glob(os.path.join(self.checkpoint_directory, "*")),
key=lambda x: int(re.match(".*[a-z]+(\d+).pth", x).group(1)),
)
if checkpoint_path:
checkpoint_path = checkpoint_path[-1]
print(f"Found saved model at: {checkpoint_path}")
checkpoint = torch.load(checkpoint_path, map_location=self.device)
self.model.load_state_dict(checkpoint["state_dict"])
self.optimizer.load_state_dict(checkpoint["optimizer_dict"])
self.start_epoch = (
checkpoint["epoch"] + 1
) # Start at next epoch of saved model
self.model_D.load_state_dict(checkpoint["state_dict_D"])
self.optimizer_D.load_state_dict(checkpoint["optimizer_dict_D"])
print(f"Finish restoring model. Resuming at epoch {self.start_epoch}")
else:
print("No saved model found. Training from scratch.")
def save_model(self, epoch):
"""Save model checkpoint.
Parameters
----------
epoch : int
The current epoch number.
"""
if self.args.onlysaveg:
torch.save(
{
"epoch": epoch, # Epoch we just finished
"state_dict": self.model.state_dict(),
"args": self.args,
},
os.path.join(self.checkpoint_directory, "ckpt_g{}.pth".format(epoch)),
)
else:
torch.save(
{
"epoch": epoch, # Epoch we just finished
"state_dict": self.model.state_dict(),
"optimizer_dict": self.optimizer.state_dict(),
"state_dict_D": self.model_D.state_dict(),
"optimizer_dict_D": self.optimizer_D.state_dict(),
"args": self.args,
},
os.path.join(self.checkpoint_directory, "ckpt{}.pth".format(epoch)),
)
def train(self):
"""Train the model!"""
# tqdm_bar = tqdm(range(self.start_epoch, self.args.epochs + 1), "Epoch")
# sys.exit()
losses_l1_all = []
losses_G_all = []
losses_D_all = []
losses_G_all_com = []
losses_D_all_com = []
for epoch in range(self.start_epoch, self.args.epochs + 1):
if self.args.scheduler:
self.scheduler.step()
self.scheduler_D.step()
print("current lr:", self.scheduler.get_last_lr())
print("current lr D:", self.scheduler_D.get_last_lr())
self.model.train()
tqdm_bar = tqdm(enumerate(self.dataloader), "Index")
for index, (
image_bg_bg,
im_composite,
mask,
im_real,
mask_bg,
im_real_augment,
fname,
bname,
) in tqdm_bar:
image_bg_bg = image_bg_bg.to(self.device)
im_composite = im_composite.to(self.device)
mask = mask.to(self.device)
im_real = im_real.to(self.device)
im_real_augment = im_real_augment.to(self.device)
mask_bg = mask_bg.to(self.device)
if np.random.rand() < self.args.reconratio or epoch <= self.args.warmup:
if self.args.unet:
# print("Using UNet")
input_composite, output_composite, par1, par2 = self.model(
im_real, mask_bg, image_bg_bg, mask=self.args.unetmask
)
# print(output_composite.max())
else:
if self.args.augreconweight:
self.model.setscalor(random.uniform(0, 1))
if self.args.twoinputs:
input_composite, output_composite, par1, par2 = self.model(
im_real, mask_bg
)
else:
input_composite, output_composite, par1, par2 = self.model(
image_bg_bg, im_real, mask_bg
)
if self.args.twoinputs:
(
input_composite_aug,
output_composite_aug,
par1_aug,
par2_aug,
) = self.model(im_real_augment, mask_bg)
else:
(
input_composite_aug,
output_composite_aug,
par1_aug,
par2_aug,
) = self.model(image_bg_bg, im_real_augment, mask_bg)
# print(par2_aug.shape)
if self.args.reconwithgan:
## Update D
if index % self.args.frequency == 0:
for param in self.model_D.parameters():
param.requires_grad = True
self.optimizer_D.zero_grad()
if self.args.inputdimD == 3:
# fake_AB = torch.cat((mask, output_composite), 1)
fake_AB = output_composite_aug.clone()
elif self.args.inputdimD == 4:
fake_AB = torch.cat((mask_bg, output_composite_aug), 1)
elif self.args.inputdimD == 6:
fake_AB = torch.cat(
(image_bg_bg, output_composite_aug), 1
)
elif self.args.inputdimD == 7:
fake_AB = torch.cat(
(image_bg_bg, mask_bg, output_composite_aug), 1
)
else:
print(
"Using a wrong input dimension for discriminator, supporting 3, 6, 7"
)
pred_fake = self.model_D(fake_AB.detach())
# print(pred_fake.shape)
if self.args.ganlossmask:
loss_D_fake = self.criterion_GAN(
pred_fake, False, mask=mask_bg
)
else:
loss_D_fake = self.criterion_GAN(pred_fake, False)
# real_AB = torch.cat((mask_bg, im_real), 1)
if self.args.inputdimD == 3:
real_AB = im_real.clone()
elif self.args.inputdimD == 4:
real_AB = torch.cat((mask_bg, im_real), 1)
elif self.args.inputdimD == 6:
real_AB = torch.cat((image_bg_bg, im_real), 1)
elif self.args.inputdimD == 7:
real_AB = torch.cat((image_bg_bg, mask_bg, im_real), 1)
pred_real = self.model_D(real_AB)
# print("Real_label mean: %f Fake label mean: %f"%(pred_real.mean(),pred_fake.mean()))
if self.args.ganlossmask:
loss_D_real = self.criterion_GAN(
pred_real, True, mask=mask_bg
)
else:
loss_D_real = self.criterion_GAN(pred_real, True)
loss_D = (
0.5
* (loss_D_fake + loss_D_real)
* (1 - self.args.reconweight)
)
if self.args.augreconweight:
if self.args.losstype == 0:
loss_D = loss_D * self.model.scalor
if self.args.losstype == 1:
loss_D = loss_D * self.model.scalor
if self.args.losstype == 2:
pass
loss_D.backward()
self.optimizer_D.step()
losses_D_all.append(loss_D.item())
## Update G
for param in self.model_D.parameters():
param.requires_grad = False
self.optimizer.zero_grad()
if self.args.inputdimD == 3:
# fake_AB = torch.cat((mask, output_composite), 1)
fake_AB = output_composite_aug.clone()
elif self.args.inputdimD == 4:
fake_AB = torch.cat((mask_bg, output_composite_aug), 1)
elif self.args.inputdimD == 6:
fake_AB = torch.cat((image_bg_bg, output_composite_aug), 1)
elif self.args.inputdimD == 7:
fake_AB = torch.cat(
(image_bg_bg, mask_bg, output_composite_aug), 1
)
else:
print(
"Using a wrong input dimension for discriminator, supporting 3, 6, 7"
)
pred_fake = self.model_D(fake_AB)
if self.args.ganlossmask:
loss_G_adv = self.criterion_GAN(
pred_fake, True, mask=mask_bg
)
else:
loss_G_adv = self.criterion_GAN(pred_fake, True)
# loss_l1 = self.reconloss(output_composite_aug, im_real)
if self.args.purepairaugment:
if self.args.bgshadow:
print("haha")
if self.args.nosubmask:
loss_l1 = self.reconloss(
output_composite_aug, im_real
)
else:
loss_l1 = self.reconloss(
output_composite_aug * mask_bg,
im_real * mask_bg,
)
print("l1", loss_l1)
print(
"l1_raw",
self.reconloss(output_composite_aug, im_real),
)
print(
"l1_mk",
self.reconloss(
output_composite_aug * mask_bg,
im_real * mask_bg,
),
)
else:
loss_l1 = self.reconloss(output_composite_aug, im_real)
else:
loss_l1 = 1 * self.reconloss(
output_composite, im_real
) + self.reconloss(output_composite_aug, im_real)
if self.args.augreconweight:
if self.args.losstype == 0:
# print("love 000")
loss_G_all = self.model.scalor * loss_G_adv + loss_l1
if self.args.losstype == 1:
# print("love 001")
loss_G_all = (
self.model.scalor * loss_G_adv
+ (1 - self.model.scalor) * loss_l1
)
if self.args.losstype == 2:
# print("love 002")
loss_G_all = (
self.model.scalor * loss_G_adv
+ (1 - self.model.scalor) * loss_l1
)
else:
loss_G_all = (
1 - self.args.reconweight
) * loss_G_adv + self.args.reconweight * loss_l1
# print("all", loss_G_all)
loss_G_all.backward()
self.optimizer.step()
if self.args.augreconweight:
tqdm_bar.set_description(
"E: {}. L_1: {:3f} L_1_raw: {:3f} L_G: {:3f} L_D: {:3f} L_all: {:3f} Scalor: {:3f}".format(
epoch,