-
Notifications
You must be signed in to change notification settings - Fork 2
/
train.py
1961 lines (1806 loc) · 111 KB
/
train.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import matplotlib
matplotlib.use('Agg')
import torch, os, sys, numpy as np, pprint, utils, shutil, argparse, random
import shapedata, imgutils, meshutils, graphicsutils
import logging, datetime, matplotlib
import matplotlib.pyplot as plt
from torch.nn import DataParallel
from renderer import SrRenderer
from model import CyclicGenRen
from losses import Cycle_1_loss_calculator, Cycle_2_loss_calculator
from vector_adversaries import *
from image_adversaries import *
from shape_adversaries import *
from utils import rfp, bool_string_type, AccumTimer
from options import *
from torch.utils.tensorboard import SummaryWriter
def main():
# Core parser arguments
parser = argparse.ArgumentParser(description='GenRen entry point')
parser.add_argument('options_choice', type = str,
help = 'Name of options set')
parser.add_argument('outpath', type = str,
help = 'Path to output dir')
parser.add_argument('--devices', type = str,
help = 'GPU device numbers (as comma separated list)', default='0')
# Autogenerated parser arguments based on options
movable_key_names = []
for key in all_keys():
if key.startswith('w_') or key.endswith('_lr') or key.endswith('_fp') or ('_lr_' in key): # float parameters
parser.add_argument('--' + key, type = float)
movable_key_names.append(key)
elif key in str_keys():
parser.add_argument('--' + key, type = str)
movable_key_names.append(key)
elif key in int_keys() or key.startswith('dim_'):
parser.add_argument('--' + key, type = int)
movable_key_names.append(key)
elif key in bool_keys():
parser.add_argument('--' + key, type = bool_string_type) # must pass true or false (the string)
movable_key_names.append(key)
args = parser.parse_args()
# Read inputs arguments
options = get_options( args.options_choice )
# Modify output path
true_outpath = os.path.join(options['out_dir_prepen'], args.outpath)
# Check: handle output existence
_folder_deletion = options['allow_overwrite']
_h_msg = "Output directory already exists (%s)" % true_outpath
if _folder_deletion: # Delete and re-create if present
if os.path.isdir(true_outpath): shutil.rmtree( true_outpath )
else: # Enforce the folder is not pre-existing
assert not os.path.isdir(true_outpath), _h_msg
os.makedirs(true_outpath)
### Set up logging ###
# Standard log file
logfile = os.path.join(true_outpath, 'genren.log')
root = logging.getLogger()
root.setLevel(logging.INFO)
hdlr = root.handlers[0]
fmt = logging.Formatter('%(message)s')
hdlr.setFormatter(fmt)
fh = logging.FileHandler(logfile)
fh.setLevel(logging.INFO)
fh.setFormatter(fmt)
root.addHandler(fh)
# Tensorboard setup
board_writer = SummaryWriter(log_dir = os.path.join(true_outpath, 'tb_log'),
filename_suffix = args.options_choice)
options['board_writer'] = board_writer
logging.info('Entering GenRen Main')
logging.info("Date & Time: %s", datetime.datetime.now().strftime("%Y-%m-%d %H:%M"))
utils.log_current_git_revision_safe()
logging.info('Option choice: %s', args.options_choice)
logging.info('Devices: %s', args.devices)
logging.info('Output path: %s', true_outpath)
logging.info('Num logging handlers: %d', len(root.handlers))
# Now that the true outpath has been used for tensorboard and the logger,
# Let's create an inner folder for the saved files
outdir_core = true_outpath
true_outpath = os.path.join(true_outpath, 'progress')
# Device handling
devices = [ torch.device('cuda:%s' % d) for d in args.devices.strip().split(',') ]
device_main = devices[0]
options['devices'] = devices
options['device_main'] = device_main
options['output_dir'] = true_outpath
options['output_dir_core'] = outdir_core
options['options_choice'] = args.options_choice
# Overwrite specified options with cmd line specified key
for key in movable_key_names:
in_arg = getattr(args, key)
if not in_arg is None:
curr_val = options[key]
logging.info( ('Altering base options for %s:' % key) + str(curr_val)
+ ' -> ' + str(in_arg))
options[key] = in_arg
logging.info('\nOPTIONS')
logging.info(optformat(options))
#-----------------------------------------------------------------------------------#
assert options['B_imgs'] == options['B_shapes'], "Currently, batch sizes must be equal"
assert options['pose_buffer_size'] >= options['B_shapes'], "Pose buffer should be as large as the batch"
IMSIZE = options['img_size']
NUM_PC_POINTS = options['n_pc_points'] # sampling from orig meshes
IMG_BATCH_SIZE = options['B_imgs']
SHAPE_BATCH_SIZE = options['B_shapes']
img_data_dir = options['img_data_dir']
shape_data_dir = options['shape_data_dir']
# Dataset specific settings
data_scale = options['data_scale']
R_angle = options['data_R_angle']
R_axis = options['data_R_axis']
# Initialize model
use_predefined_template = not ( options['template_path'] is None )
template_path = options['template_path']
if use_predefined_template:
assert not options['manual_template_UV'] is None, "Specify manual UV!"
assert options['manual_template_UV'] == template_path, "For BFF, use the same file for geom and uv!"
template, t_faces = meshutils.read_surface_mesh(template_path,
to_torch=True, subdivide=options['subdivide_template'])
template_scale = options['template_scale']
template_R_angle = options['template_R_angle']
template_R_axis = options['template_R_axis']
#template = tmesh.normalize(scale_divisor=SCALE, rotation=(R_axis, R_angle))
template = meshutils.norm_mesh(template, scale = template_scale)
template = meshutils.rotate(template_R_angle, template_R_axis, template)
template_mesh = (template, t_faces)
#learn_template = False
else:
assert options['manual_template_UV'] is None, "No manual UV!"
template_mesh = None
template_scale = None
#learn_template = True
learn_template = options['learn_template']
# Initialize renderer
renderer = SrRenderer(IMSIZE).to(device_main)
renderer.set_eye( torch.FloatTensor(options['fixed_eye']) )
renderer.move_at_up(device_main)
# Initialize datasets and generate dataloaders
shapedata_type = options['shape_data_type'].strip().lower()
if shapedata_type == 'obj': shapedata_type = shapedata.ObjToPcsNormalsDataset
elif shapedata_type == 'pn': shapedata_type = shapedata.DirectPointsAndNormals
else: raise ValueError('Unknown shape dataset type ' + options['shape_data_type'])
shape_dataset = shapedata_type(shape_data_dir,
NUM_PC_POINTS,
duplicate = options['shape_data_dup'],
pre_transform = True,
subset_num = options['subset_num'],
scale = data_scale,
rot_angle = R_angle,
rot_axis = R_axis)
if options['preload_img_data']:
img_data_class = imgutils.SinglePreloadedDirImageDataset
else:
img_data_class = imgutils.SingleDirImageDataset
img_dataset = img_data_class(img_data_dir,
use_alpha = options['use_alpha'],
resize = IMSIZE,
load_gt_file = options['USE_GT'],
num_fixed_to_store = options['B_imgs'],
take_subset = options['img_data_subset'] )
shape_dataloader = shape_dataset.get_infinite_dataloader(SHAPE_BATCH_SIZE)
img_dataloader = img_dataset.get_infinite_dataloader(IMG_BATCH_SIZE)
# Create the cyclic genren model
cyclic_genren = CyclicGenRen(
dim_xi_T = options['dim_xi_T'],
dim_xi_p = options['dim_xi_p'],
dim_lat_pert = options['dim_lat_pert'],
dim_backbone = options['dim_backbone'],
num_impulses = options['nts'],
num_hypotheses = options['num_pose_hypotheses'],
use_alpha = options['use_alpha'],
options = options,
template_mesh = template_mesh,
learn_template = learn_template,
parallelize = devices,
rotation_representation_mode = options['rrm'],
FDR_pixel_distribution = img_dataset.unmasked_pixel_set(),
renderer = renderer )
n_template_verts = cyclic_genren.nV
cyclic_genren = cyclic_genren.to(device_main)
##### Initialize critics #####
#-------------------------------------------------------------------------------------------------------------------#
logging.info('Initializing critics')
#>> Image critic <<#
#img_critic = ImageAdversarySimple(img_size=IMSIZE).to(device)
if options['img_critic_type'] == 'lsgan':
logging.info('Img critic: SLSGAN')
img_critic = ImageAdversarySimpleLSGAN(critic_arch = options['img_critic_arch']) # 'spec'
elif options['img_critic_type'] == 'wgangp':
logging.info('Img critic: WGAN-GP')
img_critic_gp_pen_weight = options['img_critic_gp_pen_weight_fp']
img_critic = ImageAdversarySimpleWganGp(lambda_weight = img_critic_gp_pen_weight,
drift_mag_weight = 0.01,
critic_type = options['wgan_img_mini_critic'] )
#img_critic = ImageAdversarySimpleHingeGan()
#img_critic = ImageAdversarySimpleWganGp().to(device)
#>> Shape Critic <<#
#shape_critic = ComTwoStageShapeAdversary(n_template_verts, options['dim_lat_pert'])
#shape_critic = TwoStageShapeAdversary(n_template_verts, options['dim_lat_pert'])
if options['shape_critic_type'].strip().lower() == 'single_stage':
logging.info('Using single stage latent shape critic (dim(v) = %d)' % options['dim_lat_pert'])
shape_critic = SingleStageShapeAdversary(options['dim_lat_pert'],
(512, 256, 128),
wgan_gp_pen_weight = 10,
drift_mag_weight = 0.01)
elif options['shape_critic_type'].strip().lower() == 'com':
logging.info('Using single stage latent shape critic (dim(v) = %d, |V| = %d)' %
(options['dim_lat_pert'], n_template_verts))
shape_critic = ComSingleStageShapeAdversary(options['dim_lat_pert'],
n_template_verts,
(512, 256, 128),
wgan_gp_pen_weight = 10,
drift_mag_weight = 0.01)
#shape_critic = FcTemplatePositionShapeAdversary(n_template_verts)
#shape_critic = DglGcnSimpleMeshAdversary().to(device)
#>> Critic on Sampled Poses <<#
# Pose critic (for cycle 1, matching cycle 2)
_pose_buffer_size = options['pose_buffer_size'] # 100
logging.info('Using Sinkhorn pose buffer critic (|B| = %d)' % _pose_buffer_size)
pose_critic = Wasserstein3dPoseAdversary(buffer_size = _pose_buffer_size)
#>> Latent texture critic <<#
# Latent texture critic (pushing cy2 inference to N(0,I))
if options['vae_for_xi_T']:
xi_T_critic = None
else:
if options['use_SWD_loss_for_xi_T']:
_swd_nprojs = options['num_swd_projections_xi_T']
logging.info('Using SWD critic for xi_T (n_projs = %d)' % _swd_nprojs)
xi_T_critic = StdNormalSlicedWassersteinMatcher(num_projections = _swd_nprojs,
expected_dim = options['dim_xi_T'])
else:
logging.info('Using WGAN-GP critic for xi_T')
xi_T_critic = VectorAdversaryLinWGANGP(options['dim_xi_T'], (512, 256, 128),
wgan_gp_pen_weight=10.0, drift_mag_weight=0.01)
#_swd_nprojs = 64
#logging.info('Using SWD critic for xi_T (n_projs = %d)' % _swd_nprojs)
#xi_T_critic = StdNormalSlicedWassersteinMatcher(num_projections = _swd_nprojs)
#>> Texture critic <<#
# Decoded texture adversary (pushing cy1 outputs to look like cy2 inferences)
if options['texture_critic_arch'] == 'lsgan':
assert False
logging.info('Using SLSGAN for texture critic')
texture_critic = VectorAdversaryLin(cyclic_genren.nV * 3, (512, 256, 128))
elif options['texture_critic_arch'] == 'wgan':
texture_critic_gp_pen_weight = options['tex_critic_gp_pen_weight_fp']
#logging.info('Using WGANGP for texture critic')
fixed_batch_graph = cyclic_genren.generate_featureless_dgl_template_graph_batch(
SHAPE_BATCH_SIZE, as_dglb=True)
# Critic on the KDE histogram of the texture colours
#texture_critic = WGANGPDiscriminator64(inchannels = 3)
# texture_critic = ImageAdversarySimpleWganGp(lambda_weight = texture_critic_gp_pen_weight,
# drift_mag_weight = 0.01,
# inchannels = 3,
# critic_type = 'full' )
texture_critic = UvTextureImagePlus2dHistoCritic(
## Histogram critic settings
num_template_vertices = cyclic_genren.nV,
hidden_sizes = (512, 256, 128),
batch_size = SHAPE_BATCH_SIZE,
## UV texture image
inchannels = 3,
critic_type = 'full',
## Shared parameters
wgan_gp_pen_weight = texture_critic_gp_pen_weight,
drift_mag_weight = 0.01,
## Meta-parameters
texture_critic_type = options['texture_critic_type'],
options = options,
)
# if options['texture_critic_type'].lower() == 'histo': # global
# logging.info('Using global texture histogram for texture critic (WGANGP)')
# texture_critic = GlobalHistogramFixedSamplesLinWGANGP(
# num_template_vertices = cyclic_genren.nV,
# hidden_sizes = (512, 256, 128),
# wgan_gp_pen_weight = texture_critic_gp_pen_weight,
# drift_mag_weight = 0.01,
# num_fixed_samples = options['num_histo_samples_per_dim']**3)
# # Local patch critic on the mesh graph texture values
# elif options['texture_critic_type'].lower() == 'graph_patch': # local
# logging.info('Using local graph patch critic (WGANGP)')
# fixed_batch_graph = cyclic_genren.generate_featureless_dgl_template_graph_batch(
# SHAPE_BATCH_SIZE, as_dglb=True)
# texture_critic = TextureGraphAdversaryWGANGP(
# per_node_input_dim = 3,
# hidden_dims = (16, 32, 64), # hidden nodal feature dimensionalities
# GSB = fixed_batch_graph,
# wgan_gp_pen_weight = texture_critic_gp_pen_weight,
# drift_mag_weight = 0.01 )
# elif options['texture_critic_type'].lower() == 'global+local':
# logging.info('Using both global texture histogram and local graph patch processor for texture critic (WGANGP)')
# texture_critic = GlobalAndLocalTextureCritic(
# input_dim = 3,
# num_template_vertices = cyclic_genren.nV,
# fixed_graph_structure_batch = fixed_batch_graph,
# hidden_sizes_local = (16, 32, 64),
# hidden_sizes_global = (512, 256, 128),
# num_fixed_samples_global = options['num_histo_samples_per_dim'] ** 3,
# wgan_gp_pen_weight = texture_critic_gp_pen_weight,
# drift_mag_weight = 0.01 )
# elif options['texture_critic_type'].lower() == 'vec+histo':
# logging.info('Using vec+histo texture critic')
# texture_critic = VecAndHistoVecTextureCritic(
# input_dim = 3,
# num_template_vertices = cyclic_genren.nV,
# fixed_graph_structure_batch = fixed_batch_graph,
# hidden_sizes_local = None, # (16, 32, 64),
# hidden_sizes_global = (512, 256, 128),
# num_fixed_samples_global = options['num_histo_samples_per_dim'] ** 3,
# wgan_gp_pen_weight = texture_critic_gp_pen_weight,
# drift_mag_weight = 0.01 )
# # Critic on the overall vector (unfolded) of the texture
# elif options['texture_critic_type'].lower() == 'vector':
# logging.info('Using unfolded texture vector critic for texture critic (WGANGP)')
# texture_critic = VectorAdversaryLinWGANGP(cyclic_genren.nV * 3, (512, 256, 128),
# wgan_gp_pen_weight = texture_critic_gp_pen_weight,
# drift_mag_weight = 0.01)
# else:
# raise ValueError('Unknown texture critic type')
### </ End critic initializations /> ###
#-------------------------------------------------------------------------------------------------------------------#
# Parallelize critics
img_critic = DataParallel( img_critic, device_ids=devices ).to(device_main)
shape_critic = DataParallel( shape_critic, device_ids=devices ).to(device_main)
pose_critic = DataParallel( pose_critic, device_ids=devices ).to(device_main)
if not xi_T_critic is None:
xi_T_critic = DataParallel( xi_T_critic, device_ids=devices ).to(device_main)
#xi_p_critic = DataParallel( xi_p_critic, device_ids=devices ).to(device_main)
texture_critic = DataParallel( texture_critic, device_ids=devices ).to(device_main)
# Run training
NAN_CHECK = False # False #True
with torch.autograd.set_detect_anomaly(NAN_CHECK):
run_training(cyclic_genren,
renderer,
img_dataloader,
shape_dataloader,
img_critic,
shape_critic,
pose_critic,
xi_T_critic,
None, #xi_p_critic,
texture_critic,
options)
#------------------------------------------------------------------------------#
def run_training(model,
renderer,
img_dataloader,
shape_dataloader,
img_critic,
shape_critic,
pose_critic,
xi_T_critic,
xi_p_critic,
texture_critic,
options):
# Unpack arguments
n_gen_iters = options['n_gen_iters']
img_critic_iters_per_gen_iter = options['img_critic_iters_per_gen_iter']
cy2_critics_update_per_gen_iter = options['cy2_critics_update_per_gen_iter']
print_every = options['print_every']
device_main = options['device_main']
save_imgs_every = options['save_imgs_every']
USE_GT = options['USE_GT']
thresh = options['init_gt_iters']
cham_only_iters = options['chamfer_only_iters']
stage_2_pretrain_iters = options['stage_2_pretrain_iters']
outdir = options['output_dir']
outdir_core = options['output_dir_core']
B = options['B_imgs']
NH = options['num_pose_hypotheses']
num_frozen_mesh_ae_iters = options['freeze_mesh_ae_iters']
mesh_ae_load_path = options['mesh_ae_load_path']
mode_1_iters = options['mode_1_iters']
mode_2_iters = options['mode_2_iters']
cy2_annealing_period = options['cy2_annealing_period']
board_writer = options['board_writer']
options_choice = options['options_choice']
run_rerenders = options['run_rerenderings']
if options['w_reren_adv_loss'] > 1e-8:
assert run_rerenders
assert options['shape_critic_updates'] <= cy2_critics_update_per_gen_iter
assert options['shape_critic_updates'] >= 1
_pt_its = n_gen_iters - cham_only_iters - stage_2_pretrain_iters - mode_1_iters - mode_2_iters
S = '\nTraining Phases (Total iters: %d)\n' % n_gen_iters
S += ' (a) Mesh Autoencoder pretraining: %d iters\n' % cham_only_iters
S += ' (b) Domain randomized pretraining: %d iters\n' % stage_2_pretrain_iters
S += ' (c) Mode I: %d iters (cy2 annealing: %d)\n' % (mode_1_iters, cy2_annealing_period)
S += ' (d) Mode II: %d iters\n' % mode_2_iters
S += ' (e) Mode III: %d iters\n' % _pt_its
logging.info(S)
if not USE_GT:
thresh = 0
else:
logging.info('GT Present')
thresh += cham_only_iters
### Loss functions ###
# S -> I
Cy1_loss = Cycle_1_loss_calculator(V = model.template_V,
E = model.template_E,
F = model.template_F,
options = options
).to(device_main) #
# I -> S
Cy2_loss = Cycle_2_loss_calculator(V = model.template_V,
E = model.template_E,
F = model.template_F,
options = options,
mrl = Cy1_loss.get_mrl() # Avoid extra precomputations
).to(device_main) #
# Additional initializations
logging.info('Optimization preparation')
rot_loss_function = graphicsutils.MinAngleComposedRotationLoss()
n_pose_critic_params = len(list(pose_critic.parameters()))
n_xi_T_critic_params = 0 if xi_T_critic is None else len(list(xi_T_critic.parameters()))
## Optimizers ##
# SAGAN betas = (0, 0.9), default betas = (0.9, 0.999)
#BETAS = options['betas'] # (0.9, 0.99)
BETAS = (options['beta1_fp'], options['beta2_fp'])
gen_wd = 1e-6 # Generator weight decay
opter = lambda p, lr, wd: torch.optim.Adam(p, lr=lr, weight_decay=wd, betas=BETAS)
img_critic_optimizer = opter(img_critic.parameters(), lr = options['imc_lr'], wd=1e-3)
shape_critic_optimizer = opter(shape_critic.parameters(), lr = options['shc_lr'], wd=1e-3)
if n_pose_critic_params > 0:
pose_critic_optimizer = opter(pose_critic.parameters(), lr = options['xip_lr'], wd=1e-6)
#xi_p_critic_optimizer = opter(xi_p_critic.parameters(), lr=options['xip_lr'])
if n_xi_T_critic_params > 0:
xi_T_critic_optimizer = opter(xi_T_critic.parameters(), lr = options['xit_lr'], wd=1e-3)
texture_critic_optimizer = opter(texture_critic.parameters(), lr = options['C_lr'], wd=1e-3)
logging.info('Initialized optimizers')
# CPTC critic
if options['use_adversarial_cptc']:
cptc_critic = RotationPredictorRN20().to(device_main)
cptc_adversary_optimizer = opter(cptc_critic.parameters(), lr=0.0005, wd=1e-6)
else:
cptc_critic = None
### Function Definitions ###
# Predefine the image critic update
def run_img_critic_turn(gen_iter, include_fdr_batch, fake_gen_imgs, real_imgs, rerendered_real_images, P): #
"""
Runs an update for the image critic.
Can only run ONE iteration.
P = pose probabilities
cy2_chance: probability of replacing I_real with shape2img(img2shape(I_real))
"""
cy2_chance = options['img_critic_use_cy2_renders_chance_fp']
if cy2_chance > 1e-6:
# Mask is one if we perform replacement, zero if we keep the original
mask = (torch.rand(B) < cy2_chance).float().view(B,1,1,1).to(real_imgs.device)
# We replace the corresponding true img batch member with its reconstruction
#ic_images_f, P = model.run_cycle_2(, renderer, renders_and_probs_only=True)
ic_images = real_imgs
ic_images_f = rerendered_real_images
B_NH, C, H, W = ic_images_f.shape
assert B_NH == B * NH
ic_images_f = ic_images_f.reshape(B,NH,C,H,W).gather(
dim = 1,
index = P.detach().argmax(dim=1).view(B,1,1,1,1).expand(-1,-1,C,H,W)
).squeeze(1).detach()
ic_images = ( ic_images * (1.0 - mask) + ic_images_f * mask )
else:
ic_images = real_imgs
# Compute loss and update
img_critic_optimizer.zero_grad()
ic_loss = img_critic(I_fake=fake_gen_imgs.detach(),
I_real=ic_images.detach(),
for_gen=False).mean()
ic_loss.backward()
# if include_fdr_batch: #
# fdr_loss = img_critic(I_fake = renders, I_real=fdr_renders, for_gen=False).mean()
# fdr_loss.backward()
img_critic_optimizer.step()
return ic_loss
# Predefine the image critic update
def run_img_critic_turn_old(gen_iter, include_fdr_batch): #
"""
Runs an update for the image critic.
cy2_chance: probability of replacing I_real with shape2img(img2shape(I_real))
"""
cy2_chance = options['img_critic_use_cy2_renders_chance_fp']
ic_loss = torch.tensor([0.0]).to(device_main)
for img_critic_update in range(img_critic_iters_per_gen_iter):
if gen_iter < thresh: return ic_loss
# Sample image data
if USE_GT: ic_images, gt_R, gt_t = img_dataloader.sample()
else: ic_images = img_dataloader.sample()
ic_images = ic_images.to(device_main)
# Sample shape data
ic_shapes, ic_normals = shape_dataloader.sample()
#_, ic_shapes = shape_dataloader.sample()
ic_shapes = ic_shapes.to(device_main)
ic_normals = ic_normals.to(device_main)
# Generate images
with torch.no_grad():
# Generate fakes
renders = model.shape_to_image(ic_shapes, ic_normals, renderer)[0].detach()
if include_fdr_batch:
assert False
fdr_renders = model.run_domain_randomized_cycle_1(ic_shapes,
ic_normals, renderer, learned_tex=False)[0]
# If we are doing ANY replacements, enter the mixup, else don't bother (it's expensive...)
if cy2_chance > 1e-6:
# Mask is one if we perform replacement, zero if we keep the original
mask = (torch.rand(B) < cy2_chance).float().view(B,1,1,1).to(renders.device)
# We replace the corresponding true img batch member with its reconstruction
ic_images_f, P = model.run_cycle_2(ic_images, renderer, renders_and_probs_only=True)
B_NH, C, H, W = ic_images_f.shape
assert B_NH == B * NH
ic_images_f = ic_images_f.reshape(B,NH,C,H,W).gather(dim = 1,
index = P.detach().argmax(dim=1).view(B,1,1,1,1).expand(-1,-1,C,H,W)
).squeeze(1).detach()
ic_images = ( ic_images * (1.0 - mask) + ic_images_f * mask )
# Compute loss and update
img_critic_optimizer.zero_grad()
ic_loss = img_critic(I_fake=renders, I_real=ic_images, for_gen=False).mean()
ic_loss.backward()
if include_fdr_batch: #
fdr_loss = img_critic(I_fake = renders, I_real=fdr_renders, for_gen=False).mean()
fdr_loss.backward()
img_critic_optimizer.step()
return ic_loss
# Predefine the domain randomized Cy1 loss computation and update
DR_full_rand_iters = 0
DR_LR_iters = 0
def compute_domain_randomized_quantities(cy1_shapes, cy1_normals, learned_tex=False):
"""
Maps input shapes (PC + normals) to generated renders (and intermediates) using domain randomized
poses and (optionally) textures
"""
nonlocal DR_LR_iters; nonlocal DR_full_rand_iters
if learned_tex: DR_LR_iters += 1
else: DR_full_rand_iters += 1
( renders, # Generated image renders
texture, # Random texture (from xi_T OR from random)
V_new, # Deformed nodal positions (incl. Euclidean transform)
V_new_pe, # Deformed template (before Euclidean transform)
V_new_ints, # Intermediate deformations (S -> I)
delta, # Nodal perturbation vector
R, t, # Random Euclidean transform (pose) [input]
v, # Random latent deformation [input]
M_hat, # Reconstructed mesh [output]
M_hat_pe, # Reconstructed mesh before Euclidean transform [output]
M_hat_ints, # Intermediate deformations reconstruction (I -> S)
xi_T_hat, # Inferred latent texture
decoded_texture, # Decoded reconstructed texture
v_hat, # Inferred latent deformation
R_hat, # Inferred rotation
t_hat, # Inferred translation
r_hat, # Inferred intermediate rotation representation
delta_hat, # Inferred perturbation
pose_probs, # Pose probabilities from image inference
_xi_T, # initial latent texture [None if not learned_tex]
mu_v, logvar_v,
dr_texture_img_hat
) = model.run_domain_randomized_cycle_1(cy1_shapes, cy1_normals, renderer, learned_tex)
# ACPTC generator loss calculations
if options['use_adversarial_cptc']:
_c2acptc_inds = pose_probs.detach().argmax(dim=1)
B = _c2acptc_inds.shape[0]
# Best rotations
acptc_best_hyp_Rmats = R_hat.gather( # B x nH x 3 x 3 -> B x 3 x 3
dim = 1,
index = _c2acptc_inds.view(B,1,1,1).expand(-1, -1, 3, 3)
).squeeze(1)
B, nH, _nIC, H, W = dr_texture_img_hat.shape
acptc_best_inferred_texture_images = dr_texture_img_hat.gather(
dim = 1, # B x nH x 3 x H x W
index = _c2acptc_inds.view(B,1,1,1,1).expand(-1, -1, 3, H, W)
).squeeze(1)
# Compute negative prediction error -> min this to get max prediction error
# Do NOT detach the tex images: we need to backprop through them
cptc_adv_genloss = -1.0 * cptc_critic.loss(
TI = acptc_best_inferred_texture_images,
R_true = acptc_best_hyp_Rmats.detach() ).mean()
else:
cptc_adv_genloss = None
#
total_loss, loss_dict = Cy1_loss.domain_randomized_loss( #
S = V_new_pe,
S_hat = M_hat_pe,
orig_M = cy1_shapes,
orig_normals = cy1_normals,
v = v,
v_hat = v_hat,
renders = renders,
delta = delta,
S_ints = V_new_ints,
S_hat_ints = M_hat_ints,
R = R,
t = t,
R_hat = R_hat,
t_hat = t_hat,
pose_probs = pose_probs,
input_texture = texture,
output_texture = decoded_texture,
_xi_T = _xi_T if learned_tex else None,
xi_T_hat = xi_T_hat,
img_critic = img_critic if learned_tex else None,
mu_v = mu_v,
logvar_v = logvar_v,
adv_cptc_loss = cptc_adv_genloss )
return ( total_loss, loss_dict, renders,
(R_hat, t_hat, v_hat, delta_hat, xi_T_hat, pose_probs, V_new_pe) )
# Partial currying of the domain randomized cycle 1 computation with learned texture
compute_LT_DR_quantities = lambda s, n: compute_domain_randomized_quantities(s, n, learned_tex=True) # LTDR
compute_FDR_quantities = lambda s, n: compute_domain_randomized_quantities(s, n, learned_tex=False) # FDR
def run_domain_randomized_update(cy1_shapes, cy1_normals, opt,
learned_tex=False, ret_for_ren=False):
"""
Performs a gradient descent step for the domain-randomized cycle 1
"""
(total_loss, loss_dict, renders,
(R_hat, t_hat, v_hat, delta_hat, xi_T_hat, pose_probs, V_new_pe)
) = compute_domain_randomized_quantities(cy1_shapes, cy1_normals, learned_tex)
opt.zero_grad()
total_loss.backward()
opt.step()
if ret_for_ren:
return ( total_loss, loss_dict, renders,
(R_hat, t_hat, v_hat, delta_hat, xi_T_hat, pose_probs) )
return total_loss, loss_dict, renders
# Predefine the Cy1 loss computations -> BOTH pose and texture are learned
def compute_cycle_1_quantities(cy1_shapes, cy1_normals, duplicated_half = False, mixed_reren_loss = False):
"""
Classical cycle 1 computations (S -> I -> S)
"""
# Run cycle 1 on input shapes
( cy1_renders, # Generated image renders
cy1_texture, # Random texture
cy1_V_new, # Deformed nodal positions
cy1_V_new_pe, # Deformed template (before Euclidean transform)
cy1_V_new_ints, # Deformed template intermediates during impulse perturbations
cy1_delta, # Nodal perturbation vector
cy1_R, # Random Euclidean rotation (pose) [input]
cy1_t, # Random Euclidean translation (pose) [input]
cy1_r, # Random rotation from sample in intermed representation (pose) [input]
cy1_v, # Random latent deformation [input]
cy1_xi_p, # Random latent pose [input]
cy1_xi_T, # Random latent texture [input]
cy1_M_hat, # Reconstructed mesh [output]
cy1_M_hat_pe, # Reconstructed mesh [output] (before R,t applied)
cy1_M_hat_ints, # Reconstructed mesh impulse intermediates [output]
cy1_xi_p_hat, # Inferred latent pose
cy1_xi_T_hat, # Inferred latent texture
cy1_C_dec_tex, # Inferred reconstructed complete texture
cy1_v_hat, # Inferred latent deformation
cy1_R_hat, # Inferred rotation
cy1_t_hat, # Inferred translation
cy1_r_hat, # Inferred rotation in 6D representation (pose)
cy1_delta_hat, # Inferred perturbation
pose_probs, # Inferred pose probabilities (loss weights)
mu_v, logvar_v, # VAE approx posterior param outputs
sampled_texture_image, # Sampled texture image
recon_texture_image, # Reconstructed texture image
) = model.run_cycle_1(cy1_shapes, cy1_normals, renderer,
duplicated_xi_T_half_batch = duplicated_half)
# ACPTC generator loss calculations
if options['use_adversarial_cptc']:
_c2acptc_inds = pose_probs.detach().argmax(dim=1)
B = _c2acptc_inds.shape[0]
# Best rotations
acptc_best_hyp_Rmats = cy1_R_hat.gather( # B x nH x 3 x 3 -> B x 3 x 3
dim = 1,
index = _c2acptc_inds.view(B,1,1,1).expand(-1, -1, 3, 3)
).squeeze(1)
B, nH, _nIC, H, W = recon_texture_image.shape
acptc_best_inferred_texture_images = recon_texture_image.gather(
dim = 1, # B x nH x 3 x H x W
index = _c2acptc_inds.view(B,1,1,1,1).expand(-1, -1, 3, H, W)
).squeeze(1)
# Compute negative prediction error -> min this to get max prediction error
# Do NOT detach the tex images: we need to backprop through them
cptc_adv_genloss = -1.0 * cptc_critic.loss(
TI = acptc_best_inferred_texture_images,
R_true = acptc_best_hyp_Rmats.detach() ).mean()
else:
cptc_adv_genloss = None
# Compute the re-rendering mixture loss
if mixed_reren_loss:
assert duplicated_half
B = cy1_M_hat.shape[0]
coin = random.randint(0, 1)
inds = pose_probs.detach().argmax(dim = 1)
mls = cy1_C_dec_tex.shape # B x nH x |V| x 3
best_cy1_C_dec_tex = cy1_C_dec_tex.gather(dim = 1,
index = inds.view(B,1,1,1).expand(-1,-1,mls[2],mls[3])
).squeeze(1)
best_cy1_M_hat = cy1_M_hat.gather(dim = 1,
index = inds.view(B,1,1,1).expand(-1,-1,mls[2],mls[3])
).squeeze(1)
if coin == 0:
M_E_half = best_cy1_M_hat[0 : B // 2].detach()
texture_half = best_cy1_C_dec_tex[B // 2 : ]
target_render = cy1_renders[0 : B // 2]
else:
M_E_half = best_cy1_M_hat[B // 2 : ].detach()
texture_half = best_cy1_C_dec_tex[0 : B // 2]
target_render = cy1_renders[B // 2 : ]
new_rens = model.render(M_E_half, texture_half, renderer)
mixed_cy1_rerens_comparators = (new_rens, target_render)
else:
mixed_cy1_rerens_comparators = None
# Compute the loss associated to cycle 1
cy1_L, cy1_L_dict = Cy1_loss(gen_iter, cy1_V_new_pe, cy1_M_hat_pe, cy1_shapes, cy1_normals,
img_critic, cy1_xi_p, cy1_xi_p_hat,
cy1_xi_T, cy1_xi_T_hat, cy1_v, cy1_v_hat,
cy1_renders, cy1_delta, cy1_V_new_ints, cy1_M_hat_ints,
cy1_R, cy1_t, cy1_R_hat, cy1_t_hat, pose_probs,
pose_critic, cy1_r, cy1_r_hat,
input_texture = cy1_texture,
output_texture = cy1_C_dec_tex,
mu_v = mu_v, logvar_v = logvar_v,
texture_critic = texture_critic,
sampled_texture_image = sampled_texture_image,
reconstructed_texture_image = recon_texture_image,
mixed_cy1_rerens_comparators = mixed_cy1_rerens_comparators,
adv_cptc_loss = cptc_adv_genloss
)
cy1_quantities_oth = ( cy1_v_hat, cy1_R_hat, cy1_t_hat, cy1_C_dec_tex,
cy1_delta_hat, pose_probs, cy1_M_hat_pe,
cy1_r_hat, cy1_texture, sampled_texture_image, recon_texture_image )
return cy1_L, cy1_L_dict, cy1_renders, cy1_quantities_oth
# Function for weighted combined DR_full + DR_learned_tex, used in pretraining stage 2
def run_combined_cy1_DR_update(rtex_weight, ltex_weight):
"""
Performs a gradient update for *both* the standard cycle 1 and the domain-randomized version.
rtex: random texture weight (DR)
ltex: learned texture (standard cy1)
"""
cy1_shapes, cy1_normals = shape_dataloader.sample()
cy1_shapes = cy1_shapes.to(device_main)
cy1_normals = cy1_normals.to(device_main)
gen_optimizer.zero_grad()
# Run the PTS2 Domain-randomized cycle 1 (random_texture) and send the weighted loss backward
(rtex_total_loss, rtex_loss_dict, rtex_renders, rtex_oth
) = compute_domain_randomized_quantities(cy1_shapes, cy1_normals, learned_tex=False)
rtex_total_loss = rtex_total_loss * rtex_weight
rtex_total_loss.backward() # Clear the graph
# Run the PTS2 Domain-randomized cycle 1 (learned texture) and send the weighted loss backward
(ltex_total_loss, ltex_loss_dict, ltex_renders, ltex_oth
) = compute_domain_randomized_quantities(cy1_shapes, cy1_normals, learned_tex=True)
ltex_total_loss = ltex_total_loss * ltex_weight
ltex_total_loss.backward() # Clear the graph
# Step the optimizer
gen_optimizer.step()
# Return everything
return ( (rtex_total_loss, rtex_loss_dict, rtex_renders, rtex_oth),
(ltex_total_loss, ltex_loss_dict, ltex_renders, ltex_oth) )
def get_combined_FDR_and_fullCy1_quantities(w_full_cy1, w_fdr_cy1, cy1_shapes, cy1_normals):
"""
Run (a) the full Cy1 and (b) the fully DR Cy1.
Performs the backwards in here for each, but no gradient step.
"""
# Run the full cycle 1 with immediate backward (avoid graph storage)
cy1_L, cy1_L_dict, cy1_renders, cy1_quantities_oth = compute_cycle_1_quantities(cy1_shapes, cy1_normals)
cy1_L = w_full_cy1 * cy1_L
cy1_L.backward()
# Run the FDR (fully domain randomized) cycle, with backward
cy1_shapes, cy1_normals = shape_dataloader.sample()
cy1_shapes = cy1_shapes.to(device_main)
cy1_normals = cy1_normals.to(device_main)
( total_loss, loss_dict, renders,
fdr_q #(R_hat, t_hat, delta_hat, xi_T_hat, pose_probs)
) = compute_FDR_quantities(cy1_shapes, cy1_normals)
total_loss = w_fdr_cy1 * total_loss
total_loss.backward()
# Return the results of both cycles
return ( (cy1_L, cy1_L_dict, cy1_renders, cy1_quantities_oth),
(total_loss, loss_dict, renders, fdr_q) )
def get_combined_LTDR_and_fullCy1_quantities(w_full_cy1, w_ltdr_cy1, cy1_normals):
"""
Run (a) the full Cycle 1 and (b) the learned texture (LT) + random pose DR cycle.
Returns (cy1_full_outs, LTDR_outs)
"""
# Run the full cycle 1 with immediate backward (avoid graph storage)
cy1_L, cy1_L_dict, cy1_renders, _ = compute_cycle_1_quantities(cy1_shapes, cy1_normals)
cy1_L = w_full_cy1 * cy1_L
cy1_L.backward()
# Run the LTDR (learned texture domain randomized) cycle, with backward
cy1_shapes, cy1_normals = shape_dataloader.sample()
cy1_shapes = cy1_shapes.to(device_main)
cy1_normals = cy1_normals.to(device_main)
( total_loss, loss_dict, renders,
ltdr_q #(R_hat, t_hat, delta_hat, xi_T_hat, pose_probs)
) = compute_LT_DR_quantities(cy1_shapes, cy1_normals)
total_loss = w_ltdr_cy1 * total_loss
total_loss.backward()
# Return the results of both cycles
return ( (cy1_L, cy1_L_dict, cy1_renders),
(total_loss, loss_dict, renders, ltdr_q) )
###< Finished function definitions >###
#-------------------------------------#
# If required, preload the mesh AE model
if not (mesh_ae_load_path is None):
logging.info('Loading mesh AE ' + mesh_ae_load_path)
model.load_mesh_ae(mesh_ae_load_path)
# >>> Training iterations loop <<< #
### Setup pretraining stages ###
pretraining = True if cham_only_iters + stage_2_pretrain_iters > 0 else False
pt_stage = 1 if cham_only_iters > 0 else 2
frozen_mesh_ae = False
frozen_iters_so_far = 0
cy2_loss_only_max_iters = options['cy2_loss_only_iters']
cy2_loss_only = cy2_loss_only_max_iters > 0 # Track current state/mode
cy2_loss_only_iters = 0 # Track number of cy2-only iters
# Annealing of domain randomized pretraining probabilities
START_PROB_LT = options['pts2_lt_start_prob'] # prob of using learned texturer at start of DR training
END_PROB_LT = options['pts2_lt_final_prob'] # prob of using learned texturer at end of DR training
# def current_prob_and_prog(c_iter):
#""" Compute probability of choosing a batch from cycle 1 learned and DR (when annealing in the former) """
# prob -> interpolates between start and end (depending on chosen end-points)
# prob is the relative weight on the "learned texture" pretrained case
# prog = (c_iter - cham_only_iters + 1) / stage_2_pretrain_iters
# return np.clip( # prog = 0 --> start, prog = 1 --> end
# prog * END_PROB_LT + (1.0 - prog) * START_PROB_LT,
# a_min=0.001, a_max=0.999 ), prog
### Setup main training stages ###
main_training_mode = 1
mode_1_training_iterations = 0
mode_2_training_iterations = 0
mode_3_training_iterations = 0
# Annealing of Mode II balance (full cy1 vs FDR cy1)
def current_cy1_balancer(m2_iters_so_far):
""" Compute convex combination loss weight balance between full and FDR cy1 """
progress = (m2_iters_so_far / options['mode_2_iters'])
start = 0.01 # Relative weight on full cycle 1 [start]
end = 0.99 # As above, at end
full_weight = start * (1.0 - progress) + progress * end
oth_weight = 1.0 - full_weight
return full_weight, oth_weight
# Annealing of cy2 loss weights, starting in Mode I
def cy2_total_loss_weight_and_prog(i):
""" Compute the loss weight on the cy2 loss, when annealing it in """
if options['cy2_annealing_period'] == 0:
return 1.0, 1.0 # No annealing
progg = (i - cham_only_iters - stage_2_pretrain_iters) / options['cy2_annealing_period']
init_w = options['initial_cy2_weight']
final_w = 1.0
return np.clip( # prog = 0 --> start, prog = 1 --> end
progg * final_w + (1.0 - progg) * init_w,
a_min=0.001, a_max=0.999 ), progg
# The generator optimizer depends on the initial training stage
if pretraining:
if pt_stage == 1: # cham_only pretraining
logging.info('Resetting optimizer [pt1] (lr = %f, gamma = %f, milestones = %s)'
% (options['gen_lr_pt1'],options['gen_lr_pt1_gamma'],str(options['gen_lr_pt1_ms'])) )
gen_optimizer = opter(model.parameters(), lr=options['gen_lr_pt1'], wd=gen_wd)
pt_1_scheduler = torch.optim.lr_scheduler.MultiStepLR(
gen_optimizer, options['gen_lr_pt1_ms'],
gamma = options['gen_lr_pt1_gamma'])
elif pt_stage == 2: # DR-based pretraining
logging.info('Resetting std optimizer [pt2] (lr = %f)' % options['gen_lr_main'])
gen_optimizer = opter(model.parameters(), lr=options['gen_lr_main'], wd=gen_wd)
else:
ValueError('Unexpected pt_stage ' + str(pt_stage))
else: # Not in pretraining
logging.info('Resetting std optimizer (lr = %f)' % options['gen_lr_main'])
gen_optimizer = opter(model.parameters(), lr=options['gen_lr_main'], wd=gen_wd)
# Create the fixed image batch and write it out before starting training
os.makedirs(outdir)
fixed_batch_gt_name = 'fixed_batch-imgs.png'
fixed_img_batch = img_dataloader.dataset.get_fixed_batch()
imgutils.imswrite_t(fixed_img_batch, os.path.join(outdir, fixed_batch_gt_name))
# Fixed texture values for cy1 fixed output saving
fixed_cy1_batch_size = options['B_shapes']
#fixed_cy1_num_cols = 10
fixed_cy1_xi_T_vecs = model.sample_xi_T(fixed_cy1_batch_size).to(device_main)
outdir_pared = os.path.basename( os.path.normpath( outdir_core ) ) # progress
path_to_latest_folder = os.path.join(outdir_core, 'latest-' + outdir_pared)
os.makedirs(path_to_latest_folder)
shutil.copy(os.path.join(outdir, fixed_batch_gt_name), path_to_latest_folder)
#########################
##### TRAINING LOOP #####
#########################
# Timer
stopwatch = AccumTimer()
# Start training iterations
for gen_iter in range(n_gen_iters): #########################################################
time_string = '-m%d' % main_training_mode
stopwatch.start('gen_iter' + time_string)
#----------------------------------------------------------------#
###### < Handle Pretraining > #####
if pretraining:
stopwatch.start('pts_iter')
stopwatch.start('pts_load')
#cy1_graphs, cy1_shapes = shape_dataloader.sample()
cy1_shapes, cy1_normals = shape_dataloader.sample()
cy1_shapes = cy1_shapes.to(device_main)
cy1_normals = cy1_normals.to(device_main)
stopwatch.end('pts_load')
# Compute loss depending on PT stage
if pt_stage == 1:
stopwatch.start('pts1_iter')
### Stage 1 pretraining: Just train the mesh AE ###
# Perturbed template, intermeds, delta -> all pre-euc transform
cy1_V_new_pt, cy1_V_new_ints_pt, delta_pt, v, mu_v, logvar_v = model.pretrain_iteration(cy1_shapes, cy1_normals)
stopwatch.end('pts1_iter')
stopwatch.start('pts1_loss')
recon_loss, normals_loss, reg_loss, vreg = Cy1_loss.pretraining_loss(cy1_shapes, cy1_normals,
cy1_V_new_pt, cy1_V_new_ints_pt, delta_pt,
v, mu_v, logvar_v)
total_loss = recon_loss + normals_loss + reg_loss + vreg
stopwatch.end('pts1_loss')
if gen_iter % print_every == 0:
rfpn = lambda ss: rfp(ss, s=False)
_LD = { 'total' : rfpn(total_loss), 'recon' : rfpn(recon_loss), 'shape_reg' : rfpn(reg_loss),
'normals' : rfpn(normals_loss), 'v_reg' : rfpn(vreg) }
logging.info('(PTS1-%d) Total: %s\n\tRecon: %s, MeshReg: %s, Normals: %s, vReg: %s [CurrLR: %f]'
% ( gen_iter, rfp(total_loss), rfp(recon_loss), rfp(reg_loss), rfp(normals_loss), rfp(vreg),
pt_1_scheduler.get_lr()[0] ) )
utils.write_all_to_tensorboard( board_writer, _LD, gen_iter, prepend_string='PT1-')
logging.info('Average Timings: ' + stopwatch.csv_means_string())
stopwatch.reset()
# Update optimizer
stopwatch.start('pts1_step')
gen_optimizer.zero_grad()
total_loss.backward()