-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathsolver.py
2052 lines (1783 loc) · 108 KB
/
solver.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
"""solver.py"""
import warnings
warnings.filterwarnings("ignore")
import os
from tqdm import tqdm
import visdom
import torch
import torch.optim as optim
import torch.nn.functional as F
from torch.autograd import Variable
from torchvision.utils import make_grid, save_image
from utils import cuda, grid2gif
from model_share import Generator_fc, Generator_fc_dsprites
from dataset import return_data
from PIL import Image
import torch.nn as nn
import functools
import networks
from torchvision import transforms
class Solver(object):
def __init__(self, args):
#GPU
self.use_cuda = args.cuda and torch.cuda.is_available()
#dataset and Z-space
if args.dataset.lower() == 'ilab_20m' or args.dataset.lower() == 'ilab_20m_custom':
self.nc = 3
self.z_dim = 100 #'dimension of the latent representation z'
# id: 0~60; back: 60~80; pose: 80~100
self.z_pose_dim = 20 # 'dimension of the pose latent representation in z'
self.z_back_dim = 20 # 'dimension of the background latent representation in z'
self.z_id_dim = self.z_dim - self.z_pose_dim - self.z_back_dim # 'dimension of the id latent representation in z'
elif args.dataset.lower() == 'fonts':
self.nc = 3
self.z_dim = 100 #'dimension of the latent representation z'
# content(letter): 0~20; size: 20~40; font_color: 40~60; back_color: 60~80; style(font): 20
self.z_content_dim = 20 # 'dimension of the z_content (letter) latent representation in z'
self.z_size_dim = 20 # 'dimension of the z_size latent representation in z'
self.z_font_color_dim = 20 # 'dimension of the z_font_color latent representation in z'
self.z_back_color_dim = 20 # 'dimension of the z_back_color latent representation in z'
self.z_style_dim = 20 # 'dimension of the z_style latent representation in z'
self.z_content_start_dim = 0
self.z_size_start_dim = 20
self.z_font_color_start_dim = 40
self.z_back_color_start_dim = 60
self.z_style_start_dim = 80
elif args.dataset.lower() == 'rafd':
self.nc = 3
self.z_dim = 100
self.z_pose_dim = 20
self.z_expression_dim = 20
self.z_id_dim = self.z_dim - self.z_pose_dim - self.z_expression_dim
elif args.dataset.lower() == 'dsprites':
self.decoder_dist = 'bernoulli'
self.nc = 1
self.z_dim = 10 # 'dimension of the latent representation z'
self.z_content_dim = 2 # 'dimension of the z_content (letter) latent representation in z'
self.z_size_dim = 2 # 'dimension of the z_size latent representation in z'
self.z_font_color_dim = 2 # 'dimension of the z_font_color latent representation in z'
self.z_back_color_dim = 2 # 'dimension of the z_back_color latent representation in z'
self.z_style_dim = 2 # 'dimension of the z_style latent representation in z'
self.z_content_start_dim = 0
self.z_size_start_dim = 2
self.z_font_color_start_dim = 4
self.z_back_color_start_dim = 6
self.z_style_start_dim = 8
else:
raise NotImplementedError
self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
self.dataset = args.dataset
if args.train: # train mode
self.train = True
else: # test mode
self.train = False
args.batch_size = 1
self.pretrain_model_path = args.pretrain_model_path
self.test_img_path = args.test_img_path
self.batch_size = args.batch_size
self.data_loader = return_data(args) ### key
# model training param
self.g_conv_dim = args.g_conv_dim
self.g_repeat_num = args.g_repeat_num
self.norm_layer = get_norm_layer(norm_type=args.norm)
self.max_iter = args.max_iter
self.lr = args.lr
self.beta1 = args.beta1
self.beta2 = args.beta2
self.lambda_combine = args.lambda_combine
self.lambda_unsup = args.lambda_unsup
if args.dataset.lower() == 'dsprites':
self.Autoencoder = Generator_fc_dsprites(self.nc, self.g_conv_dim, self.g_repeat_num, self.z_dim)
else:
self.Autoencoder = Generator_fc(self.nc, self.g_conv_dim, self.g_repeat_num, self.z_dim)
self.Autoencoder.to(self.device)
self.auto_optim = optim.Adam(self.Autoencoder.parameters(), lr=self.lr,
betas=(self.beta1, self.beta2))
# log and save
self.log_dir = './checkpoints/' + args.viz_name
self.model_save_dir = args.model_save_dir
self.viz_name = args.viz_name
self.viz_port = args.viz_port
self.viz_on = args.viz_on
self.win_recon = None
self.win_combine_sup = None
self.win_combine_unsup = None
self.gather_step = args.gather_step
self.gather = DataGather()
self.display_step = args.display_step
if self.viz_on:
self.viz = visdom.Visdom(port=self.viz_port)
self.resume_iters = args.resume_iters
self.ckpt_dir = os.path.join(args.ckpt_dir, args.viz_name)
if not os.path.exists(self.ckpt_dir):
os.makedirs(self.ckpt_dir, exist_ok=True)
self.save_step = args.save_step
self.save_output = args.save_output
self.output_dir = os.path.join(args.output_dir, args.viz_name)
if not os.path.exists(self.output_dir):
os.makedirs(self.output_dir, exist_ok=True)
def restore_model(self, resume_iters):
"""Restore the trained generator"""
if resume_iters == 'pretrained':
print('Loading the pretrained models from {}...'.format(self.pretrain_model_path))
self.Autoencoder.load_state_dict(torch.load(self.pretrain_model_path, map_location=lambda storage, loc: storage))
print("=> loaded checkpoint '{} '".format(self.pretrain_model_path))
else: # not test
print('Loading the trained models from step {}...'.format(resume_iters))
Auto_path = os.path.join(self.model_save_dir, self.viz_name, '{}-Auto.ckpt'.format(resume_iters))
self.Autoencoder.load_state_dict(torch.load(Auto_path, map_location=lambda storage, loc: storage))
print("=> loaded checkpoint '{} (iter {})'".format(self.viz_name, resume_iters))
# For ilab20M and ilab20m_custom dataset
def train_ilab20m(self):
# self.net_mode(train=True)
out = False
# Start training from scratch or resume training.
self.global_iter = 0
if self.resume_iters: # if resume the previous training
self.global_iter = self.resume_iters
self.restore_model(self.resume_iters)
pbar = tqdm(total=self.max_iter)
pbar.update(self.global_iter) # update the current iter if we resume training
while not out:
for sup_package in self.data_loader:
# id, back, pose: 60, 20, 20
A_img = sup_package['A']
B_img = sup_package['B']
C_img = sup_package['C']
D_img = sup_package['D']
self.global_iter += 1
pbar.update(1)
A_img = Variable(cuda(A_img, self.use_cuda))
B_img = Variable(cuda(B_img, self.use_cuda))
C_img = Variable(cuda(C_img, self.use_cuda))
D_img = Variable(cuda(D_img, self.use_cuda))
## 1. A B C seperate(first400: id last600 background)
A_recon, A_z = self.Autoencoder(A_img)
B_recon, B_z = self.Autoencoder(B_img)
C_recon, C_z = self.Autoencoder(C_img)
D_recon, D_z = self.Autoencoder(D_img)
A_z_id = A_z[:, 0:self.z_id_dim] # 0-60
A_z_back = A_z[:, self.z_id_dim:self.z_id_dim + self.z_back_dim] # 60-80
A_z_pose = A_z[:, self.z_id_dim + self.z_back_dim:] #80-100
B_z_id = B_z[:, 0:self.z_id_dim]
B_z_back = B_z[:, self.z_id_dim:self.z_id_dim + self.z_back_dim]
B_z_pose = B_z[:, self.z_id_dim + self.z_back_dim:]
C_z_id = C_z[:, 0:self.z_id_dim]
C_z_back = C_z[:, self.z_id_dim:self.z_id_dim + self.z_back_dim]
C_z_pose = C_z[:, self.z_id_dim + self.z_back_dim:]
D_z_id = D_z[:, 0:self.z_id_dim]
D_z_back = D_z[:, self.z_id_dim:self.z_id_dim + self.z_back_dim]
D_z_pose = D_z[:, self.z_id_dim + self.z_back_dim:]
## 2. combine with strong supervise
# C A same pose diff id, back
ApCo_combine_2C = torch.cat((C_z_id, C_z_back), dim=1)
ApCo_combine_2C = torch.cat((ApCo_combine_2C, A_z_pose), dim=1)
mid_ApCo = self.Autoencoder.fc_decoder(ApCo_combine_2C)
mid_ApCo = mid_ApCo.view(ApCo_combine_2C.shape[0], 256, 8, 8)
ApCo_2C = self.Autoencoder.decoder(mid_ApCo)
AoCp_combine_2A = torch.cat((A_z_id, A_z_back), dim=1)
AoCp_combine_2A = torch.cat((AoCp_combine_2A, C_z_pose), dim=1)
mid_AoCp = self.Autoencoder.fc_decoder(AoCp_combine_2A)
mid_AoCp = mid_AoCp.view(AoCp_combine_2A.shape[0], 256, 8, 8)
AoCp_2A = self.Autoencoder.decoder(mid_AoCp)
# C B same id diff pose, back
BaCo_combine_2C = torch.cat((B_z_id, C_z_back), dim=1)
BaCo_combine_2C = torch.cat((BaCo_combine_2C, C_z_pose), dim=1)
mid_BaCo = self.Autoencoder.fc_decoder(BaCo_combine_2C)
mid_BaCo = mid_BaCo.view(BaCo_combine_2C.shape[0], 256, 8, 8)
BaCo_2C = self.Autoencoder.decoder(mid_BaCo)
BoCa_combine_2B = torch.cat((C_z_id, B_z_back), dim=1)
BoCa_combine_2B = torch.cat((BoCa_combine_2B, B_z_pose), dim=1)
mid_BoCa = self.Autoencoder.fc_decoder(BoCa_combine_2B)
mid_BoCa = mid_BoCa.view(BoCa_combine_2B.shape[0], 256, 8, 8)
BoCa_2B = self.Autoencoder.decoder(mid_BoCa)
# C D same background diff id, pose
DbCo_combine_2C = torch.cat((C_z_id, D_z_back), dim=1)
DbCo_combine_2C = torch.cat((DbCo_combine_2C, C_z_pose), dim=1)
mid_DbCo = self.Autoencoder.fc_decoder(DbCo_combine_2C)
mid_DbCo = mid_DbCo.view(DbCo_combine_2C.shape[0], 256, 8, 8)
DbCo_2C = self.Autoencoder.decoder(mid_DbCo)
DoCb_combine_2D = torch.cat((D_z_id, C_z_back), dim=1)
DoCb_combine_2D = torch.cat((DoCb_combine_2D, D_z_pose), dim=1)
mid_DoCb = self.Autoencoder.fc_decoder(DoCb_combine_2D)
mid_DoCb = mid_DoCb.view(DoCb_combine_2D.shape[0], 256, 8, 8)
DoCb_2D = self.Autoencoder.decoder(mid_DoCb)
# combine_2C
ApBaDb_combine_2C = torch.cat((B_z_id, D_z_back), dim=1)
ApBaDb_combine_2C = torch.cat((ApBaDb_combine_2C, A_z_pose), dim=1)
mid_ApBaDb = self.Autoencoder.fc_decoder(ApBaDb_combine_2C)
mid_ApBaDb = mid_ApBaDb.view(ApBaDb_combine_2C.shape[0], 256, 8, 8)
ApBaDb_2C = self.Autoencoder.decoder(mid_ApBaDb)
# ''' need unsupervise '''
AaBpDb_combine_2N = torch.cat((A_z_id, D_z_back), dim=1)
AaBpDb_combine_2N = torch.cat((AaBpDb_combine_2N, B_z_pose), dim=1)
mid_AaBpDb = self.Autoencoder.fc_decoder(AaBpDb_combine_2N)
mid_AaBpDb = mid_AaBpDb.view(AaBpDb_combine_2N.shape[0], 256, 8, 8)
AaBpDb_2N = self.Autoencoder.decoder(mid_AaBpDb)
'''
optimize for autoencoder
'''
# 1. recon_loss
A_recon_loss = torch.mean(torch.abs(A_img - A_recon))
B_recon_loss = torch.mean(torch.abs(B_img - B_recon))
C_recon_loss = torch.mean(torch.abs(C_img - C_recon))
D_recon_loss = torch.mean(torch.abs(D_img - D_recon))
recon_loss = A_recon_loss + B_recon_loss + C_recon_loss + D_recon_loss
# 2. sup_combine_loss
ApCo_2C_loss = torch.mean(torch.abs(C_img - ApCo_2C))
AoCp_2A_loss = torch.mean(torch.abs(A_img - AoCp_2A))
BaCo_2C_loss = torch.mean(torch.abs(C_img - BaCo_2C))
BoCa_2B_loss = torch.mean(torch.abs(B_img - BoCa_2B))
DbCo_2C_loss = torch.mean(torch.abs(C_img - DbCo_2C))
DoCb_2D_loss = torch.mean(torch.abs(D_img - DoCb_2D))
ApBaDb_2C_loss = torch.mean(torch.abs(C_img - ApBaDb_2C))
combine_sup_loss = ApCo_2C_loss + AoCp_2A_loss + BaCo_2C_loss + BoCa_2B_loss + DbCo_2C_loss + DoCb_2D_loss + ApBaDb_2C_loss
# 3. unsup_combine_loss
_, AaBpDb_z = self.Autoencoder(AaBpDb_2N)
combine_unsup_loss = torch.mean(torch.abs(A_z_id - AaBpDb_z[:, 0:self.z_id_dim])) + \
torch.mean(torch.abs(D_z_back - AaBpDb_z[:, self.z_id_dim:self.z_id_dim + self.z_back_dim])) + \
torch.mean(torch.abs(B_z_pose - AaBpDb_z[:, self.z_id_dim + self.z_back_dim:]))
# Whole loss
vae_unsup_loss = recon_loss + self.lambda_combine * combine_sup_loss + self.lambda_unsup * combine_unsup_loss
self.auto_optim.zero_grad()
vae_unsup_loss.backward()
self.auto_optim.step()
# save the log
f = open(self.log_dir + '/log.txt', 'a')
f.writelines(['\n', '[{}] recon_loss:{:.3f} combine_sup_loss:{:.3f} combine_unsup_loss:{:.3f}'.format(
self.global_iter, recon_loss.data, combine_sup_loss.data, combine_unsup_loss.data)])
f.close()
if self.viz_on and self.global_iter%self.gather_step == 0: # gather loss information
self.gather.insert(iter=self.global_iter,recon_loss=recon_loss.data,
combine_sup_loss=combine_sup_loss.data, combine_unsup_loss=combine_unsup_loss.data)
if self.global_iter%self.display_step == 0:
pbar.write('[{}] recon_loss:{:.3f} combine_sup_loss:{:.3f} combine_unsup_loss:{:.3f}'.format(
self.global_iter, recon_loss.data, combine_sup_loss.data, combine_unsup_loss.data))
if self.viz_on:
self.gather.insert(images=A_img.data)
self.gather.insert(images=B_img.data)
self.gather.insert(images=C_img.data)
self.gather.insert(images=D_img.data)
self.gather.insert(images=F.sigmoid(A_recon).data)
self.ilab20m_viz_reconstruction()
self.viz_lines()
'''
combine show
'''
self.gather.insert(combine_supimages=F.sigmoid(AoCp_2A).data)
self.gather.insert(combine_supimages=F.sigmoid(BoCa_2B).data)
self.gather.insert(combine_supimages=F.sigmoid(DbCo_2C).data)
self.gather.insert(combine_supimages=F.sigmoid(DoCb_2D).data)
self.ilab20m_viz_combine_recon()
self.gather.insert(combine_unsupimages=F.sigmoid(ApBaDb_2C).data)
self.gather.insert(combine_unsupimages=F.sigmoid(AaBpDb_2N).data)
self.ilab20m_viz_combine_unsuprecon()
self.gather.flush()
# Save model checkpoints.
if self.global_iter%self.save_step == 0:
Auto_path = os.path.join(self.model_save_dir, self.viz_name, '{}-Auto.ckpt'.format(self.global_iter))
torch.save(self.Autoencoder.state_dict(), Auto_path)
print('Saved model checkpoints into {}/{}...'.format(self.model_save_dir, self.viz_name))
if self.global_iter >= self.max_iter:
out = True
break
pbar.write("[Training Finished]")
pbar.close()
def train_ilab20m_custom(self):
# self.net_mode(train=True)
out = False
# Start training from scratch or resume training.
self.global_iter = 0
if self.resume_iters:
self.global_iter = self.resume_iters
self.restore_model(self.resume_iters)
pbar = tqdm(total=self.max_iter)
pbar.update(self.global_iter)
while not out:
for sup_package in self.data_loader:
if self.global_iter == 121:
print(121)
# appe, pose, combine
A_img = sup_package['A']
B_img = sup_package['B']
C_img = sup_package['C']
D_img = sup_package['D']
C_img1 = sup_package['C1']
C_img2 = sup_package['C2']
self.global_iter += 1
pbar.update(1)
A_img = Variable(cuda(A_img, self.use_cuda))
B_img = Variable(cuda(B_img, self.use_cuda))
C_img = Variable(cuda(C_img, self.use_cuda))
D_img = Variable(cuda(D_img, self.use_cuda))
C_img1 = Variable(cuda(C_img1, self.use_cuda))
C_img2 = Variable(cuda(C_img2, self.use_cuda))
## 1. A B C seperate(first400: id last600 background)
A_recon, A_z = self.Autoencoder(A_img)
B_recon, B_z = self.Autoencoder(B_img)
C_recon, C_z = self.Autoencoder(C_img)
D_recon, D_z = self.Autoencoder(D_img)
C_recon1, C_z1 = self.Autoencoder(C_img1)
C_recon2, C_z2 = self.Autoencoder(C_img2)
A_z_appe = A_z[:, 0:self.z_id_dim] # 0-700
A_z_back = A_z[:, self.z_id_dim:self.z_id_dim + self.z_back_dim] # 700-800
A_z_pose = A_z[:, self.z_id_dim + self.z_back_dim:] #800-1000
B_z_appe = B_z[:, 0:self.z_id_dim]
B_z_back = B_z[:, self.z_id_dim:self.z_id_dim + self.z_back_dim]
B_z_pose = B_z[:, self.z_id_dim + self.z_back_dim:]
C_z_appe = C_z[:, 0:self.z_id_dim]
C_z_back = C_z[:, self.z_id_dim:self.z_id_dim + self.z_back_dim]
C_z_pose = C_z[:, self.z_id_dim + self.z_back_dim:]
D_z_appe = D_z[:, 0:self.z_id_dim]
D_z_back = D_z[:, self.z_id_dim:self.z_id_dim + self.z_back_dim]
D_z_pose = D_z[:, self.z_id_dim + self.z_back_dim:]
C_z_appe1 = C_z1[:, 0:self.z_id_dim]
C_z_back1 = C_z1[:, self.z_id_dim:self.z_id_dim + self.z_back_dim]
C_z_pose1 = C_z1[:, self.z_id_dim + self.z_back_dim:]
C_z_appe2 = C_z2[:, 0:self.z_id_dim]
C_z_back2 = C_z2[:, self.z_id_dim:self.z_id_dim + self.z_back_dim]
C_z_pose2 = C_z2[:, self.z_id_dim + self.z_back_dim:]
## 2. combine with strong supervise
# C A same pose diff id, back
ApCo_combine_2C = torch.cat((C_z_appe1, C_z_back1), dim=1)
ApCo_combine_2C = torch.cat((ApCo_combine_2C, A_z_pose), dim=1)
mid_ApCo = self.Autoencoder.fc_decoder(ApCo_combine_2C)
mid_ApCo = mid_ApCo.view(ApCo_combine_2C.shape[0], 256, 8, 8)
ApCo_2C = self.Autoencoder.decoder(mid_ApCo)
AoCp_combine_2A = torch.cat((A_z_appe, A_z_back), dim=1)
AoCp_combine_2A = torch.cat((AoCp_combine_2A, C_z_pose1), dim=1)
mid_AoCp = self.Autoencoder.fc_decoder(AoCp_combine_2A)
mid_AoCp = mid_AoCp.view(AoCp_combine_2A.shape[0], 256, 8, 8)
AoCp_2A = self.Autoencoder.decoder(mid_AoCp)
# C B same id diff pose, back
BaCo_combine_2C = torch.cat((B_z_appe, C_z_back), dim=1)
BaCo_combine_2C = torch.cat((BaCo_combine_2C, C_z_pose), dim=1)
mid_BaCo = self.Autoencoder.fc_decoder(BaCo_combine_2C)
mid_BaCo = mid_BaCo.view(BaCo_combine_2C.shape[0], 256, 8, 8)
BaCo_2C = self.Autoencoder.decoder(mid_BaCo)
BoCa_combine_2B = torch.cat((C_z_appe, B_z_back), dim=1)
BoCa_combine_2B = torch.cat((BoCa_combine_2B, B_z_pose), dim=1)
mid_BoCa = self.Autoencoder.fc_decoder(BoCa_combine_2B)
mid_BoCa = mid_BoCa.view(BoCa_combine_2B.shape[0], 256, 8, 8)
BoCa_2B = self.Autoencoder.decoder(mid_BoCa)
# C D same background diff id, pose
DbCo_combine_2C = torch.cat((C_z_appe2, D_z_back), dim=1)
DbCo_combine_2C = torch.cat((DbCo_combine_2C, C_z_pose2), dim=1)
mid_DbCo = self.Autoencoder.fc_decoder(DbCo_combine_2C)
mid_DbCo = mid_DbCo.view(DbCo_combine_2C.shape[0], 256, 8, 8)
DbCo_2C = self.Autoencoder.decoder(mid_DbCo)
DoCb_combine_2D = torch.cat((D_z_appe, C_z_back2), dim=1)
DoCb_combine_2D = torch.cat((DoCb_combine_2D, D_z_pose), dim=1)
mid_DoCb = self.Autoencoder.fc_decoder(DoCb_combine_2D)
mid_DoCb = mid_DoCb.view(DoCb_combine_2D.shape[0], 256, 8, 8)
DoCb_2D = self.Autoencoder.decoder(mid_DoCb)
# combine_2C
ApBaDb_combine_2C = torch.cat((B_z_appe, D_z_back), dim=1)
ApBaDb_combine_2C = torch.cat((ApBaDb_combine_2C, A_z_pose), dim=1)
mid_ApBaDb = self.Autoencoder.fc_decoder(ApBaDb_combine_2C)
mid_ApBaDb = mid_ApBaDb.view(ApBaDb_combine_2C.shape[0], 256, 8, 8)
ApBaDb_2C = self.Autoencoder.decoder(mid_ApBaDb)
# ''' need unsupervise '''
AaBpDb_combine_2N = torch.cat((A_z_appe, D_z_back), dim=1)
AaBpDb_combine_2N = torch.cat((AaBpDb_combine_2N, B_z_pose), dim=1)
mid_AaBpDb = self.Autoencoder.fc_decoder(AaBpDb_combine_2N)
mid_AaBpDb = mid_AaBpDb.view(AaBpDb_combine_2N.shape[0], 256, 8, 8)
AaBpDb_2N = self.Autoencoder.decoder(mid_AaBpDb)
# ''' need unsupervise '''
# AaBp_combine_2N = torch.cat((A_z_appe, C_z_back), dim=1)
# AaBp_combine_2N = torch.cat((AaBp_combine_2N, B_z_pose), dim=1)
# mid_AaBp = self.Autoencoder.fc_decoder(AaBp_combine_2N)
# mid_AaBp = mid_AaBp.view(AaBp_combine_2N.shape[0], 256, 8, 8)
# AaBp_2N = self.Autoencoder.decoder(mid_AaBp)
'''
optimize for autoencoder
'''
# 1. recon_loss
A_recon_loss = torch.mean(torch.abs(A_img - A_recon))
B_recon_loss = torch.mean(torch.abs(B_img - B_recon))
C_recon_loss = torch.mean(torch.abs(C_img - C_recon))
D_recon_loss = torch.mean(torch.abs(D_img - D_recon))
recon_loss = A_recon_loss + B_recon_loss + C_recon_loss + D_recon_loss
# 2. sup_combine_loss
ApCo_2C_loss = torch.mean(torch.abs(C_img1 - ApCo_2C))
AoCp_2A_loss = torch.mean(torch.abs(A_img - AoCp_2A))
BaCo_2C_loss = torch.mean(torch.abs(C_img - BaCo_2C))
BoCa_2B_loss = torch.mean(torch.abs(B_img - BoCa_2B))
DbCo_2C_loss = torch.mean(torch.abs(C_img2 - DbCo_2C))
DoCb_2D_loss = torch.mean(torch.abs(D_img - DoCb_2D))
ApBaDb_2C_loss = torch.mean(torch.abs(C_img - ApBaDb_2C))
combine_sup_loss = ApCo_2C_loss + AoCp_2A_loss + BaCo_2C_loss + BoCa_2B_loss + DbCo_2C_loss + DoCb_2D_loss #+ ApBaDb_2C_loss
# 3. unsup_combine_loss
_, AaBpDb_z = self.Autoencoder(AaBpDb_2N)
combine_unsup_loss = torch.mean(torch.abs(A_z_appe - AaBpDb_z[:, 0:self.z_id_dim])) + torch.mean(torch.abs(D_z_back - AaBpDb_z[:, self.z_id_dim:self.z_id_dim + self.z_back_dim])) + torch.mean(torch.abs(B_z_pose - AaBpDb_z[:, self.z_id_dim + self.z_back_dim:]))
# whole loss
vae_unsup_loss = recon_loss + self.lambda_combine * combine_sup_loss + self.lambda_unsup * combine_unsup_loss
self.auto_optim.zero_grad()
vae_unsup_loss.backward()
self.auto_optim.step()
# save the log
f = open(self.log_dir + '/log.txt', 'a')
f.writelines(['\n', '[{}] recon_loss:{:.3f} combine_sup_loss:{:.3f} combine_unsup_loss:{:.3f}'.format(
self.global_iter, recon_loss.data, combine_sup_loss.data, combine_unsup_loss.data)])
f.close()
print(['\n', '[{}] recon_loss:{:.3f} combine_sup_loss:{:.3f} combine_unsup_loss:{:.3f}'.format(
self.global_iter, recon_loss.data, combine_sup_loss.data, combine_unsup_loss.data)])
if self.viz_on and self.global_iter%self.gather_step == 0:
self.gather.insert(iter=self.global_iter,recon_loss=recon_loss.data,
combine_sup_loss=combine_sup_loss.data, combine_unsup_loss=combine_unsup_loss.data)
if self.global_iter%self.display_step == 0:
pbar.write('[{}] recon_loss:{:.3f} combine_sup_loss:{:.3f} combine_unsup_loss:{:.3f}'.format(
self.global_iter, recon_loss.data, combine_sup_loss.data, combine_unsup_loss.data))
if self.viz_on:
self.gather.insert(images=A_img.data)
self.gather.insert(images=B_img.data)
self.gather.insert(images=C_img.data)
self.gather.insert(images=D_img.data)
self.gather.insert(images=F.sigmoid(A_recon).data)
self.ilab20m_viz_reconstruction()
self.viz_lines()
'''
combine show
'''
self.gather.insert(combine_supimages=F.sigmoid(AoCp_2A).data)
self.gather.insert(combine_supimages=F.sigmoid(BoCa_2B).data)
self.gather.insert(combine_supimages=F.sigmoid(DbCo_2C).data)
self.gather.insert(combine_supimages=F.sigmoid(DoCb_2D).data)
self.ilab20m_viz_combine_recon()
self.gather.insert(combine_unsupimages=F.sigmoid(ApBaDb_2C).data)
self.gather.insert(combine_unsupimages=F.sigmoid(AaBpDb_2N).data)
self.ilab20m_viz_combine_unsuprecon()
# self.viz_combine(x)
self.gather.flush()
# Save model checkpoints.
if self.global_iter%self.save_step == 0:
Auto_path = os.path.join(self.model_save_dir, self.viz_name, '{}-Auto.ckpt'.format(self.global_iter))
torch.save(self.Autoencoder.state_dict(), Auto_path)
print('Saved model checkpoints into {}/{}...'.format(self.model_save_dir, self.viz_name))
if self.global_iter >= self.max_iter:
out = True
break
pbar.write("[Training Finished]")
pbar.close()
def test_ilab20m(self):
# self.net_mode(train=False)
# load pretrained model
self.restore_model('pretrained')
for index, sup_package in enumerate(self.data_loader):
# id, back, pose
A_img = sup_package['A']
B_img = sup_package['B']
D_img = sup_package['D']
A_img = Variable(cuda(A_img, self.use_cuda))
B_img = Variable(cuda(B_img, self.use_cuda))
D_img = Variable(cuda(D_img, self.use_cuda))
## 1. get latent
A_recon, A_z = self.Autoencoder(A_img)
B_recon, B_z = self.Autoencoder(B_img)
D_recon, D_z = self.Autoencoder(D_img)
A_z_id = A_z[:, 0:self.z_id_dim] # 0-60
D_z_back = D_z[:, self.z_id_dim:self.z_id_dim + self.z_back_dim] # 60-80
B_z_pose = B_z[:, self.z_id_dim + self.z_back_dim:] # 80-100
## 2. combine for target
AaBpDb_combine_2N = torch.cat((A_z_id, D_z_back, B_z_pose), dim=1)
# AaBpDb_combine_2N = torch.cat((AaBpDb_combine_2N, B_z_pose), dim=1)
mid_AaBpDb = self.Autoencoder.fc_decoder(AaBpDb_combine_2N)
mid_AaBpDb = mid_AaBpDb.view(AaBpDb_combine_2N.shape[0], 256, 8, 8)
AaBpDb_2N = self.Autoencoder.decoder(mid_AaBpDb)
# save synthesized image
self.test_iter = index
self.gather.insert(test=F.sigmoid(AaBpDb_2N).data)
self.ilab20m_viz_test()
self.gather.flush()
def ilab20m_save_sample_img(self, tensor, mode):
unloader = transforms.ToPILImage()
dir = os.path.join(self.model_save_dir, self.viz_name, 'sample_img')
if not os.path.exists(dir):
os.makedirs(dir)
image = tensor.cpu().clone() # we clone the tensor to not do changes on it
if mode == 'recon':
image_ori_A = image[0].squeeze(0) # remove the fake batch dimension
image_ori_B = image[1].squeeze(0)
image_ori_C = image[2].squeeze(0)
image_ori_D = image[3].squeeze(0)
image_recon = image[4].squeeze(0)
image_ori_A = unloader(image_ori_A)
image_ori_B = unloader(image_ori_B)
image_ori_C = unloader(image_ori_C)
image_ori_D = unloader(image_ori_D)
image_recon = unloader(image_recon)
image_ori_A.save(os.path.join(dir, '{}-A_img.png'.format(self.global_iter)))
image_ori_B.save(os.path.join(dir, '{}-B_img.png'.format(self.global_iter)))
image_ori_C.save(os.path.join(dir, '{}-C_img.png'.format(self.global_iter)))
image_ori_D.save(os.path.join(dir, '{}-D_img.png'.format(self.global_iter)))
image_recon.save(os.path.join(dir, '{}-A_img_recon.png'.format(self.global_iter)))
elif mode == 'combine_sup':
image_AoCp_2A = image[0].squeeze(0) # remove the fake batch dimension
image_BoCa_2B = image[1].squeeze(0)
image_DbCo_2C = image[2].squeeze(0)
image_DoCb_2D = image[3].squeeze(0)
image_AoCp_2A = unloader(image_AoCp_2A)
image_BoCa_2B = unloader(image_BoCa_2B)
image_DbCo_2C = unloader(image_DbCo_2C)
image_DoCb_2D = unloader(image_DoCb_2D)
image_AoCp_2A.save(os.path.join(dir, '{}-AoCp_2A.png'.format(self.global_iter)))
image_BoCa_2B.save(os.path.join(dir, '{}-BoCa_2B.png'.format(self.global_iter)))
image_DbCo_2C.save(os.path.join(dir, '{}-DbCo_2C.png'.format(self.global_iter)))
image_DoCb_2D.save(os.path.join(dir, '{}-DoCb_2D.png'.format(self.global_iter)))
elif mode == 'combine_unsup':
image_ApBaDb_2C = image[0].squeeze(0) # remove the fake batch dimension
image_AaBpDb_2N = image[1].squeeze(0)
image_ApBaDb_2C = unloader(image_ApBaDb_2C)
image_AaBpDb_2N = unloader(image_AaBpDb_2N)
image_ApBaDb_2C.save(os.path.join(dir, '{}-ApBaDb_2C.png'.format(self.global_iter)))
image_AaBpDb_2N.save(os.path.join(dir, '{}-AaBpDb_2N.png'.format(self.global_iter)))
elif mode == 'test':
image_AaBpDb_2N = image
image_AaBpDb_2N = unloader(image_AaBpDb_2N)
image_AaBpDb_2N.save(os.path.join(self.output_dir, 'group{}-AaBpDb_2N.png'.format(self.test_iter +1)))
def ilab20m_viz_reconstruction(self):
# self.net_mode(train=False)
x_A = self.gather.data['images'][0][:100]
x_A = make_grid(x_A, normalize=True)
x_B = self.gather.data['images'][1][:100]
x_B = make_grid(x_B, normalize=True)
x_C = self.gather.data['images'][2][:100]
x_C = make_grid(x_C, normalize=True)
x_D = self.gather.data['images'][3][:100]
x_D = make_grid(x_D, normalize=True)
x_A_recon = self.gather.data['images'][4][:100]
x_A_recon = make_grid(x_A_recon, normalize=True)
images = torch.stack([x_A, x_B, x_C, x_D, x_A_recon], dim=0).cpu()
self.viz.images(images, env=self.viz_name+'_reconstruction',
opts=dict(title=str(self.global_iter)), nrow=10)
self.ilab20m_save_sample_img(images, 'recon')
# self.net_mode(train=True)
def ilab20m_viz_combine_recon(self):
# self.net_mode(train=False)
AoCp_2A = self.gather.data['combine_supimages'][0][:100]
AoCp_2A = make_grid(AoCp_2A, normalize=True)
BoCa_2B = self.gather.data['combine_supimages'][1][:100]
BoCa_2B = make_grid(BoCa_2B, normalize=True)
DbCo_2C = self.gather.data['combine_supimages'][2][:100]
DbCo_2C = make_grid(DbCo_2C, normalize=True)
DoCb_2D = self.gather.data['combine_supimages'][3][:100]
DoCb_2D = make_grid(DoCb_2D, normalize=True)
images = torch.stack([AoCp_2A, BoCa_2B, DbCo_2C, DoCb_2D], dim=0).cpu()
self.viz.images(images, env=self.viz_name+'combine_supimages',
opts=dict(title=str(self.global_iter)), nrow=10)
self.ilab20m_save_sample_img(images, 'combine_sup')
def ilab20m_viz_combine_unsuprecon(self):
# self.net_mode(train=False)
ApBaDb_2C = self.gather.data['combine_unsupimages'][0][:100]
ApBaDb_2C = make_grid(ApBaDb_2C, normalize=True)
AaBpDb_2N = self.gather.data['combine_unsupimages'][1][:100]
AaBpDb_2N = make_grid(AaBpDb_2N, normalize=True)
images = torch.stack([ApBaDb_2C, AaBpDb_2N], dim=0).cpu()
self.viz.images(images, env=self.viz_name+'combine_unsupimages',
opts=dict(title=str(self.global_iter)), nrow=10)
self.ilab20m_save_sample_img(images, 'combine_unsup')
def ilab20m_viz_test(self):
# self.net_mode(train=False)
AaBpDb_2N = self.gather.data['test'][0][:100]
AaBpDb_2N = make_grid(AaBpDb_2N, normalize=True)
images = AaBpDb_2N
self.ilab20m_save_sample_img(images, 'test')
# For Fonts dataset
def train_fonts(self):
# self.net_mode(train=True)
out = False
# Start training from scratch or resume training.
self.global_iter = 0
if self.resume_iters:
self.global_iter = self.resume_iters
self.restore_model(self.resume_iters)
pbar = tqdm(total=self.max_iter)
pbar.update(self.global_iter)
while not out:
for sup_package in self.data_loader:
A_img = sup_package['A']
B_img = sup_package['B']
C_img = sup_package['C']
D_img = sup_package['D']
E_img = sup_package['E']
F_img = sup_package['F']
self.global_iter += 1
pbar.update(1)
A_img = Variable(cuda(A_img, self.use_cuda))
B_img = Variable(cuda(B_img, self.use_cuda))
C_img = Variable(cuda(C_img, self.use_cuda))
D_img = Variable(cuda(D_img, self.use_cuda))
E_img = Variable(cuda(E_img, self.use_cuda))
F_img = Variable(cuda(F_img, self.use_cuda))
## 1. A B C seperate(first400: id last600 background)
A_recon, A_z = self.Autoencoder(A_img)
B_recon, B_z = self.Autoencoder(B_img)
C_recon, C_z = self.Autoencoder(C_img)
D_recon, D_z = self.Autoencoder(D_img)
E_recon, E_z = self.Autoencoder(E_img)
F_recon, F_z = self.Autoencoder(F_img)
''' refer 1: content, 2: size, 3: font-color, 4 back_color, 5 style'''
A_z_1 = A_z[:, 0:self.z_size_start_dim] # 0-20
A_z_2 = A_z[:, self.z_size_start_dim: self.z_font_color_start_dim] # 20-40
A_z_3 = A_z[:, self.z_font_color_start_dim: self.z_back_color_start_dim] # 40-60
A_z_4 = A_z[:, self.z_back_color_start_dim: self.z_style_start_dim] # 60-80
A_z_5 = A_z[:, self.z_style_start_dim:] # 80-100
B_z_1 = B_z[:, 0:self.z_size_start_dim] # 0-20
B_z_2 = B_z[:, self.z_size_start_dim: self.z_font_color_start_dim] # 20-40
B_z_3 = B_z[:, self.z_font_color_start_dim: self.z_back_color_start_dim] # 40-60
B_z_4 = B_z[:, self.z_back_color_start_dim: self.z_style_start_dim] # 60-80
B_z_5 = B_z[:, self.z_style_start_dim:] # 80-100
C_z_1 = C_z[:, 0:self.z_size_start_dim] # 0-20
C_z_2 = C_z[:, self.z_size_start_dim: self.z_font_color_start_dim] # 20-40
C_z_3 = C_z[:, self.z_font_color_start_dim: self.z_back_color_start_dim] # 40-60
C_z_4 = C_z[:, self.z_back_color_start_dim: self.z_style_start_dim] # 60-80
C_z_5 = C_z[:, self.z_style_start_dim:] # 80-100
D_z_1 = D_z[:, 0:self.z_size_start_dim] # 0-20
D_z_2 = D_z[:, self.z_size_start_dim: self.z_font_color_start_dim] # 20-40
D_z_3 = D_z[:, self.z_font_color_start_dim: self.z_back_color_start_dim] # 40-60
D_z_4 = D_z[:, self.z_back_color_start_dim: self.z_style_start_dim] # 60-80
D_z_5 = D_z[:, self.z_style_start_dim:] # 80-100
E_z_1 = E_z[:, 0:self.z_size_start_dim] # 0-20
E_z_2 = E_z[:, self.z_size_start_dim: self.z_font_color_start_dim] # 20-40
E_z_3 = E_z[:, self.z_font_color_start_dim: self.z_back_color_start_dim] # 40-60
E_z_4 = E_z[:, self.z_back_color_start_dim: self.z_style_start_dim] # 60-80
E_z_5 = E_z[:, self.z_style_start_dim:] # 80-100
F_z_1 = F_z[:, 0:self.z_size_start_dim] # 0-20
F_z_2 = F_z[:, self.z_size_start_dim: self.z_font_color_start_dim] # 20-40
F_z_3 = F_z[:, self.z_font_color_start_dim: self.z_back_color_start_dim] # 40-60
F_z_4 = F_z[:, self.z_back_color_start_dim: self.z_style_start_dim] # 60-80
F_z_5 = F_z[:, self.z_style_start_dim:] # 80-100
## 2. combine with strong supervise
''' refer 1: content, 2: size, 3: font-color, 4 back_color, 5 style'''
# C A same content 1
A1Co_combine_2C = torch.cat((A_z_1, C_z_2, C_z_3, C_z_4, C_z_5), dim=1)
mid_A1Co = self.Autoencoder.fc_decoder(A1Co_combine_2C)
mid_A1Co = mid_A1Co.view(A1Co_combine_2C.shape[0], 256, 8, 8)
A1Co_2C = self.Autoencoder.decoder(mid_A1Co)
AoC1_combine_2A = torch.cat((C_z_1, A_z_2, A_z_3, A_z_4, A_z_5), dim=1)
mid_AoC1 = self.Autoencoder.fc_decoder(AoC1_combine_2A)
mid_AoC1 = mid_AoC1.view(AoC1_combine_2A.shape[0], 256, 8, 8)
AoC1_2A = self.Autoencoder.decoder(mid_AoC1)
# C B same size 2
B2Co_combine_2C = torch.cat((C_z_1, B_z_2, C_z_3, C_z_4, C_z_5), dim=1)
mid_B2Co = self.Autoencoder.fc_decoder(B2Co_combine_2C)
mid_B2Co = mid_B2Co.view(B2Co_combine_2C.shape[0], 256, 8, 8)
B2Co_2C = self.Autoencoder.decoder(mid_B2Co)
BoC2_combine_2B = torch.cat((B_z_1, C_z_2, B_z_3, B_z_4, B_z_5), dim=1)
mid_BoC2 = self.Autoencoder.fc_decoder(BoC2_combine_2B)
mid_BoC2 = mid_BoC2.view(BoC2_combine_2B.shape[0], 256, 8, 8)
BoC2_2B = self.Autoencoder.decoder(mid_BoC2)
# C D same font_color 3
D3Co_combine_2C = torch.cat((C_z_1, C_z_2, D_z_3, C_z_4, C_z_5), dim=1)
mid_D3Co = self.Autoencoder.fc_decoder(D3Co_combine_2C)
mid_D3Co = mid_D3Co.view(D3Co_combine_2C.shape[0], 256, 8, 8)
D3Co_2C = self.Autoencoder.decoder(mid_D3Co)
DoC3_combine_2D = torch.cat((D_z_1, D_z_2, C_z_3, D_z_4, D_z_5), dim=1)
mid_DoC3 = self.Autoencoder.fc_decoder(DoC3_combine_2D)
mid_DoC3 = mid_DoC3.view(DoC3_combine_2D.shape[0], 256, 8, 8)
DoC3_2D = self.Autoencoder.decoder(mid_DoC3)
# C E same back_color 4
E4Co_combine_2C = torch.cat((C_z_1, C_z_2, C_z_3, E_z_4, C_z_5), dim=1)
mid_E4Co = self.Autoencoder.fc_decoder(E4Co_combine_2C)
mid_E4Co = mid_E4Co.view(E4Co_combine_2C.shape[0], 256, 8, 8)
E4Co_2C = self.Autoencoder.decoder(mid_E4Co)
EoC4_combine_2E = torch.cat((E_z_1, E_z_2, E_z_3, C_z_4, E_z_5), dim=1)
mid_EoC4 = self.Autoencoder.fc_decoder(EoC4_combine_2E)
mid_EoC4 = mid_EoC4.view(EoC4_combine_2E.shape[0], 256, 8, 8)
EoC4_2E = self.Autoencoder.decoder(mid_EoC4)
# C F same style 5
F5Co_combine_2C = torch.cat((C_z_1, C_z_2, C_z_3, C_z_4, F_z_5), dim=1)
mid_F5Co = self.Autoencoder.fc_decoder(F5Co_combine_2C)
mid_F5Co = mid_F5Co.view(F5Co_combine_2C.shape[0], 256, 8, 8)
F5Co_2C = self.Autoencoder.decoder(mid_F5Co)
FoC5_combine_2F = torch.cat((F_z_1, F_z_2, F_z_3, F_z_4, C_z_5), dim=1)
mid_FoC5 = self.Autoencoder.fc_decoder(FoC5_combine_2F)
mid_FoC5 = mid_FoC5.view(FoC5_combine_2F.shape[0], 256, 8, 8)
FoC5_2F = self.Autoencoder.decoder(mid_FoC5)
# combine_2C
A1B2D3E4F5_combine_2C = torch.cat((A_z_1, B_z_2, D_z_3, E_z_4, F_z_5), dim=1)
mid_A1B2D3E4F5 = self.Autoencoder.fc_decoder(A1B2D3E4F5_combine_2C)
mid_A1B2D3E4F5 = mid_A1B2D3E4F5.view(A1B2D3E4F5_combine_2C.shape[0], 256, 8, 8)
A1B2D3E4F5_2C = self.Autoencoder.decoder(mid_A1B2D3E4F5)
# ''' need unsupervise '''
A2B3D4E5F1_combine_2N = torch.cat((F_z_1, A_z_2, B_z_3, D_z_4, E_z_5), dim=1)
mid_A2B3D4E5F1 = self.Autoencoder.fc_decoder(A2B3D4E5F1_combine_2N)
mid_A2B3D4E5F1 = mid_A2B3D4E5F1.view(A2B3D4E5F1_combine_2N.shape[0], 256, 8, 8)
A2B3D4E5F1_2N = self.Autoencoder.decoder(mid_A2B3D4E5F1)
'''
optimize for autoencoder
'''
# 1. recon_loss
A_recon_loss = torch.mean(torch.abs(A_img - A_recon))
B_recon_loss = torch.mean(torch.abs(B_img - B_recon))
C_recon_loss = torch.mean(torch.abs(C_img - C_recon))
D_recon_loss = torch.mean(torch.abs(D_img - D_recon))
E_recon_loss = torch.mean(torch.abs(E_img - E_recon))
F_recon_loss = torch.mean(torch.abs(F_img - F_recon))
recon_loss = A_recon_loss + B_recon_loss + C_recon_loss + D_recon_loss + E_recon_loss + F_recon_loss
# 2. sup_combine_loss
A1Co_2C_loss = torch.mean(torch.abs(C_img - A1Co_2C))
AoC1_2A_loss = torch.mean(torch.abs(A_img - AoC1_2A))
B2Co_2C_loss = torch.mean(torch.abs(C_img - B2Co_2C))
BoC2_2B_loss = torch.mean(torch.abs(B_img - BoC2_2B))
D3Co_2C_loss = torch.mean(torch.abs(C_img - D3Co_2C))
DoC3_2D_loss = torch.mean(torch.abs(D_img - DoC3_2D))
E4Co_2C_loss = torch.mean(torch.abs(C_img - E4Co_2C))
EoC4_2E_loss = torch.mean(torch.abs(E_img - EoC4_2E))
F5Co_2C_loss = torch.mean(torch.abs(C_img - F5Co_2C))
FoC5_2F_loss = torch.mean(torch.abs(F_img - FoC5_2F))
A1B2D3E4F5_2C_loss = torch.mean(torch.abs(C_img - A1B2D3E4F5_2C))
combine_sup_loss = A1Co_2C_loss + AoC1_2A_loss + B2Co_2C_loss + BoC2_2B_loss + D3Co_2C_loss + DoC3_2D_loss + E4Co_2C_loss + EoC4_2E_loss + F5Co_2C_loss + FoC5_2F_loss + A1B2D3E4F5_2C_loss
# 3. unsup_combine_loss
_, A2B3D4E5F1_z = self.Autoencoder(A2B3D4E5F1_2N)
combine_unsup_loss = torch.mean(
torch.abs(F_z_1 - A2B3D4E5F1_z[:, 0:self.z_size_start_dim])) + torch.mean(
torch.abs(A_z_2 - A2B3D4E5F1_z[:, self.z_size_start_dim: self.z_font_color_start_dim])) \
+ torch.mean(
torch.abs(B_z_3 - A2B3D4E5F1_z[:, self.z_font_color_start_dim: self.z_back_color_start_dim])) \
+ torch.mean(
torch.abs(D_z_4 - A2B3D4E5F1_z[:, self.z_back_color_start_dim: self.z_style_start_dim])) \
+ torch.mean(torch.abs(E_z_5 - A2B3D4E5F1_z[:, self.z_style_start_dim:]))
# whole loss
vae_unsup_loss = recon_loss + self.lambda_combine * combine_sup_loss + self.lambda_unsup * combine_unsup_loss
self.auto_optim.zero_grad()
vae_unsup_loss.backward()
self.auto_optim.step()
# save the log
f = open(self.log_dir + '/log.txt', 'a')
f.writelines(['\n', '[{}] recon_loss:{:.3f} combine_sup_loss:{:.3f} combine_unsup_loss:{:.3f}'.format(
self.global_iter, recon_loss.data, combine_sup_loss.data, combine_unsup_loss.data)])
f.close()
if self.viz_on and self.global_iter % self.gather_step == 0:
self.gather.insert(iter=self.global_iter, recon_loss=recon_loss.data,
combine_sup_loss=combine_sup_loss.data,
combine_unsup_loss=combine_unsup_loss.data)
if self.global_iter % self.display_step == 0:
pbar.write('[{}] recon_loss:{:.3f} combine_sup_loss:{:.3f} combine_unsup_loss:{:.3f}'.format(
self.global_iter, recon_loss.data, combine_sup_loss.data, combine_unsup_loss.data))
if self.viz_on:
self.gather.insert(images=A_img.data)
self.gather.insert(images=B_img.data)
self.gather.insert(images=C_img.data)
self.gather.insert(images=D_img.data)
self.gather.insert(images=E_img.data)
self.gather.insert(images=F_img.data)
self.gather.insert(images=F.sigmoid(A_recon).data)
self.fonts_viz_reconstruction()
self.viz_lines()
'''
combine show
'''
self.gather.insert(combine_supimages=F.sigmoid(AoC1_2A).data)
self.gather.insert(combine_supimages=F.sigmoid(BoC2_2B).data)
self.gather.insert(combine_supimages=F.sigmoid(D3Co_2C).data)
self.gather.insert(combine_supimages=F.sigmoid(DoC3_2D).data)
self.gather.insert(combine_supimages=F.sigmoid(EoC4_2E).data)
self.gather.insert(combine_supimages=F.sigmoid(FoC5_2F).data)
self.fonts_viz_combine_recon()
self.gather.insert(combine_unsupimages=F.sigmoid(A1B2D3E4F5_2C).data)
self.gather.insert(combine_unsupimages=F.sigmoid(A2B3D4E5F1_2N).data)
self.fonts_viz_combine_unsuprecon()
# self.viz_combine(x)
self.gather.flush()
# Save model checkpoints.
if self.global_iter % self.save_step == 0:
Auto_path = os.path.join(self.model_save_dir, self.viz_name,
'{}-Auto.ckpt'.format(self.global_iter))
torch.save(self.Autoencoder.state_dict(), Auto_path)
print('Saved model checkpoints into {}/{}...'.format(self.model_save_dir, self.viz_name))
if self.global_iter >= self.max_iter:
out = True
break
pbar.write("[Training Finished]")
pbar.close()
def test_fonts(self):
# self.net_mode(train=True)
# load pretrained model
self.restore_model('pretrained')
for index, sup_package in enumerate(self.data_loader):
A_img = sup_package['A']
B_img = sup_package['B']
D_img = sup_package['D']
E_img = sup_package['E']
F_img = sup_package['F']
A_img = Variable(cuda(A_img, self.use_cuda))
B_img = Variable(cuda(B_img, self.use_cuda))
D_img = Variable(cuda(D_img, self.use_cuda))
E_img = Variable(cuda(E_img, self.use_cuda))
F_img = Variable(cuda(F_img, self.use_cuda))
## 1. A B C seperate(first400: id last600 background)
A_recon, A_z = self.Autoencoder(A_img)
B_recon, B_z = self.Autoencoder(B_img)
D_recon, D_z = self.Autoencoder(D_img)
E_recon, E_z = self.Autoencoder(E_img)
F_recon, F_z = self.Autoencoder(F_img)
''' refer 1: content, 2: size, 3: font-color, 4 back_color, 5 style'''
A_z_2 = A_z[:, self.z_size_start_dim: self.z_font_color_start_dim] # 20-40
B_z_3 = B_z[:, self.z_font_color_start_dim: self.z_back_color_start_dim] # 40-60
D_z_4 = D_z[:, self.z_back_color_start_dim: self.z_style_start_dim] # 60-80
E_z_5 = E_z[:, self.z_style_start_dim:] # 80-100
F_z_1 = F_z[:, 0:self.z_size_start_dim] # 0-20
# ''' need unsupervise '''
A2B3D4E5F1_combine_2N = torch.cat((F_z_1, A_z_2, B_z_3, D_z_4, E_z_5), dim=1)
mid_A2B3D4E5F1 = self.Autoencoder.fc_decoder(A2B3D4E5F1_combine_2N)
mid_A2B3D4E5F1 = mid_A2B3D4E5F1.view(A2B3D4E5F1_combine_2N.shape[0], 256, 8, 8)
A2B3D4E5F1_2N = self.Autoencoder.decoder(mid_A2B3D4E5F1)
# save synthesized image
self.test_iter = index
self.gather.insert(test=F.sigmoid(A2B3D4E5F1_2N).data)
self.fonts_viz_test()
self.gather.flush()
def fonts_save_sample_img(self, tensor, mode):
unloader = transforms.ToPILImage()
dir = os.path.join(self.model_save_dir, self.viz_name, 'sample_img')
if not os.path.exists(dir):
os.makedirs(dir)
image = tensor.cpu().clone() # we clone the tensor to not do changes on it
if mode == 'recon':
image_ori_A = image[0].squeeze(0) # remove the fake batch dimension
image_ori_B = image[1].squeeze(0)
image_ori_C = image[2].squeeze(0)
image_ori_D = image[3].squeeze(0)
image_ori_E = image[4].squeeze(0)
image_ori_F = image[5].squeeze(0)
image_recon = image[6].squeeze(0)
image_ori_A = unloader(image_ori_A)
image_ori_B = unloader(image_ori_B)
image_ori_C = unloader(image_ori_C)
image_ori_D = unloader(image_ori_D)
image_ori_E = unloader(image_ori_E)
image_ori_F = unloader(image_ori_F)
image_recon = unloader(image_recon)
image_ori_A.save(os.path.join(dir, '{}-A_img.png'.format(self.global_iter)))
image_ori_B.save(os.path.join(dir, '{}-B_img.png'.format(self.global_iter)))
image_ori_C.save(os.path.join(dir, '{}-C_img.png'.format(self.global_iter)))
image_ori_D.save(os.path.join(dir, '{}-D_img.png'.format(self.global_iter)))
image_ori_E.save(os.path.join(dir, '{}-E_img.png'.format(self.global_iter)))
image_ori_F.save(os.path.join(dir, '{}-F_img.png'.format(self.global_iter)))
image_recon.save(os.path.join(dir, '{}-A_img_recon.png'.format(self.global_iter)))
elif mode == 'combine_sup':
image_AoC1_2A = image[0].squeeze(0) # remove the fake batch dimension
image_BoC2_2B = image[1].squeeze(0)
image_D3Co_2C = image[2].squeeze(0)
image_DoC3_2D = image[3].squeeze(0)
image_EoC4_2E = image[4].squeeze(0)