forked from NVlabs/DG-Net-PP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
trainer.py
1615 lines (1462 loc) · 78.6 KB
/
trainer.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 (C) 2019 NVIDIA Corporation. All rights reserved.
Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).
"""
from networks import AdaINGen, MsImageDis, IdDis
from reIDmodel import ft_net, ft_netABe
from utils import get_model_list, vgg_preprocess, load_vgg16, get_scheduler
from torch.autograd import Variable
import torch
import torch.nn as nn
import torchvision
import copy
import os
import cv2
import numpy as np
from random_erasing import RandomErasing
from shutil import copyfile, copytree
import random
import yaml
from re_ranking_one import re_ranking_one
from sklearn.cluster import DBSCAN
def to_gray(half=False): #simple
def forward(x):
x = torch.mean(x, dim=1, keepdim=True)
if half:
x = x.half()
return x
return forward
def to_edge(x):
x = x.data.cpu()
out = torch.FloatTensor(x.size(0), x.size(2), x.size(3))
for i in range(x.size(0)):
xx = recover(x[i,:,:,:]) # 3 channel, 256x128x3
xx = cv2.cvtColor(xx, cv2.COLOR_RGB2GRAY) # 256x128x1
xx = cv2.Canny(xx, 10, 200) #256x128
xx = xx/255.0 - 0.5 # {-0.5,0.5}
xx += np.random.randn(xx.shape[0],xx.shape[1])*0.1 #add random noise
xx = torch.from_numpy(xx.astype(np.float32))
out[i,:,:] = xx
out = out.unsqueeze(1)
return out.cuda()
def scale2(x):
if x.size(2) > 128: # do not need to scale the input
return x
x = torch.nn.functional.upsample(x, scale_factor=2, mode='nearest') #bicubic is not available for the time being.
return x
def recover(inp):
inp = inp.numpy().transpose((1, 2, 0))
mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225])
inp = std * inp + mean
inp = inp * 255.0
inp = np.clip(inp, 0, 255)
inp = inp.astype(np.uint8)
return inp
def train_bn(m):
classname = m.__class__.__name__
if classname.find('BatchNorm') != -1:
m.train()
def fliplr(img):
'''flip horizontal'''
inv_idx = torch.arange(img.size(3)-1,-1,-1).long().cuda() # N x C x H x W
img_flip = img.index_select(3,inv_idx)
return img_flip
def update_teacher(model_s, model_t, alpha=0.999):
for param_s, param_t in zip(model_s.parameters(), model_t.parameters()):
param_t.data.mul_(alpha).add_(1 - alpha, param_s.data)
def predict_label(teacher_models, inputs, num_class, alabel, slabel, teacher_style=0):
# teacher_style:
# 0: Our smooth dynamic label
# 1: Pseudo label, hard dynamic label
# 2: Conditional label, hard static label
# 3: LSRO, static smooth label
# 4: Dynamic Soft Two-label
# alabel is appearance label
if teacher_style == 0:
count = 0
sm = nn.Softmax(dim=1)
for teacher_model in teacher_models:
_, outputs_t1 = teacher_model(inputs)
outputs_t1 = sm(outputs_t1.detach())
_, outputs_t2 = teacher_model(fliplr(inputs))
outputs_t2 = sm(outputs_t2.detach())
if count==0:
outputs_t = outputs_t1 + outputs_t2
else:
outputs_t = outputs_t * opt.alpha # old model decay
outputs_t += outputs_t1 + outputs_t2
count +=2
elif teacher_style == 1: # dynamic one-hot label
count = 0
sm = nn.Softmax(dim=1)
for teacher_model in teacher_models:
_, outputs_t1 = teacher_model(inputs)
outputs_t1 = sm(outputs_t1.detach()) # change softmax to max
_, outputs_t2 = teacher_model(fliplr(inputs))
outputs_t2 = sm(outputs_t2.detach())
if count==0:
outputs_t = outputs_t1 + outputs_t2
else:
outputs_t = outputs_t * opt.alpha # old model decay
outputs_t += outputs_t1 + outputs_t2
count +=2
_, dlabel = torch.max(outputs_t.data, 1)
outputs_t = torch.zeros(inputs.size(0), num_class).cuda()
for i in range(inputs.size(0)):
outputs_t[i, dlabel[i]] = 1
elif teacher_style == 2: # appearance label
outputs_t = torch.zeros(inputs.size(0), num_class).cuda()
for i in range(inputs.size(0)):
outputs_t[i, alabel[i]] = 1
elif teacher_style == 3: # LSRO
outputs_t = torch.ones(inputs.size(0), num_class).cuda()
elif teacher_style == 4: #Two-label
count = 0
sm = nn.Softmax(dim=1)
for teacher_model in teacher_models:
_, outputs_t1 = teacher_model(inputs)
outputs_t1 = sm(outputs_t1.detach())
_, outputs_t2 = teacher_model(fliplr(inputs))
outputs_t2 = sm(outputs_t2.detach())
if count==0:
outputs_t = outputs_t1 + outputs_t2
else:
outputs_t = outputs_t * opt.alpha # old model decay
outputs_t += outputs_t1 + outputs_t2
count +=2
mask = torch.zeros(outputs_t.shape)
mask = mask.cuda()
for i in range(inputs.size(0)):
mask[i, alabel[i]] = 1
mask[i, slabel[i]] = 1
outputs_t = outputs_t*mask
else:
print('not valid style. teacher-style is in [0-3].')
s = torch.sum(outputs_t, dim=1, keepdim=True)
s = s.expand_as(outputs_t)
outputs_t = outputs_t/s
return outputs_t
######################################################################
# Load model
#---------------------------
def load_network(network, name):
save_path = os.path.join('./models',name,'net_last.pth')
network.load_state_dict(torch.load(save_path))
return network
def load_config(name):
config_path = os.path.join('./models',name,'opts.yaml')
with open(config_path, 'r') as stream:
config = yaml.load(stream)
return config
def norm(f, dim = 1):
f = f.squeeze()
fnorm = torch.norm(f, p=2, dim=dim, keepdim=True)
f = f.div(fnorm.expand_as(f))
return f
def get_id(img_path, time_constraint = False):
camera_id = []
time_id = []
labels = []
for path, v in img_path:
# filename = path.split('/')[-1]
filename = os.path.basename(path)
label = filename[0:4]
camera = filename.split('c')[1]
if time_constraint:
metadata = filename.split('_')
num_metadata = len(metadata)
if num_metadata == 3:
time = filename.split('f')[1]
elif num_metadata == 4:
time = metadata[2]
# print(camera)
if label[0:2] == '-1':
labels.append(-1)
else:
labels.append(int(label))
camera_id.append(int(camera[0]))
if time_constraint:
if num_metadata == 3:
time_id.append(int(time[0:7]))
elif num_metadata == 4:
time_id.append(int(time[0:6]))
return camera_id, labels, time_id
def evaluate(qf, ql, qc, gf, gl, gc):
query = qf.view(-1, 1)
# print(query.shape)
score = torch.mm(gf, query)
score = score.squeeze(1).cpu()
score = score.numpy()
# predict index
index = np.argsort(score) # from small to large
index = index[::-1]
# index = index[0:2000]
# good index
query_index = np.argwhere(gl == ql)
# same camera
camera_index = np.argwhere(gc == qc)
good_index = np.setdiff1d(query_index, camera_index, assume_unique=True)
junk_index1 = np.argwhere(gl == -1)
junk_index2 = np.intersect1d(query_index, camera_index)
junk_index = np.append(junk_index2, junk_index1) # .flatten())
CMC_tmp = compute_mAP(index, gc, good_index, junk_index)
return CMC_tmp
def compute_mAP(index, gc, good_index, junk_index):
ap = 0
cmc = torch.IntTensor(len(index)).zero_()
if good_index.size == 0: # if empty
cmc[0] = -1
return ap, cmc
# remove junk_index
ranked_camera = gc[index]
mask = np.in1d(index, junk_index, invert=True)
mask2 = np.in1d(index, np.append(good_index, junk_index), invert=True)
index = index[mask]
ranked_camera = ranked_camera[mask]
# find good_index index
ngood = len(good_index)
mask = np.in1d(index, good_index)
rows_good = np.argwhere(mask == True)
rows_good = rows_good.flatten()
cmc[rows_good[0]:] = 1
for i in range(ngood):
d_recall = 1.0 / ngood
precision = (i + 1) * 1.0 / (rows_good[i] + 1)
if rows_good[i] != 0:
old_precision = i * 1.0 / rows_good[i]
else:
old_precision = 1.0
ap = ap + d_recall * (old_precision + precision) / 2
return ap, cmc
class DGNetpp_Trainer(nn.Module):
def __init__(self, hyperparameters):
super(DGNetpp_Trainer, self).__init__()
lr_g = hyperparameters['lr_g']
lr_d = hyperparameters['lr_d']
lr_id_d = hyperparameters['lr_id_d']
ID_class_a = hyperparameters['ID_class_a']
# Initiate the networks
# We do not need to manually set fp16 in the network. So here I set fp16=False.
self.gen_a = AdaINGen(hyperparameters['input_dim_a'], hyperparameters['gen'], fp16=False) # auto-encoder for domain a
self.gen_b = AdaINGen(hyperparameters['input_dim_b'], hyperparameters['gen'], fp16=False) # auto-encoder for domain b
if not 'ID_stride' in hyperparameters.keys():
hyperparameters['ID_stride'] = 2
self.id_a = ft_netABe(ID_class_a + hyperparameters['ID_class_b'], stride=hyperparameters['ID_stride'], norm=hyperparameters['norm_id'], pool=hyperparameters['pool'])
self.id_b = self.id_a
self.dis_a = MsImageDis(3, hyperparameters['dis'], fp16=False) # discriminator for domain a
self.dis_b = self.dis_a
self.id_dis = IdDis(hyperparameters['gen']['id_dim'], hyperparameters['dis'], fp16=False) # ID discriminator
# load teachers
if hyperparameters['teacher'] != "":
teacher_name = hyperparameters['teacher']
print(teacher_name)
teacher_names = teacher_name.split(',')
teacher_model = nn.ModuleList()
teacher_count = 0
for teacher_name in teacher_names:
config_tmp = load_config(teacher_name)
if 'stride' in config_tmp:
stride = config_tmp['stride']
else:
stride = 2
model_tmp = ft_net(ID_class_a, stride = stride)
teacher_model_tmp = load_network(model_tmp, teacher_name)
teacher_model_tmp.model.fc = nn.Sequential() # remove the original fc layer in ImageNet
teacher_model_tmp = teacher_model_tmp.cuda()
teacher_model.append(teacher_model_tmp.cuda().eval())
teacher_count += 1
self.teacher_model = teacher_model
if hyperparameters['train_bn']:
self.teacher_model = self.teacher_model.apply(train_bn)
self.instancenorm = nn.InstanceNorm2d(512, affine=False)
display_size = int(hyperparameters['display_size'])
# RGB to one channel
if hyperparameters['single'] == 'edge':
self.single = to_edge
else:
self.single = to_gray(False)
# Random Erasing when training
if not 'erasing_p' in hyperparameters.keys():
hyperparameters['erasing_p'] = 0
self.single_re = RandomErasing(probability=hyperparameters['erasing_p'], mean=[0.0, 0.0, 0.0])
if not 'T_w' in hyperparameters.keys():
hyperparameters['T_w'] = 1
# Setup the optimizers
beta1 = hyperparameters['beta1']
beta2 = hyperparameters['beta2']
dis_a_params = list(self.dis_a.parameters())
gen_a_params = list(self.gen_a.parameters())
gen_b_params = list(self.gen_b.parameters())
id_dis_params = list(self.id_dis.parameters())
self.dis_a_opt = torch.optim.Adam([p for p in dis_a_params if p.requires_grad],
lr=lr_d, betas=(beta1, beta2), weight_decay=hyperparameters['weight_decay'])
self.id_dis_opt = torch.optim.Adam([p for p in id_dis_params if p.requires_grad],
lr=lr_id_d, betas=(beta1, beta2), weight_decay=hyperparameters['weight_decay'])
self.gen_a_opt = torch.optim.Adam([p for p in gen_a_params if p.requires_grad],
lr=lr_g, betas=(beta1, beta2), weight_decay=hyperparameters['weight_decay'])
self.gen_b_opt = torch.optim.Adam([p for p in gen_b_params if p.requires_grad],
lr=lr_g, betas=(beta1, beta2), weight_decay=hyperparameters['weight_decay'])
# id params
ignored_params = (list(map(id, self.id_a.classifier1.parameters()))
+ list(map(id, self.id_a.classifier2.parameters())))
base_params = filter(lambda p: id(p) not in ignored_params, self.id_a.parameters())
lr2 = hyperparameters['lr2']
self.id_opt = torch.optim.SGD([
{'params': base_params, 'lr': lr2},
{'params': self.id_a.classifier1.parameters(), 'lr': lr2 * 10},
{'params': self.id_a.classifier2.parameters(), 'lr': lr2 * 10}
], weight_decay=hyperparameters['weight_decay'], momentum=0.9, nesterov=True)
self.dis_a_scheduler = get_scheduler(self.dis_a_opt, hyperparameters)
self.id_dis_scheduler = get_scheduler(self.id_dis_opt, hyperparameters)
self.id_dis_scheduler.gamma = hyperparameters['gamma2']
self.gen_a_scheduler = get_scheduler(self.gen_a_opt, hyperparameters)
self.gen_b_scheduler = get_scheduler(self.gen_b_opt, hyperparameters)
self.id_scheduler = get_scheduler(self.id_opt, hyperparameters)
self.id_scheduler.gamma = hyperparameters['gamma2']
# ID Loss
self.id_criterion = nn.CrossEntropyLoss()
self.criterion_teacher = nn.KLDivLoss(size_average=False)
# Load VGG model if needed
if 'vgg_w' in hyperparameters.keys() and hyperparameters['vgg_w'] > 0:
self.vgg = load_vgg16(hyperparameters['vgg_model_path'] + '/models')
self.vgg.eval()
for param in self.vgg.parameters():
param.requires_grad = False
def to_re(self, x):
out = torch.FloatTensor(x.size(0), x.size(1), x.size(2), x.size(3))
out = out.cuda()
for i in range(x.size(0)):
out[i, :, :, :] = self.single_re(x[i, :, :, :])
return out
def recon_criterion(self, input, target):
diff = input - target.detach()
return torch.mean(torch.abs(diff[:]))
def recon_criterion_sqrt(self, input, target):
diff = input - target
return torch.mean(torch.sqrt(torch.abs(diff[:]) + 1e-8))
def recon_criterion2(self, input, target):
diff = input - target
return torch.mean(diff[:] ** 2)
def recon_cos(self, input, target):
cos = torch.nn.CosineSimilarity()
cos_dis = 1 - cos(input, target)
return torch.mean(cos_dis[:])
def forward(self, x_a, x_b):
self.eval()
s_a = self.gen_a.encode(self.single(x_a))
s_b = self.gen_b.encode(self.single(x_b))
f_a, _, _ = self.id_a(scale2(x_a))
f_b, _, _ = self.id_b(scale2(x_b))
x_ba = self.gen_b.decode(s_b, f_a)
x_ab = self.gen_a.decode(s_a, f_b)
self.train()
return x_ab, x_ba
def gen_update_ab(self, x_a, l_a, xp_a, x_b, l_b, xp_b, hyperparameters, iteration):
# ppa, ppb is the same person
self.gen_a_opt.zero_grad()
self.gen_b_opt.zero_grad()
self.id_opt.zero_grad()
self.id_dis_opt.zero_grad()
# encode
s_a = self.gen_a.encode(self.single(x_a))
s_b = self.gen_b.encode(self.single(x_b))
f_a, p_a, fe_a = self.id_a(scale2(x_a))
f_b, p_b, fe_b = self.id_b(scale2(x_b))
# autodecode
x_a_recon = self.gen_a.decode(s_a, f_a)
x_b_recon = self.gen_b.decode(s_b, f_b)
# encode the same ID different photo
fp_a, pp_a, fe_pa = self.id_a(scale2(xp_a))
fp_b, pp_b, fe_pb = self.id_b(scale2(xp_b))
# decode the same person
x_a_recon_p = self.gen_a.decode(s_a, fp_a)
x_b_recon_p = self.gen_b.decode(s_b, fp_b)
# has gradient
x_ba = self.gen_b.decode(s_b, f_a)
x_ab = self.gen_a.decode(s_a, f_b)
# no gradient
x_ba_copy = Variable(x_ba.data, requires_grad=False)
x_ab_copy = Variable(x_ab.data, requires_grad=False)
rand_num = random.uniform(0, 1)
#################################
# encode structure
if hyperparameters['use_encoder_again'] >= rand_num:
# encode again (encoder is tuned, input is fixed)
s_a_recon = self.gen_a.enc_content(self.single(x_ab_copy))
s_b_recon = self.gen_b.enc_content(self.single(x_ba_copy))
else:
# copy the encoder
self.enc_content_a_copy = copy.deepcopy(self.gen_a.enc_content)
self.enc_content_a_copy = self.enc_content_a_copy.eval()
self.enc_content_b_copy = copy.deepcopy(self.gen_b.enc_content)
self.enc_content_b_copy = self.enc_content_b_copy.eval()
# encode again (encoder is fixed, input is tuned)
s_a_recon = self.enc_content_a_copy(self.single(x_ab))
s_b_recon = self.enc_content_b_copy(self.single(x_ba))
#################################
# encode appearance
self.id_a_copy = copy.deepcopy(self.id_a)
self.id_a_copy = self.id_a_copy.eval()
if hyperparameters['train_bn']:
self.id_a_copy = self.id_a_copy.apply(train_bn)
self.id_b_copy = self.id_a_copy
# encode again (encoder is fixed, input is tuned)
f_a_recon, p_a_recon, _ = self.id_a_copy(scale2(x_ba))
f_b_recon, p_b_recon, _ = self.id_b_copy(scale2(x_ab))
# teacher Loss
# Tune the ID model
log_sm = nn.LogSoftmax(dim=1)
if hyperparameters['teacher_w'] > 0 and hyperparameters['teacher'] != "":
if hyperparameters['ID_style'] == 'normal':
_, p_a_student, _ = self.id_a(scale2(x_ba_copy))
p_a_student = log_sm(p_a_student)
p_a_teacher = predict_label(self.teacher_model, scale2(x_ba_copy))
self.loss_teacher = self.criterion_teacher(p_a_student, p_a_teacher) / p_a_student.size(0)
_, p_b_student, _ = self.id_b(scale2(x_ab_copy))
p_b_student = log_sm(p_b_student)
p_b_teacher = predict_label(self.teacher_model, scale2(x_ab_copy))
self.loss_teacher += self.criterion_teacher(p_b_student, p_b_teacher) / p_b_student.size(0)
elif hyperparameters['ID_style'] == 'AB':
# normal teacher-student loss
# BA -> LabelA(smooth) + LabelB(batchB)
_, p_ba_student, _ = self.id_a(scale2(x_ba_copy)) # f_a, s_b
p_a_student = log_sm(p_ba_student[0])
with torch.no_grad():
p_a_teacher = predict_label(self.teacher_model, scale2(x_ba_copy),
num_class=hyperparameters['ID_class_a'], alabel=l_a, slabel=l_b,
teacher_style=hyperparameters['teacher_style'])
p_a_teacher = torch.cat(
(p_a_teacher, torch.zeros((p_a_teacher.size(0), hyperparameters['ID_class_b'])).cuda()),
1).detach()
self.loss_teacher = self.criterion_teacher(p_a_student, p_a_teacher) / p_a_student.size(0)
_, p_ab_student, _ = self.id_b(scale2(x_ab_copy)) # f_b, s_a
# branch b loss
# here we give different label
self.loss_teacher = hyperparameters['T_w'] * self.loss_teacher
loss_B = self.id_criterion(p_ab_student[1], l_a)
self.loss_teacher = self.loss_teacher + hyperparameters['B_w'] * loss_B
else:
self.loss_teacher = 0.0
# decode again (if needed)
if hyperparameters['use_decoder_again']:
x_aba = self.gen_a.decode(s_a_recon, f_a_recon) if hyperparameters['recon_x_cyc_w'] > 0 else None
x_bab = self.gen_b.decode(s_b_recon, f_b_recon) if hyperparameters['recon_x_cyc_w'] > 0 else None
else:
self.mlp_w_a_copy = copy.deepcopy(self.gen_a.mlp_w)
self.mlp_b_a_copy = copy.deepcopy(self.gen_a.mlp_b)
self.dec_a_copy = copy.deepcopy(self.gen_a.dec) # Error
ID = f_a_recon
ID_Style = ID.view(ID.shape[0], ID.shape[1], 1, 1)
adain_params_w_a = self.mlp_w_a_copy(ID_Style)
adain_params_b_a = self.mlp_b_a_copy(ID_Style)
self.gen_a.assign_adain_params(adain_params_w_a, adain_params_b_a, self.dec_a_copy)
x_aba = self.dec_a_copy(s_a_recon) if hyperparameters['recon_x_cyc_w'] > 0 else None
self.mlp_w_b_copy = copy.deepcopy(self.gen_b.mlp_w)
self.mlp_b_b_copy = copy.deepcopy(self.gen_b.mlp_b)
self.dec_b_copy = copy.deepcopy(self.gen_b.dec) # Error
ID = f_b_recon
ID_Style = ID.view(ID.shape[0], ID.shape[1], 1, 1)
adain_params_w_b = self.mlp_w_b_copy(ID_Style)
adain_params_b_b = self.mlp_b_b_copy(ID_Style)
self.gen_a.assign_adain_params(adain_params_w_b, adain_params_b_b, self.dec_b_copy)
x_bab = self.dec_b_copy(s_b_recon) if hyperparameters['recon_x_cyc_w'] > 0 else None
# auto-encoder image reconstruction
self.loss_gen_recon_x_a = self.recon_criterion(x_a_recon, x_a)
self.loss_gen_recon_x_b = self.recon_criterion(x_b_recon, x_b)
self.loss_gen_recon_xp_a = self.recon_criterion(x_a_recon_p, x_a)
self.loss_gen_recon_xp_b = self.recon_criterion(x_b_recon_p, x_b)
# feature reconstruction
self.loss_gen_recon_s_a = self.recon_criterion(s_a_recon, s_a) if hyperparameters['recon_s_w'] > 0 else 0
self.loss_gen_recon_s_b = self.recon_criterion(s_b_recon, s_b) if hyperparameters['recon_s_w'] > 0 else 0
self.loss_gen_recon_f_a = self.recon_criterion(f_a_recon, f_a) if hyperparameters['recon_f_w'] > 0 else 0
self.loss_gen_recon_f_b = self.recon_criterion(f_b_recon, f_b) if hyperparameters['recon_f_w'] > 0 else 0
# Random Erasing only effect the ID and PID loss.
if hyperparameters['erasing_p'] > 0:
x_a_re = self.to_re(scale2(x_a.clone()))
x_b_re = self.to_re(scale2(x_b.clone()))
xp_a_re = self.to_re(scale2(xp_a.clone()))
xp_b_re = self.to_re(scale2(xp_b.clone()))
_, p_a, _ = self.id_a(x_a_re)
_, p_b, _ = self.id_b(x_b_re)
# encode the same ID different photo
_, pp_a, _ = self.id_a(xp_a_re)
_, pp_b, _ = self.id_b(xp_b_re)
# ID loss AND Tune the Generated image
weight_B = hyperparameters['teacher_w'] * hyperparameters['B_w']
if hyperparameters['id_tgt']:
self.loss_id = self.id_criterion(p_a[0], l_a) + self.id_criterion(p_b[0], l_b) \
+ weight_B * (self.id_criterion(p_a[1], l_a) + self.id_criterion(p_b[1], l_b))
self.loss_pid = self.id_criterion(pp_a[0], l_a) + hyperparameters['tgt_pos'] * self.id_criterion(pp_b[0],l_b) # + weight_B * ( self.id_criterion(pp_a[1], l_a) + self.id_criterion(pp_b[1], l_b) )
self.loss_gen_recon_id = self.id_criterion(p_a_recon[0], l_a) + self.id_criterion(p_b_recon[0], l_b)
else:
self.loss_id = self.id_criterion(p_a[0], l_a) + weight_B * self.id_criterion(p_a[1], l_a)
self.loss_pid = self.id_criterion(pp_a[0], l_a)
self.loss_gen_recon_id = self.id_criterion(p_a_recon[0], l_a)
# print(f_a_recon, f_a)
self.loss_gen_cycrecon_x_a = self.recon_criterion(x_aba, x_a) if hyperparameters['recon_x_cyc_w'] > 0 else 0
self.loss_gen_cycrecon_x_b = self.recon_criterion(x_bab, x_b) if hyperparameters['recon_x_cyc_w'] > 0 else 0
# GAN loss
self.loss_gen_adv_a = self.dis_a.calc_gen_loss(x_ba)
self.loss_gen_adv_b = self.dis_a.calc_gen_loss(x_ab)
# domain-invariant perceptual loss
self.loss_gen_vgg_a = self.compute_vgg_loss(self.vgg, x_ba, x_b) if hyperparameters['vgg_w'] > 0 else 0
self.loss_gen_vgg_b = self.compute_vgg_loss(self.vgg, x_ab, x_a) if hyperparameters['vgg_w'] > 0 else 0
# ID domain adversarial loss
self.loss_gen_id_adv = self.id_dis.calc_gen_loss(fe_b) if hyperparameters['id_adv_w'] > 0 else 0
if iteration > hyperparameters['warm_iter']:
hyperparameters['recon_f_w'] += hyperparameters['warm_scale']
hyperparameters['recon_f_w'] = min(hyperparameters['recon_f_w'], hyperparameters['max_w'])
hyperparameters['recon_s_w'] += hyperparameters['warm_scale']
hyperparameters['recon_s_w'] = min(hyperparameters['recon_s_w'], hyperparameters['max_w'])
hyperparameters['recon_x_cyc_w'] += hyperparameters['warm_scale']
hyperparameters['recon_x_cyc_w'] = min(hyperparameters['recon_x_cyc_w'], hyperparameters['max_cyc_w'])
if iteration > hyperparameters['warm_teacher_iter']:
hyperparameters['teacher_w'] += hyperparameters['warm_scale']
hyperparameters['teacher_w'] = min(hyperparameters['teacher_w'], hyperparameters['max_teacher_w'])
hyperparameters['id_adv_w'] += hyperparameters['adv_warm_scale']
hyperparameters['id_adv_w'] = min(hyperparameters['id_adv_w'], hyperparameters['id_adv_w_max'])
# total loss
self.loss_gen_total = hyperparameters['gan_w'] * self.loss_gen_adv_a + \
hyperparameters['gan_w'] * self.loss_gen_adv_b + \
hyperparameters['recon_x_w'] * self.loss_gen_recon_x_a + \
hyperparameters['recon_xp_w'] * self.loss_gen_recon_xp_a + \
hyperparameters['recon_f_w'] * self.loss_gen_recon_f_a + \
hyperparameters['recon_s_w'] * self.loss_gen_recon_s_a + \
hyperparameters['recon_x_w'] * self.loss_gen_recon_x_b + \
hyperparameters['recon_xp_w'] * hyperparameters['recon_xp_tgt_w'] * self.loss_gen_recon_xp_b + \
hyperparameters['recon_f_w'] * self.loss_gen_recon_f_b + \
hyperparameters['recon_s_w'] * self.loss_gen_recon_s_b + \
hyperparameters['recon_x_cyc_w'] * self.loss_gen_cycrecon_x_a + \
hyperparameters['recon_x_cyc_w'] * self.loss_gen_cycrecon_x_b + \
hyperparameters['id_w'] * self.loss_id + \
hyperparameters['pid_w'] * self.loss_pid + \
hyperparameters['recon_id_w'] * self.loss_gen_recon_id + \
hyperparameters['vgg_w'] * self.loss_gen_vgg_a + \
hyperparameters['vgg_w'] * self.loss_gen_vgg_b + \
hyperparameters['teacher_w'] * self.loss_teacher + \
hyperparameters['id_adv_w'] * self.loss_gen_id_adv
self.loss_gen_total.backward()
self.gen_a_opt.step()
self.gen_b_opt.step()
self.id_opt.step()
print(
"L_total: %.4f, L_gan: %.4f, L_adv: %.4f, Lx: %.4f, Lxp: %.4f, Lrecycle:%.4f, Lf: %.4f, Ls: %.4f, Recon-id: %.4f, id: %.4f, pid:%.4f, teacher: %.4f" % (
self.loss_gen_total, \
hyperparameters['gan_w'] * (self.loss_gen_adv_a + self.loss_gen_adv_b), \
hyperparameters['id_adv_w'] * (self.loss_gen_id_adv), \
hyperparameters['recon_x_w'] * (self.loss_gen_recon_x_a + self.loss_gen_recon_x_b), \
hyperparameters['recon_xp_w'] * (self.loss_gen_recon_xp_a + hyperparameters['recon_xp_tgt_w'] * self.loss_gen_recon_xp_b), \
hyperparameters['recon_x_cyc_w'] * (self.loss_gen_cycrecon_x_a + self.loss_gen_cycrecon_x_b), \
hyperparameters['recon_f_w'] * (self.loss_gen_recon_f_a + self.loss_gen_recon_f_b), \
hyperparameters['recon_s_w'] * (self.loss_gen_recon_s_a + self.loss_gen_recon_s_b), \
hyperparameters['recon_id_w'] * self.loss_gen_recon_id, \
hyperparameters['id_w'] * self.loss_id, \
hyperparameters['pid_w'] * self.loss_pid, \
hyperparameters['teacher_w'] * self.loss_teacher))
def gen_update_aa(self, x_a, l_a, xp_a, x_b, l_b, xp_b, hyperparameters, iteration):
# ppa, ppb is the same person
self.gen_a_opt.zero_grad()
self.id_opt.zero_grad()
self.id_dis_opt.zero_grad()
# encode
s_a = self.gen_a.encode(self.single(x_a))
s_b = self.gen_a.encode(self.single(x_b))
f_a, p_a, _ = self.id_a(scale2(x_a))
f_b, p_b, _ = self.id_a(scale2(x_b))
# autodecode
x_a_recon = self.gen_a.decode(s_a, f_a)
x_b_recon = self.gen_a.decode(s_b, f_b)
# encode the same ID different photo
fp_a, pp_a, _ = self.id_a(scale2(xp_a))
fp_b, pp_b, _ = self.id_a(scale2(xp_b))
# decode the same person
x_a_recon_p = self.gen_a.decode(s_a, fp_a)
x_b_recon_p = self.gen_a.decode(s_b, fp_b)
# has gradient
x_ba = self.gen_a.decode(s_b, f_a)
x_ab = self.gen_a.decode(s_a, f_b)
# no gradient
x_ba_copy = Variable(x_ba.data, requires_grad=False)
x_ab_copy = Variable(x_ab.data, requires_grad=False)
rand_num = random.uniform(0, 1)
#################################
# encode structure
if hyperparameters['use_encoder_again'] >= rand_num:
# encode again (encoder is tuned, input is fixed)
s_a_recon = self.gen_a.enc_content(self.single(x_ab_copy))
s_b_recon = self.gen_a.enc_content(self.single(x_ba_copy))
else:
# copy the encoder
self.enc_content_copy = copy.deepcopy(self.gen_a.enc_content)
self.enc_content_copy = self.enc_content_copy.eval()
# encode again (encoder is fixed, input is tuned)
s_a_recon = self.enc_content_copy(self.single(x_ab))
s_b_recon = self.enc_content_copy(self.single(x_ba))
#################################
# encode appearance
self.id_a_copy = copy.deepcopy(self.id_a)
self.id_a_copy = self.id_a_copy.eval()
if hyperparameters['train_bn']:
self.id_a_copy = self.id_a_copy.apply(train_bn)
self.id_b_copy = self.id_a_copy
# encode again (encoder is fixed, input is tuned)
f_a_recon, p_a_recon, _ = self.id_a_copy(scale2(x_ba))
f_b_recon, p_b_recon, _ = self.id_b_copy(scale2(x_ab))
# teacher Loss
# Tune the ID model
log_sm = nn.LogSoftmax(dim=1)
if hyperparameters['teacher_w'] > 0 and hyperparameters['teacher'] != "":
if hyperparameters['ID_style'] == 'normal':
_, p_a_student, _ = self.id_a(scale2(x_ba_copy))
p_a_student = log_sm(p_a_student)
p_a_teacher = predict_label(self.teacher_model, scale2(x_ba_copy))
self.loss_teacher = self.criterion_teacher(p_a_student, p_a_teacher) / p_a_student.size(0)
_, p_b_student, _ = self.id_a(scale2(x_ab_copy))
p_b_student = log_sm(p_b_student)
p_b_teacher = predict_label(self.teacher_model, scale2(x_ab_copy))
self.loss_teacher += self.criterion_teacher(p_b_student, p_b_teacher) / p_b_student.size(0)
elif hyperparameters['ID_style'] == 'AB':
# normal teacher-student loss
# BA -> LabelA(smooth) + LabelB(batchB)
_, p_ba_student, _ = self.id_a(scale2(x_ba_copy)) # f_a, s_b
p_a_student = log_sm(p_ba_student[0])
with torch.no_grad():
p_a_teacher = predict_label(self.teacher_model, scale2(x_ba_copy),
num_class=hyperparameters['ID_class_a'], alabel=l_a, slabel=l_b,
teacher_style=hyperparameters['teacher_style'])
p_a_teacher = torch.cat(
(p_a_teacher, torch.zeros((p_a_teacher.size(0), hyperparameters['ID_class_b'])).cuda()),
1).detach()
self.loss_teacher = self.criterion_teacher(p_a_student, p_a_teacher) / p_a_student.size(0)
_, p_ab_student, _ = self.id_a(scale2(x_ab_copy)) # f_b, s_a
p_b_student = log_sm(p_ab_student[0])
with torch.no_grad():
p_b_teacher = predict_label(self.teacher_model, scale2(x_ab_copy),
num_class=hyperparameters['ID_class_a'], alabel=l_b, slabel=l_a,
teacher_style=hyperparameters['teacher_style'])
p_b_teacher = torch.cat(
(p_b_teacher, torch.zeros((p_b_teacher.size(0), hyperparameters['ID_class_b'])).cuda()),
1).detach()
self.loss_teacher += self.criterion_teacher(p_b_student, p_b_teacher) / p_b_student.size(0)
# branch b loss
# here we give different label
loss_B = self.id_criterion(p_ba_student[1], l_b) + self.id_criterion(p_ab_student[1], l_a)
self.loss_teacher = hyperparameters['T_w'] * self.loss_teacher + hyperparameters['B_w'] * loss_B
else:
self.loss_teacher = 0.0
# decode again (if needed)
if hyperparameters['use_decoder_again']:
x_aba = self.gen_a.decode(s_a_recon, f_a_recon) if hyperparameters['recon_x_cyc_w'] > 0 else None
x_bab = self.gen_a.decode(s_b_recon, f_b_recon) if hyperparameters['recon_x_cyc_w'] > 0 else None
else:
self.mlp_w_copy = copy.deepcopy(self.gen_a.mlp_w)
self.mlp_b_copy = copy.deepcopy(self.gen_a.mlp_b)
self.dec_copy = copy.deepcopy(self.gen_a.dec) # Error
ID = f_a_recon
ID_Style = ID.view(ID.shape[0], ID.shape[1], 1, 1)
adain_params_w = self.mlp_w_copy(ID_Style)
adain_params_b = self.mlp_b_copy(ID_Style)
self.gen_a.assign_adain_params(adain_params_w, adain_params_b, self.dec_copy)
x_aba = self.dec_copy(s_a_recon) if hyperparameters['recon_x_cyc_w'] > 0 else None
ID = f_b_recon
ID_Style = ID.view(ID.shape[0], ID.shape[1], 1, 1)
adain_params_w = self.mlp_w_copy(ID_Style)
adain_params_b = self.mlp_b_copy(ID_Style)
self.gen_a.assign_adain_params(adain_params_w, adain_params_b, self.dec_copy)
x_bab = self.dec_copy(s_b_recon) if hyperparameters['recon_x_cyc_w'] > 0 else None
# auto-encoder image reconstruction
self.loss_gen_recon_x_a = self.recon_criterion(x_a_recon, x_a)
self.loss_gen_recon_x_b = self.recon_criterion(x_b_recon, x_b)
self.loss_gen_recon_xp_a = self.recon_criterion(x_a_recon_p, x_a)
self.loss_gen_recon_xp_b = self.recon_criterion(x_b_recon_p, x_b)
# feature reconstruction
self.loss_gen_recon_s_a = self.recon_criterion(s_a_recon, s_a) if hyperparameters['recon_s_w'] > 0 else 0
self.loss_gen_recon_s_b = self.recon_criterion(s_b_recon, s_b) if hyperparameters['recon_s_w'] > 0 else 0
self.loss_gen_recon_f_a = self.recon_criterion(f_a_recon, f_a) if hyperparameters['recon_f_w'] > 0 else 0
self.loss_gen_recon_f_b = self.recon_criterion(f_b_recon, f_b) if hyperparameters['recon_f_w'] > 0 else 0
# Random Erasing only effect the ID and PID loss.
if hyperparameters['erasing_p'] > 0:
x_a_re = self.to_re(scale2(x_a.clone()))
x_b_re = self.to_re(scale2(x_b.clone()))
xp_a_re = self.to_re(scale2(xp_a.clone()))
xp_b_re = self.to_re(scale2(xp_b.clone()))
_, p_a, _ = self.id_a(x_a_re)
_, p_b, _ = self.id_a(x_b_re)
# encode the same ID different photo
_, pp_a, _ = self.id_a(xp_a_re)
_, pp_b, _ = self.id_a(xp_b_re)
# ID loss AND Tune the Generated image
weight_B = hyperparameters['teacher_w'] * hyperparameters['B_w']
self.loss_id = self.id_criterion(p_a[0], l_a) + self.id_criterion(p_b[0], l_b) \
+ weight_B * (self.id_criterion(p_a[1], l_a) + self.id_criterion(p_b[1], l_b))
self.loss_pid = self.id_criterion(pp_a[0], l_a) + self.id_criterion(pp_b[0],
l_b) # + weight_B * ( self.id_criterion(pp_a[1], l_a) + self.id_criterion(pp_b[1], l_b) )
self.loss_gen_recon_id = self.id_criterion(p_a_recon[0], l_a) + self.id_criterion(p_b_recon[0], l_b)
# print(f_a_recon, f_a)
self.loss_gen_cycrecon_x_a = self.recon_criterion(x_aba, x_a) if hyperparameters['recon_x_cyc_w'] > 0 else 0
self.loss_gen_cycrecon_x_b = self.recon_criterion(x_bab, x_b) if hyperparameters['recon_x_cyc_w'] > 0 else 0
# GAN loss
self.loss_gen_adv_a = self.dis_a.calc_gen_loss(x_ba)
self.loss_gen_adv_b = self.dis_a.calc_gen_loss(x_ab)
# domain-invariant perceptual loss
self.loss_gen_vgg_a = self.compute_vgg_loss(self.vgg, x_ba, x_b) if hyperparameters['vgg_w'] > 0 else 0
self.loss_gen_vgg_b = self.compute_vgg_loss(self.vgg, x_ab, x_a) if hyperparameters['vgg_w'] > 0 else 0
# ID domain adversarial loss
self.loss_gen_id_adv = 0.0
if iteration > hyperparameters['warm_iter']:
hyperparameters['recon_f_w'] += hyperparameters['warm_scale']
hyperparameters['recon_f_w'] = min(hyperparameters['recon_f_w'], hyperparameters['max_w'])
hyperparameters['recon_s_w'] += hyperparameters['warm_scale']
hyperparameters['recon_s_w'] = min(hyperparameters['recon_s_w'], hyperparameters['max_w'])
hyperparameters['recon_x_cyc_w'] += hyperparameters['warm_scale']
hyperparameters['recon_x_cyc_w'] = min(hyperparameters['recon_x_cyc_w'], hyperparameters['max_cyc_w'])
if iteration > hyperparameters['warm_teacher_iter']:
hyperparameters['teacher_w'] += hyperparameters['warm_scale']
hyperparameters['teacher_w'] = min(hyperparameters['teacher_w'], hyperparameters['max_teacher_w'])
# total loss
self.loss_gen_total = hyperparameters['gan_w'] * self.loss_gen_adv_a + \
hyperparameters['gan_w'] * self.loss_gen_adv_b + \
hyperparameters['recon_x_w'] * self.loss_gen_recon_x_a + \
hyperparameters['recon_xp_w'] * self.loss_gen_recon_xp_a + \
hyperparameters['recon_f_w'] * self.loss_gen_recon_f_a + \
hyperparameters['recon_s_w'] * self.loss_gen_recon_s_a + \
hyperparameters['recon_x_w'] * self.loss_gen_recon_x_b + \
hyperparameters['recon_xp_w'] * self.loss_gen_recon_xp_b + \
hyperparameters['recon_f_w'] * self.loss_gen_recon_f_b + \
hyperparameters['recon_s_w'] * self.loss_gen_recon_s_b + \
hyperparameters['recon_x_cyc_w'] * self.loss_gen_cycrecon_x_a + \
hyperparameters['recon_x_cyc_w'] * self.loss_gen_cycrecon_x_b + \
hyperparameters['id_w'] * self.loss_id + \
hyperparameters['pid_w'] * self.loss_pid + \
hyperparameters['recon_id_w'] * self.loss_gen_recon_id + \
hyperparameters['vgg_w'] * self.loss_gen_vgg_a + \
hyperparameters['vgg_w'] * self.loss_gen_vgg_b + \
hyperparameters['teacher_w'] * self.loss_teacher
self.loss_gen_total.backward()
self.gen_a_opt.step()
self.id_opt.step()
print(
"L_total: %.4f, L_gan: %.4f, L_adv: %.4f, Lx: %.4f, Lxp: %.4f, Lrecycle:%.4f, Lf: %.4f, Ls: %.4f, Recon-id: %.4f, id: %.4f, pid:%.4f, teacher: %.4f" % (
self.loss_gen_total, \
hyperparameters['gan_w'] * (self.loss_gen_adv_a + self.loss_gen_adv_b), \
hyperparameters['id_adv_w'] * (self.loss_gen_id_adv), \
hyperparameters['recon_x_w'] * (self.loss_gen_recon_x_a + self.loss_gen_recon_x_b), \
hyperparameters['recon_xp_w'] * (self.loss_gen_recon_xp_a + self.loss_gen_recon_xp_b), \
hyperparameters['recon_x_cyc_w'] * (self.loss_gen_cycrecon_x_a + self.loss_gen_cycrecon_x_b), \
hyperparameters['recon_f_w'] * (self.loss_gen_recon_f_a + self.loss_gen_recon_f_b), \
hyperparameters['recon_s_w'] * (self.loss_gen_recon_s_a + self.loss_gen_recon_s_b), \
hyperparameters['recon_id_w'] * self.loss_gen_recon_id, \
hyperparameters['id_w'] * self.loss_id, \
hyperparameters['pid_w'] * self.loss_pid, \
hyperparameters['teacher_w'] * self.loss_teacher))
def gen_update_bb(self, x_a, l_a, xp_a, x_b, l_b, xp_b, hyperparameters, iteration):
# ppa, ppb is the same person
self.gen_b_opt.zero_grad()
self.id_opt.zero_grad()
self.id_dis_opt.zero_grad()
# encode
s_a = self.gen_b.encode(self.single(x_a))
s_b = self.gen_b.encode(self.single(x_b))
f_a, p_a, fe_a = self.id_b(scale2(x_a))
f_b, p_b, fe_b = self.id_b(scale2(x_b))
# autodecode
x_a_recon = self.gen_b.decode(s_a, f_a)
x_b_recon = self.gen_b.decode(s_b, f_b)
# encode the same ID different photo
fp_a, pp_a, fe_pa = self.id_b(scale2(xp_a))
fp_b, pp_b, fe_pb = self.id_b(scale2(xp_b))
# decode the same person
x_a_recon_p = self.gen_b.decode(s_a, fp_a)
x_b_recon_p = self.gen_b.decode(s_b, fp_b)
# has gradient
x_ba = self.gen_b.decode(s_b, f_a)
x_ab = self.gen_b.decode(s_a, f_b)
# no gradient
x_ba_copy = Variable(x_ba.data, requires_grad=False)
x_ab_copy = Variable(x_ab.data, requires_grad=False)
rand_num = random.uniform(0, 1)
#################################
# encode structure
if hyperparameters['use_encoder_again'] >= rand_num:
# encode again (encoder is tuned, input is fixed)
s_a_recon = self.gen_b.enc_content(self.single(x_ab_copy))
s_b_recon = self.gen_b.enc_content(self.single(x_ba_copy))
else:
# copy the encoder
self.enc_content_copy = copy.deepcopy(self.gen_b.enc_content)
self.enc_content_copy = self.enc_content_copy.eval()
# encode again (encoder is fixed, input is tuned)
s_a_recon = self.enc_content_copy(self.single(x_ab))
s_b_recon = self.enc_content_copy(self.single(x_ba))
#################################
# encode appearance
self.id_a_copy = copy.deepcopy(self.id_b)
self.id_a_copy = self.id_a_copy.eval()
if hyperparameters['train_bn']:
self.id_a_copy = self.id_a_copy.apply(train_bn)
self.id_b_copy = self.id_a_copy
# encode again (encoder is fixed, input is tuned)
f_a_recon, p_a_recon, _ = self.id_a_copy(scale2(x_ba))
f_b_recon, p_b_recon, _ = self.id_b_copy(scale2(x_ab))
# teacher Loss
self.loss_teacher = 0.0
# decode again (if needed)
if hyperparameters['use_decoder_again']:
x_aba = self.gen_b.decode(s_a_recon, f_a_recon) if hyperparameters['recon_x_cyc_w'] > 0 else None
x_bab = self.gen_b.decode(s_b_recon, f_b_recon) if hyperparameters['recon_x_cyc_w'] > 0 else None
else:
self.mlp_w_copy = copy.deepcopy(self.gen_b.mlp_w)
self.mlp_b_copy = copy.deepcopy(self.gen_b.mlp_b)
self.dec_copy = copy.deepcopy(self.gen_b.dec) # Error
ID = f_a_recon
ID_Style = ID.view(ID.shape[0], ID.shape[1], 1, 1)
adain_params_w = self.mlp_w_copy(ID_Style)
adain_params_b = self.mlp_b_copy(ID_Style)
self.gen_b.assign_adain_params(adain_params_w, adain_params_b, self.dec_copy)
x_aba = self.dec_copy(s_a_recon) if hyperparameters['recon_x_cyc_w'] > 0 else None
ID = f_b_recon
ID_Style = ID.view(ID.shape[0], ID.shape[1], 1, 1)
adain_params_w = self.mlp_w_copy(ID_Style)
adain_params_b = self.mlp_b_copy(ID_Style)
self.gen_b.assign_adain_params(adain_params_w, adain_params_b, self.dec_copy)
x_bab = self.dec_copy(s_b_recon) if hyperparameters['recon_x_cyc_w'] > 0 else None
# auto-encoder image reconstruction
self.loss_gen_recon_x_a = self.recon_criterion(x_a_recon, x_a)
self.loss_gen_recon_x_b = self.recon_criterion(x_b_recon, x_b)
self.loss_gen_recon_xp_a = self.recon_criterion(x_a_recon_p, x_a)
self.loss_gen_recon_xp_b = self.recon_criterion(x_b_recon_p, x_b)
# feature reconstruction
self.loss_gen_recon_s_a = self.recon_criterion(s_a_recon, s_a) if hyperparameters['recon_s_w'] > 0 else 0
self.loss_gen_recon_s_b = self.recon_criterion(s_b_recon, s_b) if hyperparameters['recon_s_w'] > 0 else 0
self.loss_gen_recon_f_a = self.recon_criterion(f_a_recon, f_a) if hyperparameters['recon_f_w'] > 0 else 0
self.loss_gen_recon_f_b = self.recon_criterion(f_b_recon, f_b) if hyperparameters['recon_f_w'] > 0 else 0
# Random Erasing only effect the ID and PID loss.
if hyperparameters['erasing_p'] > 0:
x_a_re = self.to_re(scale2(x_a.clone()))
x_b_re = self.to_re(scale2(x_b.clone()))
xp_a_re = self.to_re(scale2(xp_a.clone()))
xp_b_re = self.to_re(scale2(xp_b.clone()))
_, p_a, _ = self.id_b(x_a_re)
_, p_b, _ = self.id_b(x_b_re)
# encode the same ID different photo
_, pp_a, _ = self.id_b(xp_a_re)
_, pp_b, _ = self.id_b(xp_b_re)
# ID loss AND Tune the Generated image
if hyperparameters['id_tgt']:
weight_B = hyperparameters['teacher_w'] * hyperparameters['B_w']
self.loss_id = self.id_criterion(p_a[0], l_a) + self.id_criterion(p_b[0], l_b) \
+ weight_B * (self.id_criterion(p_a[1], l_a) + self.id_criterion(p_b[1], l_b))
self.loss_pid = self.id_criterion(pp_a[0], l_a) + self.id_criterion(pp_b[0],
l_b) # + weight_B * ( self.id_criterion(pp_a[1], l_a) + self.id_criterion(pp_b[1], l_b) )
self.loss_pid *= self.loss_pid*hyperparameters['tgt_pos']
self.loss_gen_recon_id = self.id_criterion(p_a_recon[0], l_a) + self.id_criterion(p_b_recon[0], l_b)
else:
self.loss_id = 0.0
self.loss_pid = 0.0
self.loss_gen_recon_id = 0.0
# print(f_a_recon, f_a)
self.loss_gen_cycrecon_x_a = self.recon_criterion(x_aba, x_a) if hyperparameters['recon_x_cyc_w'] > 0 else 0
self.loss_gen_cycrecon_x_b = self.recon_criterion(x_bab, x_b) if hyperparameters['recon_x_cyc_w'] > 0 else 0
# GAN loss
self.loss_gen_adv_a = self.dis_a.calc_gen_loss(x_ba)
self.loss_gen_adv_b = self.dis_a.calc_gen_loss(x_ab)
# domain-invariant perceptual loss
self.loss_gen_vgg_a = self.compute_vgg_loss(self.vgg, x_ba, x_b) if hyperparameters['vgg_w'] > 0 else 0
self.loss_gen_vgg_b = self.compute_vgg_loss(self.vgg, x_ab, x_a) if hyperparameters['vgg_w'] > 0 else 0
# ID domain adversarial loss
self.loss_gen_id_adv = ( self.id_dis.calc_gen_loss(fe_b) + self.id_dis.calc_gen_loss(fe_a) ) / 2 if hyperparameters['id_adv_w'] > 0 else 0
if iteration > hyperparameters['warm_iter']:
hyperparameters['recon_f_w'] += hyperparameters['warm_scale']
hyperparameters['recon_f_w'] = min(hyperparameters['recon_f_w'], hyperparameters['max_w'])
hyperparameters['recon_s_w'] += hyperparameters['warm_scale']
hyperparameters['recon_s_w'] = min(hyperparameters['recon_s_w'], hyperparameters['max_w'])
hyperparameters['recon_x_cyc_w'] += hyperparameters['warm_scale']
hyperparameters['recon_x_cyc_w'] = min(hyperparameters['recon_x_cyc_w'], hyperparameters['max_cyc_w'])
if iteration > hyperparameters['warm_teacher_iter']:
hyperparameters['teacher_w'] += hyperparameters['warm_scale']
hyperparameters['teacher_w'] = min(hyperparameters['teacher_w'], hyperparameters['max_teacher_w'])
hyperparameters['id_adv_w'] += hyperparameters['adv_warm_scale']
hyperparameters['id_adv_w'] = min(hyperparameters['id_adv_w'], hyperparameters['id_adv_w_max'])
# total loss
self.loss_gen_total = hyperparameters['gan_w'] * self.loss_gen_adv_a + \
hyperparameters['gan_w'] * self.loss_gen_adv_b + \
hyperparameters['recon_x_w'] * self.loss_gen_recon_x_a + \
hyperparameters['recon_xp_w'] * hyperparameters['recon_xp_tgt_w'] * self.loss_gen_recon_xp_a + \
hyperparameters['recon_f_w'] * self.loss_gen_recon_f_a + \
hyperparameters['recon_s_w'] * self.loss_gen_recon_s_a + \
hyperparameters['recon_x_w'] * self.loss_gen_recon_x_b + \
hyperparameters['recon_xp_w'] * hyperparameters['recon_xp_tgt_w'] * self.loss_gen_recon_xp_b + \
hyperparameters['recon_f_w'] * self.loss_gen_recon_f_b + \
hyperparameters['recon_s_w'] * self.loss_gen_recon_s_b + \
hyperparameters['recon_x_cyc_w'] * self.loss_gen_cycrecon_x_a + \
hyperparameters['recon_x_cyc_w'] * self.loss_gen_cycrecon_x_b + \
hyperparameters['id_w'] * self.loss_id + \
hyperparameters['pid_w'] * self.loss_pid + \
hyperparameters['recon_id_w'] * self.loss_gen_recon_id + \
hyperparameters['vgg_w'] * self.loss_gen_vgg_a + \