forked from clovaai/deep-text-recognition-benchmark
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrain_textsynth_v2_tS_sU_debug.py
1663 lines (1357 loc) · 84 KB
/
train_textsynth_v2_tS_sU_debug.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
# Desc: orig(v0) + gt of target style image
import os
import sys
import time
import random
import string
import argparse
import glob
import math
import re
import torch
import torch.backends.cudnn as cudnn
import torch.nn.init as init
import torch.optim as optim
import torch.utils.data
from torch.optim import lr_scheduler
import numpy as np
import torchvision.models as models
from torchvision import transforms, utils
import torch.nn.functional as F
import torch.autograd as autograd
import pdb
import html_visual as html
from skimage.metrics import peak_signal_noise_ratio, mean_squared_error, structural_similarity
from nltk.metrics.distance import edit_distance
from utils import CTCLabelConverter, AttnLabelConverter, Averager
from dataset import hierarchical_dataset, AlignPairCollate, AlignPairImgCollate, AlignSynthTextCollate, Batch_Balanced_Dataset, tensor2im, save_image, phoc_gen, text_gen, text_gen_synth, LmdbStyleDataset, LmdbStyleContentDataset
# from model import ModelV1, StyleTensorEncoder, StyleLatentEncoder, MsImageDisV2, AdaIN_Tensor_WordGenerator, VGGPerceptualLossModel, Mixer
from model import ModelV1, GlobalContentEncoder, VGGPerceptualEmbedLossModel, VGGFontModel
# from test_synth import validation_synth_v7
from modules.feature_extraction import ResNet_StyleExtractor, VGG_ContentExtractor, ResNet_StyleExtractor_WIN
import tflib as lib
import tflib.plot
sys.path.append('/private/home/pkrishnan/codes/st-scribe/stylegan2-pytorch/')
try:
import wandb
except ImportError:
wandb = None
from model_word import GeneratorM2V4_5_debug as styleGANGen
from model_word import EncDiscriminator as styleGANDis
from non_leaking import augment
from distributed import (
get_rank,
synchronize,
reduce_loss_dict,
reduce_sum,
get_world_size,
)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def data_sampler(dataset, shuffle, distributed):
if distributed:
return torch.utils.data.distributed.DistributedSampler(dataset, shuffle=shuffle)
if shuffle:
return torch.utils.data.RandomSampler(dataset)
else:
return torch.utils.data.SequentialSampler(dataset)
def requires_grad(model, flag=True):
for p in model.parameters():
p.requires_grad = flag
def accumulate(model1, model2, decay=0.999):
par1 = dict(model1.named_parameters())
par2 = dict(model2.named_parameters())
for k in par1.keys():
par1[k].data.mul_(decay).add_(par2[k].data, alpha=1 - decay)
def sample_data(loader, data_sampler, is_distributed):
epochCntr=0
while True:
if is_distributed:
data_sampler.set_epoch(epochCntr)
for batch in loader:
yield batch
epochCntr+=1
def d_logistic_loss(real_pred, fake_pred):
real_loss = F.softplus(-real_pred)
fake_loss = F.softplus(fake_pred)
return real_loss.mean() + fake_loss.mean()
def d_r1_loss(real_pred, real_img):
grad_real, = autograd.grad(
outputs=real_pred.sum(), inputs=real_img, create_graph=True
)
grad_penalty = grad_real.pow(2).reshape(grad_real.shape[0], -1).sum(1).mean()
return grad_penalty
def g_nonsaturating_loss(fake_pred):
loss = F.softplus(-fake_pred).mean()
return loss
def g_path_regularize(fake_img, latents, mean_path_length, decay=0.01):
noise = torch.randn_like(fake_img) / math.sqrt(
fake_img.shape[2] * fake_img.shape[3]
)
grad, = autograd.grad(
outputs=(fake_img * noise).sum(), inputs=latents, create_graph=True
)
path_lengths = torch.sqrt(grad.pow(2).sum(2).mean(1))
path_mean = mean_path_length + decay * (path_lengths.mean() - mean_path_length)
path_penalty = (path_lengths - path_mean).pow(2).mean()
return path_penalty, path_mean.detach(), path_lengths
def make_noise(z_code, batch, latent_dim, n_noise, device):
if n_noise == 1:
return torch.cat((z_code, torch.randn(batch, latent_dim, device=device)),1)
noises = torch.cat((z_code.repeat(2,1,1), torch.randn(n_noise, batch, latent_dim, device=device)),2).unbind(0)
return noises
def make_noise_style(batch, latent_dim, n_noise, device):
if n_noise == 1:
return torch.randn(batch, latent_dim, device=device)
noises = torch.randn(n_noise, batch, latent_dim, device=device).unbind(0)
return noises
def mixing_noise(batch, latent_dim, prob, device, z_code=None):
if prob > 0 and random.random() < prob:
if z_code is None:
return make_noise_style(batch, latent_dim, 2, device)
else:
return make_noise(z_code, batch, latent_dim, 2, device)
else:
if z_code is None:
return [make_noise_style(batch, latent_dim, 1, device)]
else:
return [make_noise(z_code, batch, latent_dim, 1, device)]
def mixing_noise_style(batch, latent_dim, prob, device):
if prob > 0 and random.random() < prob:
return make_noise_style(batch, latent_dim, 2, device)
else:
return [make_noise_style(batch, latent_dim, 1, device)]
def set_grad_none(model, targets):
for n, p in model.named_parameters():
if n in targets:
p.grad = None
def train(opt):
lib.print_model_settings(locals().copy())
if 'Attn' in opt.Prediction:
converter = AttnLabelConverter(opt.character)
text_len = opt.batch_max_length+2
else:
converter = CTCLabelConverter(opt.character)
text_len = opt.batch_max_length
opt.classes = converter.character
""" dataset preparation """
if not opt.data_filtering_off:
print('Filtering the images containing characters which are not in opt.character')
print('Filtering the images whose label is longer than opt.batch_max_length')
# see https://github.com/clovaai/deep-text-recognition-benchmark/blob/6593928855fb7abb999a99f428b3e4477d4ae356/dataset.py#L130
log = open(os.path.join(opt.exp_dir,opt.exp_name,'log_dataset.txt'), 'a')
AlignCollate_valid = AlignPairImgCollate(imgH=opt.imgH, imgW=opt.imgW, keep_ratio_with_pad=opt.PAD)
# train_dataset = LmdbStyleDataset(root=opt.train_data, opt=opt)
train_dataset = LmdbStyleContentDataset(root=opt.train_data, opt=opt, dataMode=opt.realTrData)
train_data_sampler = data_sampler(train_dataset, shuffle=True, distributed=opt.distributed)
train_loader = torch.utils.data.DataLoader(
train_dataset, batch_size=opt.batch_size,
shuffle=False, # 'True' to check training progress with validation function.
sampler=train_data_sampler,
num_workers=int(opt.workers),
collate_fn=AlignCollate_valid, pin_memory=True, drop_last=True)
train_loader = sample_data(train_loader, train_data_sampler, opt.distributed)
print('-' * 80)
# valid_dataset = LmdbStyleDataset(root=opt.valid_data, opt=opt)
valid_dataset = LmdbStyleContentDataset(root=opt.valid_data, opt=opt, dataMode=opt.realVaData)
test_data_sampler = data_sampler(valid_dataset, shuffle=False, distributed=opt.distributed)
valid_loader = torch.utils.data.DataLoader(
valid_dataset, batch_size=opt.batch_size,
shuffle=False, # 'True' to check training progress with validation function.
sampler=test_data_sampler,
num_workers=int(opt.workers),
collate_fn=AlignCollate_valid, pin_memory=True, drop_last=True)
numTestSamples = len(valid_loader)
# valid_loader = sample_data(valid_loader)
print('-' * 80)
log.write('-' * 80 + '\n')
log.close()
AlignCollate_text = AlignSynthTextCollate(imgH=opt.imgH, imgW=opt.imgW, keep_ratio_with_pad=opt.PAD)
# text_dataset = text_gen(opt)
text_dataset = text_gen_synth(opt)
text_data_sampler = data_sampler(text_dataset, shuffle=True, distributed=opt.distributed)
text_loader = torch.utils.data.DataLoader(
text_dataset, batch_size=opt.batch_size,
shuffle=False,
sampler=text_data_sampler,
num_workers=int(opt.workers),
collate_fn=AlignCollate_text,
drop_last=True)
opt.num_class = len(converter.character)
text_loader = sample_data(text_loader, text_data_sampler, opt.distributed)
if not opt.zAlone:
c_code_size = opt.latent
if opt.cEncode == 'mlp':
cEncoder = GlobalContentEncoder(opt.num_class, text_len, opt.char_embed_size, c_code_size).to(device)
elif opt.cEncode == 'cnn':
# for synthetic image
# cEncoder = VGG_ContentExtractor(1, opt.latent).to(device)
if opt.contentNorm == 'in':
cEncoder = ResNet_StyleExtractor_WIN(1, opt.latent).to(device)
else:
cEncoder = ResNet_StyleExtractor(1, opt.latent).to(device)
if opt.styleNorm == 'in':
styleModel = ResNet_StyleExtractor_WIN(opt.input_channel, opt.style_latent).to(device)
else:
styleModel = ResNet_StyleExtractor(opt.input_channel, opt.style_latent).to(device)
ocrModel = ModelV1(opt).to(device)
# #temp
# pdb.set_trace()
# ocrModel = torch.nn.DataParallel(ocrModel).to(device)
# checkpoint = torch.load(opt.saved_ocr_model)
# ocrModel.load_state_dict(checkpoint)
# torch.save(ocrModel.module.state_dict(),'/checkpoint/pkrishnan/experiments/scribe/pretrained/TPS-ResNet-BiLSTM-Attn-case-sensitive_actual_nonparallel.pth')
if 'CTC' in opt.Prediction:
ocrCriterion = torch.nn.CTCLoss(zero_infinity=True).to(device)
else:
ocrCriterion = torch.nn.CrossEntropyLoss(ignore_index=0).to(device) # ignore [GO] token = ignore index 0
if opt.imgReconLoss == 'l1':
reconCriterion = torch.nn.L1Loss()
elif opt.imgReconLoss == 'l2':
reconCriterion = torch.nn.MSELoss()
if opt.saved_font_model !='' and opt.saved_font_model !='None':
checkpoint = torch.load(opt.saved_font_model, map_location=lambda storage, loc: storage)
preTrainedVGGModel = VGGFontModel(models.vgg19(pretrained=False), numClasses=checkpoint['vggFontModel']['classifier.6.weight'].shape[0])
preTrainedVGGModel.load_state_dict(checkpoint['vggFontModel'])
resize = False
else:
preTrainedVGGModel = models.vgg19(pretrained=True)
resize = True
vggModel = VGGPerceptualEmbedLossModel(preTrainedVGGModel, reconCriterion, resize).to(device)
vggModel.eval()
else:
c_code_size = 0
# weight initialization for style and content models
if not opt.zAlone:
for model in [styleModel, cEncoder]:
for name, param in model.named_parameters():
if 'localization_fc2' in name:
print(f'Skip {name} as it is already initialized')
continue
try:
if 'bias' in name:
init.constant_(param, 0.0)
elif 'weight' in name:
init.kaiming_normal_(param)
except Exception as e: # for batchnorm.
print('Exception in weight init'+ name)
if 'weight' in name:
param.data.fill_(1)
continue
if opt.noiseConcat:
genModel = styleGANGen(opt.size, opt.style_latent*2, opt.latent, opt.n_mlp, content_dim=c_code_size, channel_multiplier=opt.channel_multiplier).to(device)
g_ema = styleGANGen(opt.size, opt.style_latent*2, opt.latent, opt.n_mlp, content_dim=c_code_size, channel_multiplier=opt.channel_multiplier).to(device)
else:
genModel = styleGANGen(opt.size, opt.style_latent, opt.latent, opt.n_mlp, content_dim=c_code_size, channel_multiplier=opt.channel_multiplier).to(device)
g_ema = styleGANGen(opt.size, opt.style_latent, opt.latent, opt.n_mlp, content_dim=c_code_size, channel_multiplier=opt.channel_multiplier).to(device)
g_ema.eval()
disEncModel = styleGANDis(opt.size, channel_multiplier=opt.channel_multiplier, input_dim=opt.input_channel, code_s_dim=opt.latent).to(device)
accumulate(g_ema, genModel, 0)
g_reg_ratio = opt.g_reg_every / (opt.g_reg_every + 1)
d_reg_ratio = opt.d_reg_every / (opt.d_reg_every + 1)
if opt.zAlone:
optimizer = optim.Adam(
genModel.parameters(),
lr=opt.lr * g_reg_ratio,
betas=(0 ** g_reg_ratio, 0.99 ** g_reg_ratio),
)
else:
optimizer = optim.Adam(
list(genModel.parameters())+list(cEncoder.parameters())+list(styleModel.parameters()),
lr=opt.lr * g_reg_ratio,
betas=(0 ** g_reg_ratio, 0.99 ** g_reg_ratio),
)
if opt.optim == "adam":
ocr_optimizer = optim.Adam(
ocrModel.parameters(),
lr=opt.lr,
betas=(0.9, 0.99),
)
else:
ocr_optimizer = optim.Adadelta(
ocrModel.parameters(),
lr=1.0,
rho=opt.rho, eps=opt.eps,
)
dis_optimizer = optim.Adam(
disEncModel.parameters(),
lr=opt.lr * d_reg_ratio,
betas=(0 ** d_reg_ratio, 0.99 ** d_reg_ratio),
)
# print('Model Initialization')
bestModelError=1e5
## Loading pre-trained files
if opt.modelFolderFlag:
if len(glob.glob(os.path.join(opt.exp_dir,opt.exp_name,"iter_*_synth.pth")))>0:
opt.saved_synth_model = glob.glob(os.path.join(opt.exp_dir,opt.exp_name,"iter_*_synth.pth"))[-1]
if not opt.zAlone:
if opt.saved_ocr_model !='' and opt.saved_ocr_model !='None':
print(f'loading pretrained ocr model from {opt.saved_ocr_model}')
checkpoint = torch.load(opt.saved_ocr_model, map_location=lambda storage, loc: storage)
ocrModel.load_state_dict(checkpoint)
if opt.saved_gen_model !='' and opt.saved_gen_model !='None':
print(f'loading pretrained gen model from {opt.saved_gen_model}')
checkpoint = torch.load(opt.saved_gen_model, map_location=lambda storage, loc: storage)
genModel.load_state_dict(checkpoint['genModel'])
g_ema.load_state_dict(checkpoint['g_ema'])
if opt.saved_synth_model != '' and opt.saved_synth_model != 'None':
print(f'loading pretrained synth model from {opt.saved_synth_model}')
checkpoint = torch.load(opt.saved_synth_model, map_location=lambda storage, loc: storage)
if not opt.zAlone:
cEncoder.load_state_dict(checkpoint['cEncoder'])
styleModel.load_state_dict(checkpoint['styleModel'])
ocrModel.load_state_dict(checkpoint['ocrModel'])
genModel.load_state_dict(checkpoint['genModel'])
g_ema.load_state_dict(checkpoint['g_ema'])
disEncModel.load_state_dict(checkpoint['disEncModel'])
optimizer.load_state_dict(checkpoint["optimizer"])
dis_optimizer.load_state_dict(checkpoint["dis_optimizer"])
if not opt.zAlone:
ocr_optimizer.load_state_dict(checkpoint["ocr_optimizer"])
if 'bestModelError' in checkpoint:
bestModelError = checkpoint['bestModelError']
# print('Loaded checkpoint')
if not opt.zAlone and opt.distributed:
cEncoder = torch.nn.parallel.DistributedDataParallel(
cEncoder,
device_ids=[opt.local_rank],
output_device=opt.local_rank,
broadcast_buffers=False,
find_unused_parameters=True
)
# cEncoder= torch.nn.DataParallel(cEncoder).to(device)
cEncoder.train()
styleModel = torch.nn.parallel.DistributedDataParallel(
styleModel,
device_ids=[opt.local_rank],
output_device=opt.local_rank,
broadcast_buffers=False,
find_unused_parameters=True
)
# styleModel= torch.nn.DataParallel(styleModel).to(device)
styleModel.train()
vggModel = torch.nn.parallel.DistributedDataParallel(
vggModel,
device_ids=[opt.local_rank],
output_device=opt.local_rank,
broadcast_buffers=False,
find_unused_parameters=True
)
# vggModel= torch.nn.DataParallel(vggModel).to(device)
vggModel.eval()
ocrModel = torch.nn.parallel.DistributedDataParallel(
ocrModel,
device_ids=[opt.local_rank],
output_device=opt.local_rank,
broadcast_buffers=False,
find_unused_parameters=True
)
# ocrModel = torch.nn.DataParallel(ocrModel).to(device)
if opt.ocrFixed:
if opt.Transformation == 'TPS':
ocrModel.module.Transformation.eval()
ocrModel.module.FeatureExtraction.eval()
ocrModel.module.AdaptiveAvgPool.eval()
# ocrModel.module.SequenceModeling.eval()
ocrModel.module.Prediction.eval()
else:
ocrModel.train()
if opt.distributed:
genModel = torch.nn.parallel.DistributedDataParallel(
genModel,
device_ids=[opt.local_rank],
output_device=opt.local_rank,
broadcast_buffers=False,
find_unused_parameters=True
)
disEncModel = torch.nn.parallel.DistributedDataParallel(
disEncModel,
device_ids=[opt.local_rank],
output_device=opt.local_rank,
broadcast_buffers=False,
find_unused_parameters=True
)
# genModel = torch.nn.DataParallel(genModel).to(device)
# g_ema = torch.nn.DataParallel(g_ema).to(device)
# genModel.train()
# g_ema.eval()
# disEncModel = torch.nn.DataParallel(disEncModel).to(device)
# disEncModel.train()
# print('Loaded distributed')
if opt.distributed:
if not opt.zAlone:
cEncoder_module = cEncoder.module
styleModel_module = styleModel.module
ocrModel_module = ocrModel.module
genModel_module = genModel.module
disEncModel_module = disEncModel.module
else:
if not opt.zAlone:
cEncoder_module = cEncoder
styleModel_module = styleModel
ocrModel_module = ocrModel
genModel_module = genModel
disEncModel_module = disEncModel
# print('Loading module')
# loss averager
loss_recon_train = Averager()
loss_recon_val = Averager()
loss_avg_dis = Averager()
loss_avg_gen = Averager()
log_r1_val = Averager()
log_avg_path_loss_val = Averager()
log_avg_mean_path_length_avg = Averager()
log_ada_aug_p = Averager()
loss_avg_ocr_sup = Averager()
loss_avg_ocr_unsup = Averager()
loss_avg_style_ucode = Averager()
loss_avg_style_scode = Averager()
loss_avg_img_recon = Averager()
loss_avg_cycle_recon = Averager()
loss_avg_vgg_per = Averager()
loss_avg_vgg_sty = Averager()
loss_avg_vgg_emb = Averager()
""" final options """
with open(os.path.join(opt.exp_dir,opt.exp_name,'opt.txt'), 'a') as opt_file:
opt_log = '------------ Options -------------\n'
args = vars(opt)
for k, v in args.items():
opt_log += f'{str(k)}: {str(v)}\n'
opt_log += '---------------------------------------\n'
print(opt_log)
opt_file.write(opt_log)
""" start training """
start_iter = 0
if opt.saved_synth_model != '' and opt.saved_synth_model != 'None':
try:
start_iter = int(opt.saved_synth_model.split('_')[-2].split('.')[0])
print(f'continue to train, start_iter: {start_iter}')
except:
pass
#get schedulers
scheduler = get_scheduler(optimizer,opt)
dis_scheduler = get_scheduler(dis_optimizer,opt)
if not opt.zAlone:
ocr_scheduler = get_scheduler(ocr_optimizer,opt)
iteration = start_iter
cntr=0
mean_path_length = 0
d_loss_val = 0
r1_loss = torch.tensor(0.0, device=device)
g_loss_val = 0
path_loss = torch.tensor(0.0, device=device)
path_lengths = torch.tensor(0.0, device=device)
mean_path_length_avg = 0
# loss_dict = {}
accum = 0.5 ** (32 / (10 * 1000))
ada_augment = torch.tensor([0.0, 0.0], device=device)
ada_aug_p = opt.augment_p if opt.augment_p > 0 else 0.0
ada_aug_step = opt.ada_target / opt.ada_length
r_t_stat = 0
epsilon = 10e-50
sample_z = torch.randn(opt.n_sample, opt.latent, device=device)
while(True):
# print(cntr)
# train part
start_time = time.time()
if not opt.testFlag:
if opt.lr_policy !="None":
scheduler.step()
dis_scheduler.step()
if not opt.zAlone:
ocr_scheduler.step()
image_input_tensors, image_output_tensors, labels_gt, labels_z_c, labelSynthImg, synth_z_c = next(train_loader)
# labels_z_c, synth_z_c = next(text_loader)
# labels_z_c, synth_z_c = labels_output, labelSynthImg_output
# print(labels)
# print(labels_z_c)
image_input_tensors = image_input_tensors.to(device)
image_output_tensors = image_output_tensors.to(device)
# gt_image_tensors = image_input_tensors.detach() #exemplar word style image; training OCR
# real_image_tensors = image_input_tensors.detach() #discriminator
synth_z_c = synth_z_c.to(device)
# labels_gt = labels[:opt.batch_size]
if not opt.zAlone:
requires_grad(cEncoder, False)
requires_grad(styleModel, False)
requires_grad(ocrModel, False)
requires_grad(vggModel, False)
requires_grad(genModel, False)
requires_grad(disEncModel, True)
text_z_c, length_z_c = converter.encode(labels_z_c, batch_max_length=opt.batch_max_length)
text_gt, length_gt = converter.encode(labels_gt, batch_max_length=opt.batch_max_length)
# print('Before cEncoder')
if opt.zAlone:
z_c_code = None
style = None
else:
if opt.cEncode == 'mlp':
z_c_code = cEncoder(text_z_c)
elif opt.cEncode == 'cnn':
z_c_code = cEncoder(synth_z_c)
# print('Before styleModel')
style = styleModel(image_input_tensors)
if opt.noiseConcat or opt.zAlone:
style = mixing_noise(opt.batch_size, opt.latent, opt.mixing, device, style)
else:
style = [style]
# print('Before genModel')
fake_img,_ = genModel(style, z_c_code, input_is_latent=opt.input_latent)
# print('After genModel')
#unsupervised style code prediction on generated image using StyleEncoder/Discriminator
if opt.gamma_e>0.0 and not opt.zAlone:
uPred_style_code = disEncModel(fake_img, mode='enc')
uCost = reconCriterion(uPred_style_code, style[0][:opt.latent])
else:
uCost = torch.tensor(0.0)
#Domain discriminator
# print('Before disModel')
fake_pred = disEncModel(fake_img)
real_pred = disEncModel(image_input_tensors)
# print('After disModel')
disCost = d_logistic_loss(real_pred, fake_pred)
dis_t_cost = disCost + opt.gamma_e*uCost
loss_avg_dis.add(disCost)
loss_avg_style_ucode.add(uCost)
disEncModel.zero_grad()
dis_t_cost.backward()
if opt.grad_clip !=0.0:
torch.nn.utils.clip_grad_norm_(disEncModel.parameters(), opt.grad_clip) # gradient clipping with 5 (Default)
dis_optimizer.step()
# print('After disOptim backward')
d_regularize = cntr % opt.d_reg_every == 0
if d_regularize:
image_input_tensors.requires_grad = True
# print('before d_regularize backward')
real_pred = disEncModel(image_input_tensors)
r1_loss = d_r1_loss(real_pred, image_input_tensors)
disEncModel.zero_grad()
(opt.r1 / 2 * r1_loss * opt.d_reg_every + 0 * real_pred[0]).backward()
# print('after d_regularize backward')
if opt.grad_clip !=0.0:
torch.nn.utils.clip_grad_norm_(disEncModel.parameters(), opt.grad_clip) # gradient clipping with 5 (Default)
dis_optimizer.step()
log_r1_val.add(r1_loss)
image_input_tensors.requires_grad = False
# Recognizer update
if not opt.ocrFixed and not opt.zAlone:
requires_grad(disEncModel, False)
if not opt.zAlone:
requires_grad(ocrModel, True)
if 'CTC' in opt.Prediction:
preds_recon = ocrModel(image_input_tensors, text_gt, is_train=True, inAct = opt.taskActivation)
preds_size = torch.IntTensor([preds_recon.size(1)] * opt.batch_size)
preds_recon_softmax = preds_recon.log_softmax(2).permute(1, 0, 2)
ocrCost = ocrCriterion(preds_recon_softmax, text_gt, preds_size, length_gt)
else:
preds_recon = ocrModel(image_input_tensors, text_gt[:, :-1], is_train=True, inAct = opt.taskActivation) # align with Attention.forward
target = text_gt[:, 1:] # without [GO] Symbol
ocrCost = ocrCriterion(preds_recon.view(-1, preds_recon.shape[-1]), target.contiguous().view(-1))
# print("Not implemented error")
# sys.exit()
ocrModel.zero_grad()
ocrCost.backward()
if opt.grad_clip !=0.0:
torch.nn.utils.clip_grad_norm_(ocrModel.parameters(), opt.grad_clip) # gradient clipping with 5 (Default)
ocr_optimizer.step()
else:
ocrCost = torch.tensor(0.0)
loss_avg_ocr_sup.add(ocrCost)
# [Word Generator] update
image_input_tensors, image_output_tensors, labels_gt, labels_z_c, labelSynthImg, synth_z_c = next(train_loader)
# labels_z_c, synth_z_c = next(text_loader)
# print(labels_z_c)
image_input_tensors = image_input_tensors.to(device)
image_output_tensors = image_output_tensors.to(device)
# gt_image_tensors = image_input_tensors[:opt.batch_size].detach() #exemplar word style image; training OCR
# labels_gt = labels[:opt.batch_size]
labelSynthImg = labelSynthImg.to(device)
synth_z_c = synth_z_c.to(device)
if not opt.zAlone:
requires_grad(cEncoder, True)
requires_grad(styleModel, True)
requires_grad(ocrModel, False)
requires_grad(vggModel, False)
requires_grad(genModel, True)
requires_grad(disEncModel, False)
text_z_c, length_z_c = converter.encode(labels_z_c, batch_max_length=opt.batch_max_length)
text_gt, length_gt = converter.encode(labels_gt, batch_max_length=opt.batch_max_length)
# print('before generator cEncoder')
if opt.zAlone:
z_c_code = None
style = None
else:
if opt.cEncode == 'mlp':
z_c_code = cEncoder(text_z_c)
z_gt_code = cEncoder(text_gt)
elif opt.cEncode == 'cnn':
z_c_code = cEncoder(synth_z_c)
z_gt_code = cEncoder(labelSynthImg)
# print('after generator cEncoder')
style = styleModel(image_input_tensors)
# print('after generator styleModel')
if opt.noiseConcat or opt.zAlone:
style = mixing_noise(opt.batch_size, opt.latent, opt.mixing, device, style)
else:
style = [style]
# fake_img,_ = genModel(style, z_c_code, input_is_latent=opt.input_latent)
fake_gt_img,_ = genModel(style, z_gt_code, input_is_latent=opt.input_latent)
# print('after generator genModel')
fake_pred = disEncModel(fake_gt_img)
disGenCost = g_nonsaturating_loss(fake_pred)
# print('after generator disModel')
if opt.zAlone:
ocrCost = torch.tensor(0.0)
uCost = torch.tensor(0.0)
imgReconCost = torch.tensor(0.0)
vggPerCost = torch.tensor(0.0)
vggStyCost = torch.tensor(0.0)
vggEmbCost = torch.tensor(0.0)
else:
#Compute OCR prediction (Reconstruction of content)
if 'CTC' in opt.Prediction:
preds_recon = ocrModel(fake_gt_img, text_gt, is_train=False, inAct = opt.taskActivation)
preds_size = torch.IntTensor([preds_recon.size(1)] * opt.batch_size)
preds_recon_softmax = preds_recon.log_softmax(2).permute(1, 0, 2)
ocrCost = ocrCriterion(preds_recon_softmax, text_gt, preds_size, length_gt)
else:
preds_recon = ocrModel(fake_gt_img, text_gt[:, :-1], is_train=False, inAct = opt.taskActivation) # align with Attention.forward
target = text_gt[:, 1:] # without [GO] Symbol
ocrCost = ocrCriterion(preds_recon.view(-1, preds_recon.shape[-1]), target.contiguous().view(-1))
# print("Not implemented error")
# sys.exit()
# print('after generator ocrModel')
if opt.gamma_g>0.0:
uPred_style_code = disEncModel(fake_gt_img, mode='enc')
uCost = reconCriterion(uPred_style_code, style[0][:opt.latent])
else:
uCost = torch.tensor(0.0)
if opt.reconWeight>0.0:
imgReconCost = reconCriterion(fake_gt_img, image_input_tensors)
else:
imgReconCost = torch.tensor(0.0)
# print('after generator recon genModel')
if opt.cycleReconWeight > 0.0:
style_fake = styleModel(fake_gt_img)
if opt.noiseConcat or opt.zAlone:
style_fake = mixing_noise(opt.batch_size, opt.latent, opt.mixing, device, style_fake)
else:
style_fake = [style_fake]
fake_recon_img, _ = genModel(style_fake, z_gt_code, input_is_latent=opt.input_latent)
cycleReconCost = reconCriterion(fake_recon_img, image_input_tensors)
else:
cycleReconCost = torch.tensor(0.0)
# print('after generator cycle genModel')
if opt.vggPerWeight>0.0 or opt.vggStyWeight>0.0 or opt.vggEmbWeight>0.0:
vggPerCost , vggStyCost, vggEmbCost = vggModel(fake_gt_img, image_input_tensors, inAct=opt.taskActivation, normFlag=not(opt.vggNoMean))
else:
vggPerCost = torch.tensor(0.0)
vggStyCost = torch.tensor(0.0)
vggEmbCost = torch.tensor(0.0)
# print('after generator vggModel')
genModel.zero_grad()
if not opt.zAlone:
styleModel.zero_grad()
cEncoder.zero_grad()
gen_enc_cost = disGenCost + opt.ocrWeight * ocrCost + opt.gamma_g * uCost \
+ opt.reconWeight * imgReconCost + opt.vggPerWeight * vggPerCost \
+ opt.vggStyWeight * vggStyCost + opt.vggEmbWeight * vggEmbCost \
+ opt.cycleReconWeight * cycleReconCost
gen_enc_cost.backward()
# print('after generator backward')
loss_recon_train.add(reconCriterion(fake_gt_img, image_input_tensors))
loss_avg_gen.add(disGenCost)
loss_avg_ocr_unsup.add(opt.ocrWeight * ocrCost)
loss_avg_style_scode.add(opt.gamma_g * uCost)
loss_avg_img_recon.add(opt.reconWeight * imgReconCost)
loss_avg_cycle_recon.add(opt.cycleReconWeight * cycleReconCost)
loss_avg_vgg_per.add(opt.vggPerWeight * vggPerCost)
loss_avg_vgg_sty.add(opt.vggStyWeight * vggStyCost)
loss_avg_vgg_emb.add(opt.vggEmbWeight * vggEmbCost)
if opt.grad_clip !=0.0:
torch.nn.utils.clip_grad_norm_(genModel.parameters(), opt.grad_clip) # gradient clipping with 5 (Default)
torch.nn.utils.clip_grad_norm_(cEncoder.parameters(), opt.grad_clip) # gradient clipping with 5 (Default)
torch.nn.utils.clip_grad_norm_(styleModel.parameters(), opt.grad_clip) # gradient clipping with 5 (Default)
optimizer.step()
if not opt.zAlone:
if get_rank() == 0 and ((iteration + 1) % opt.valInterval == 0 or iteration == 0):
#print training images
os.makedirs(os.path.join(opt.trainDir,str(iteration)), exist_ok=True)
text_for_pred = torch.LongTensor(opt.batch_size, opt.batch_max_length + 1).fill_(0).to(device)
length_for_pred = torch.IntTensor([opt.batch_max_length] * opt.batch_size).to(device)
#run OCR prediction for gen image (content: gt from input_image_tensors)
if 'CTC' in opt.Prediction:
_, preds_index = preds_recon.max(2)
preds_str_fake_gt_img = converter.decode(preds_index.data, preds_size.data)
else:
_, preds_index = preds_recon.max(2)
preds_str_fake_gt_img = converter.decode(preds_index, length_for_pred)
for idx, pred in enumerate(preds_str_fake_gt_img):
pred_EOS = pred.find('[s]')
preds_str_fake_gt_img[idx] = pred[:pred_EOS] # prune after "end of sentence" token ([s])
#render target style image using paired content
g_ema.eval()
with torch.no_grad():
fake_sty_img, _ = g_ema(style, z_c_code, input_is_latent=opt.input_latent)
if 'CTC' in opt.Prediction:
preds = ocrModel(fake_sty_img, text_z_c, is_train=False, inAct = opt.taskActivation)
preds_size = torch.IntTensor([preds.size(1)] * opt.batch_size)
_, preds_index = preds.max(2)
preds_str_fake_sty_img = converter.decode(preds_index.data, preds_size.data)
else:
preds = ocrModel(fake_sty_img, text_z_c[:, :-1], is_train=False, inAct = opt.taskActivation) # align with Attention.forward
_, preds_index = preds.max(2)
preds_str_fake_sty_img = converter.decode(preds_index, length_for_pred)
for idx, pred in enumerate(preds_str_fake_sty_img):
pred_EOS = pred.find('[s]')
preds_str_fake_sty_img[idx] = pred[:pred_EOS] # prune after "end of sentence" token ([s])
if opt.cycleReconWeight>0.0:
if 'CTC' in opt.Prediction:
preds = ocrModel(fake_recon_img, text_gt, is_train=False, inAct = opt.taskActivation)
preds_size = torch.IntTensor([preds.size(1)] * opt.batch_size)
_, preds_index = preds.max(2)
preds_str_fake_recon_img = converter.decode(preds_index.data, preds_size.data)
else:
preds = ocrModel(fake_recon_img, text_gt[:, :-1], is_train=False, inAct = opt.taskActivation) # align with Attention.forward
_, preds_index = preds.max(2)
preds_str_fake_recon_img = converter.decode(preds_index, length_for_pred)
for idx, pred in enumerate(preds_str_fake_recon_img):
pred_EOS = pred.find('[s]')
preds_str_fake_recon_img[idx] = pred[:pred_EOS] # prune after "end of sentence" token ([s])
for trImgCntr in range(opt.batch_size):
try:
if not opt.zAlone:
utils.save_image(image_output_tensors[trImgCntr],os.path.join(opt.trainDir,str(iteration),str(trImgCntr)+'_tr_z_orig_'+labels_z_c[trImgCntr]+'_ocr:None'+'.png'),nrow=1,normalize=True,range=(-1, 1))
if opt.cEncode == 'cnn':
utils.save_image(synth_z_c[trImgCntr],os.path.join(opt.trainDir,str(iteration),str(trImgCntr)+'_tr_synth_'+labels_z_c[trImgCntr]+'_ocr:None'+'.png'),nrow=1,normalize=True,range=(-1, 1))
utils.save_image(fake_gt_img[trImgCntr],os.path.join(opt.trainDir,str(iteration),str(trImgCntr)+'_tr_gt_recon_pred_'+labels_gt[trImgCntr]+'_ocr:'+preds_str_fake_gt_img[trImgCntr]+'_sty:'+labels_gt[trImgCntr]+'.png'),nrow=1,normalize=True,range=(-1, 1))
# if opt.reconWeight>0.0:
utils.save_image(image_input_tensors[trImgCntr],os.path.join(opt.trainDir,str(iteration),str(trImgCntr)+'_tr_gt_orig_'+labels_gt[trImgCntr]+'_ocr:None'+'.png'),nrow=1,normalize=True,range=(-1, 1))
utils.save_image(fake_sty_img[trImgCntr],os.path.join(opt.trainDir,str(iteration),str(trImgCntr)+'_tr_z_pred_'+labels_z_c[trImgCntr]+'_ocr:'+preds_str_fake_sty_img[trImgCntr]+'_sty:'+labels_gt[trImgCntr]+'.png'),nrow=1,normalize=True,range=(-1, 1))
if opt.cycleReconWeight>0.0:
utils.save_image(fake_recon_img[trImgCntr],os.path.join(opt.trainDir,str(iteration),str(trImgCntr)+'_tr_gt_cycle_pred_'+labels_gt[trImgCntr]+'_ocr:'+preds_str_fake_recon_img[trImgCntr]+'_sty:'+labels_gt[trImgCntr]+'.png'),nrow=1,normalize=True,range=(-1, 1))
except:
print('Warning while saving training image')
g_regularize = cntr % opt.g_reg_every == 0
# print('before g_regularize')
if g_regularize:
path_batch_size = max(1, opt.batch_size // opt.path_batch_shrink)
image_input_tensors, _, labels_gt, labels_z_c, labelSynthImg, synth_z_c = next(train_loader)
# labels_z_c, synth_z_c = next(text_loader)
# print(labels_z_c)
# image_input_tensors = image_input_tensors.to(device)
image_input_tensors = image_input_tensors[:path_batch_size].to(device)
# gt_image_tensors = image_input_tensors[:path_batch_size].detach() #exemplar word style image; training OCR
synth_z_c = synth_z_c[:path_batch_size].to(device)
labelSynthImg = labelSynthImg[:path_batch_size].to(device)
text_gt, length_gt = converter.encode(labels_gt[:path_batch_size], batch_max_length=opt.batch_max_length)
if opt.zAlone:
z_gt_code = None
style = None
else:
if opt.cEncode == 'mlp':
z_gt_code = cEncoder(text_gt)
elif opt.cEncode == 'cnn':
z_gt_code = cEncoder(labelSynthImg)
# print('after g_regularize cEncoder')
style = styleModel(image_input_tensors)
# print('after g_regularize styleModel')
if opt.noiseConcat or opt.zAlone:
style = mixing_noise(path_batch_size, opt.latent, opt.mixing, device, style)
else:
style = [style]
fake_gt_img, latents = genModel(style, z_gt_code, return_latents=True, input_is_latent=opt.input_latent)
path_loss, mean_path_length, path_lengths = g_path_regularize(
fake_gt_img, latents, mean_path_length
)
# print('after g_regularize genModel')
genModel.zero_grad()
if not opt.zAlone:
cEncoder.zero_grad()
styleModel.zero_grad()
weighted_path_loss = opt.path_regularize * opt.g_reg_every * path_loss
if opt.path_batch_shrink:
weighted_path_loss += 0 * fake_gt_img[0, 0, 0, 0]
weighted_path_loss.backward()
# print('after g_regularize backward')
if opt.grad_clip !=0.0:
torch.nn.utils.clip_grad_norm_(genModel.parameters(), opt.grad_clip) # gradient clipping with 5 (Default)
torch.nn.utils.clip_grad_norm_(cEncoder.parameters(), opt.grad_clip) # gradient clipping with 5 (Default)
torch.nn.utils.clip_grad_norm_(styleModel.parameters(), opt.grad_clip) # gradient clipping with 5 (Default)
optimizer.step()
mean_path_length_avg = (
reduce_sum(mean_path_length).item() / get_world_size()
)
accumulate(g_ema, genModel_module, accum)
log_avg_path_loss_val.add(path_loss)
log_avg_mean_path_length_avg.add(torch.tensor(mean_path_length_avg))
log_ada_aug_p.add(torch.tensor(ada_aug_p))
# print('after g_regularize')
if get_rank() == 0 or opt.testFlag:
if wandb and opt.wandb:
wandb.log(
{
"Generator": loss_avg_gen.val().item(),
"Discriminator": loss_avg_dis.val().item(),
"Train-UnSup-OCR-Loss": loss_avg_ocr_unsup.val().item(),
"Train-ImageRecon-Loss": loss_avg_img_recon.val().item(),
"Train-CycleRecon-Loss": loss_avg_cycle_recon.val().item(),
"Train-VGGPer-Loss": loss_avg_vgg_per.val().item(),
"Train-VGGSty-Loss": loss_avg_vgg_sty.val().item(),
"Train-VGGEmb-Loss": loss_avg_vgg_emb.val().item(),
"Train-r1_val": log_r1_val.val().item(),