-
Notifications
You must be signed in to change notification settings - Fork 7
/
train_region_final.py
1822 lines (1379 loc) · 71.1 KB
/
train_region_final.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 os, sys
BASE_DIR = os.path.normpath(
os.path.join(os.path.dirname(os.path.abspath(__file__))))
import argparse
import numpy as np
import json
import datetime
import time
from collections import defaultdict
from data_utils import *
import torch
import torch.nn as nn
import torch.nn.functional as F
from pytorch3d.loss import chamfer_distance
from dataset import *
from model import *
from losses import *
import gc
parser = argparse.ArgumentParser()
parser.add_argument("--config", default="config_chairs_final.json", help="path to the json config file", type=str)
parser.add_argument("--logdir", default="log_test2", help="path to the log directory", type=str)
parser.add_argument('--dump_dir', default= "dump_test2", type=str)
parser.add_argument('--category', default= "storagefurniture", type=str)
parser.add_argument('--to_train', default= False, type=bool)
parser.add_argument('--part_loss', default= False, type=bool)
parser.add_argument('--use_bn', default= False, type=bool)
parser.add_argument('--update_src_latent', default= False, type=bool)
parser.add_argument('--share_src_latent', default= False, type=bool)
parser.add_argument('--normalize', default= False, type=bool)
parser.add_argument('--init_deformation', default= False, type=bool)
parser.add_argument('--fixed_deformation', default= False, type=bool)
parser.add_argument('--shared_encoder', default= False, type=bool)
parser.add_argument('--clip_vec', default= False, type=bool)
parser.add_argument('--distance_function', default= "mahalanobis", type=str)
parser.add_argument('--loss_function', default= "regression", type=str)
parser.add_argument('--selection', default= "random", type=str)
parser.add_argument('--use_connectivity', default= False, type=bool)
parser.add_argument('--use_src_encoder', default= False, type=bool)
parser.add_argument('--use_src_encoder_retrieval', default= False, type=bool)
parser.add_argument('--use_symmetry', default= False, type=bool)
parser.add_argument('--use_singleaxis', default= False, type=bool)
parser.add_argument('--use_keypoint', default= False, type=bool)
parser.add_argument('--prop2', default= False, type=bool)
parser.add_argument('--prop2_more', default= False, type=bool)
parser.add_argument('--prop3', default= False, type=bool)
# parser.add_argument('--model_init', default= "log_chair500_conn/", type=str)
parser.add_argument('--model_init', default= "log_chair500_conn/", type=str)
parser.add_argument('--K', default= 10, type=int)
parser.add_argument('--margin', default= 10.0, type=float)
parser.add_argument('--activation_fn', default= "sigmoid", type=str)
parser.add_argument('--visualize', default= False, type=bool)
parser.add_argument('--eval_selection', default= "retrieval", type=str)
parser.add_argument('--num_sources', default= 500, type=int)
parser.add_argument('--complementme', default= False, type=int)
parser.add_argument('--all_models', default= False, type=bool)
parser.add_argument('--fine_tune', default= False, type=bool)
parser.add_argument("--ref_logdir", default="log_all_models_A_J3/", help="path to the log directory", type=str)
FLAGS = parser.parse_args()
config = FLAGS.config
LOG_DIR = FLAGS.logdir
if not os.path.exists(LOG_DIR):
os.mkdir(LOG_DIR)
TO_TRAIN = FLAGS.to_train
fname = os.path.join(LOG_DIR, "config.json")
if TO_TRAIN:
args = json.load(open(config))
with open(fname, "w") as fp:
json.dump(args, fp, indent=4)
else:
args = json.load(open(fname))
curr_fname = sys.argv[0]
if TO_TRAIN:
os.system('cp %s %s' % (curr_fname, LOG_DIR))
DATA_DIR = args["data_dir"]
# OBJ_CAT = args["category"]
OBJ_CAT = FLAGS.category
DUMP_DIR = FLAGS.dump_dir
if not os.path.exists(DUMP_DIR): os.mkdir(DUMP_DIR)
temp_fol = os.path.join(DUMP_DIR, "tmp")
if not os.path.exists(temp_fol): os.mkdir(temp_fol)
LOG_FOUT = open(os.path.join(DUMP_DIR, 'log_evaluate.txt'), 'w')
LOG_FOUT.write(str(FLAGS)+'\n')
ALPHA = args["alpha"]
SOURCE_LATENT_DIM = args["source_latent_dim"]
TARGET_LATENT_DIM = args["target_latent_dim"]
PART_LATENT_DIM = args["part_latent_dim"]
PART_LOSS = FLAGS.part_loss
K = FLAGS.K
MARGIN = FLAGS.margin
USE_BN = FLAGS.use_bn
ACTIVATION_FN = FLAGS.activation_fn
UPDATE_SRC_LATENT = FLAGS.update_src_latent
SHARE_SRC_LATENT = FLAGS.share_src_latent
NORMALIZE = FLAGS.normalize
INIT_DEFORMATION = FLAGS.init_deformation
FIXED_DEFORMATION = FLAGS.fixed_deformation
SHARED_ENCODER = FLAGS.shared_encoder
MODEL_INIT = FLAGS.model_init
CLIP_VEC = FLAGS.clip_vec
EVAL_SELECTION = FLAGS.eval_selection
LOSS_FUNC = FLAGS.loss_function
DIST_FUNC = FLAGS.distance_function
SELECTION = FLAGS.selection
USE_CONNECTIVITY = FLAGS.use_connectivity
USE_SRC_ENCODER = FLAGS.use_src_encoder
USE_SRC_ENCODER_RETRIEVAL = FLAGS.use_src_encoder_retrieval
USE_SYMMETRY = FLAGS.use_symmetry
USE_SINGLEAXIS = FLAGS.use_singleaxis
USE_KEYPOINT = FLAGS.use_keypoint
PROP2 = FLAGS.prop2
PROP2_MORE = FLAGS.prop2_more
PROP3 = FLAGS.prop3
NUM_SOURCES = FLAGS.num_sources
print("Num sources: "+str(NUM_SOURCES))
COMPLEMENTME = FLAGS.complementme
ALL_MODELS = FLAGS.all_models
FINE_TUNE = FLAGS.fine_tune
REF_LOGDIR = FLAGS.ref_logdir
def log_string(out_str):
LOG_FOUT.write(out_str+'\n')
LOG_FOUT.flush()
print(out_str)
log_string("Normalize: " + str(NORMALIZE))
log_string("Use connectivity: " + str(USE_CONNECTIVITY))
log_string("Update source vec: " + str(UPDATE_SRC_LATENT))
log_string("Shared src_latent: " + str(SHARE_SRC_LATENT))
log_string("")
log_string("Fixed deformation: " + str(FIXED_DEFORMATION))
log_string("Init Deformation: " + str(INIT_DEFORMATION)+" model: "+MODEL_INIT)
log_string("Shared encoder: " + str(SHARED_ENCODER))
log_string("")
log_string("Loss Func: " + str(LOSS_FUNC))
log_string("Distance Func: " + str(DIST_FUNC))
log_string("Activation Func: " + str(ACTIVATION_FN))
log_string("Selection: " + str(SELECTION))
log_string("Use Property 2: " + str(PROP2))
log_string("Use Property 2 more: " + str(PROP2_MORE))
log_string("Use Property 3: " + str(PROP3))
log_string("")
LOG_FOUT.write(str(FLAGS)+'\n')
TO_VISU = FLAGS.visualize
global DEFORMATION_CANDIDATES
DEFORMATION_CANDIDATES = {}
global DEFORMATION_DISTANCES
DEFORMATION_DISTANCES = {}
if __name__ == "__main__":
if not ALL_MODELS:
if COMPLEMENTME:
print("Using ComplementMe dataset")
src_data_fol = os.path.join(BASE_DIR, "data_complementme_final", OBJ_CAT, "h5_new")
elif USE_SINGLEAXIS:
print("Using single axis constraint")
src_data_fol = os.path.join(BASE_DIR, "data_aabb_constraints_singleaxis", OBJ_CAT, "h5")
elif USE_KEYPOINT:
print("Using keypoint constraint")
src_data_fol = os.path.join(BASE_DIR, "data_aabb_constraints_keypoint", OBJ_CAT, "h5")
else:
src_data_fol = os.path.join(BASE_DIR, "data_aabb_constraints", OBJ_CAT, "h5")
if COMPLEMENTME:
filename_pickle = os.path.join("generated_datasplits_complementme", OBJ_CAT+"_"+str(NUM_SOURCES)+".pickle")
else:
filename_pickle = os.path.join("generated_datasplits", OBJ_CAT+"_"+str(NUM_SOURCES)+".pickle")
sources, _, _ = get_all_selected_models_pickle(filename_pickle)
if COMPLEMENTME:
filename = os.path.join("generated_datasplits_complementme", OBJ_CAT+"_"+str(NUM_SOURCES)+"_"+DATA_SPLIT+".h5")
else:
#### Get data for all target models
filename = os.path.join("generated_datasplits", OBJ_CAT+"_"+str(NUM_SOURCES)+"_"+DATA_SPLIT+".h5")
else:
src_data_fol = os.path.join(BASE_DIR, "data_aabb_constraints_keypoint")
filename_pickle = os.path.join("generated_datasplits", "all_classes_chairtablecabinet_smaller.pickle")
sources, sources_cat, _, _ = get_all_selected_models_pickle(filename_pickle, all_models=True)
filename = os.path.join("generated_datasplits", "all_classes_train_smaller.h5")
if (TO_TRAIN):
DATA_SPLIT = "train"
batch_size = args["batch_size"]
else:
DATA_SPLIT = "test"
batch_size = 2
dataset = StructureNetDataset_h5(filename)
to_shuffle = TO_TRAIN
# print(to_shuffle)
loader = torch.utils.data.DataLoader(
dataset,
batch_size=batch_size,
num_workers=args["num_workers"],
pin_memory=True,
shuffle=to_shuffle,
)
#### Torch
device = args["device"]
##Get the data of the sources
## Get max number of params for the embedding size
MAX_NUM_PARAMS = -1
MAX_NUM_PARTS = -1
SOURCE_MODEL_INFO = []
SOURCE_SEMANTICS = []
SOURCE_PART_LATENT_CODES = []
print("Loading sources...")
for i in range(len(sources)):
source_model = sources[i]
src_filename = str(source_model) + "_leaves.h5"
if not ALL_MODELS:
if (USE_CONNECTIVITY):
box_params, orig_ids, default_param, points, point_labels, points_mat, point_semantic, \
constraint_mat, constraint_proj_mat = get_model(os.path.join(src_data_fol, src_filename), semantic=True, constraint=True)
else:
box_params, orig_ids, default_param, points, point_labels, points_mat, point_semantic = get_model(os.path.join(src_data_fol, src_filename), semantic=True)
else:
if (USE_CONNECTIVITY):
box_params, orig_ids, default_param, points, point_labels, points_mat, point_semantic, \
constraint_mat, constraint_proj_mat = get_model(os.path.join(src_data_fol, sources_cat[i], "h5", src_filename), semantic=True, constraint=True)
else:
box_params, orig_ids, default_param, points, point_labels, points_mat, point_semantic = get_model(os.path.join(src_data_fol, sources_cat[i], "h5", src_filename), semantic=True)
curr_source_dict = {}
curr_source_dict["default_param"] = default_param
curr_source_dict["points"] = points
curr_source_dict["point_labels"] = point_labels
curr_source_dict["points_mat"] = points_mat
curr_source_dict["point_semantic"] = point_semantic
curr_source_dict["model_id"] = source_model
if (USE_CONNECTIVITY):
curr_source_dict["constraint_mat"] = constraint_mat
curr_source_dict["constraint_proj_mat"] = constraint_proj_mat
# Get number of parts of the model
num_parts = len(np.unique(point_labels))
curr_source_dict["num_parts"] = num_parts
curr_num_params = default_param.shape[0]
if (MAX_NUM_PARAMS < curr_num_params):
MAX_NUM_PARAMS = curr_num_params
MAX_NUM_PARTS = int(MAX_NUM_PARAMS/6)
SOURCE_MODEL_INFO.append(curr_source_dict)
# For source semantics also get a list of unique labels
src_semantic = torch.from_numpy(point_semantic)
src_semantic = src_semantic.to(device)
unique_labels = torch.unique(src_semantic)
SOURCE_SEMANTICS.append([src_semantic, unique_labels])
# Create latent code per part for the autodecoder setup
part_latent_codes = torch.autograd.Variable(torch.randn((num_parts,PART_LATENT_DIM), dtype=torch.float, device=device), requires_grad=True)
SOURCE_PART_LATENT_CODES.append(part_latent_codes)
## Create source latent
SOURCE_LATENT_CODES = torch.autograd.Variable(torch.randn((len(sources),SOURCE_LATENT_DIM), dtype=torch.float, device=device), requires_grad=True)
if not SHARE_SRC_LATENT:
RETRIEVAL_SOURCE_LATENT_CODES = torch.autograd.Variable(torch.randn((len(sources),SOURCE_LATENT_DIM), dtype=torch.float, device=device), requires_grad=True)
if (DIST_FUNC == "mahalanobis"):
SOURCE_VARIANCES = torch.autograd.Variable(torch.randn((len(sources),SOURCE_LATENT_DIM), dtype=torch.float, device=device), requires_grad=True)
if (LOSS_FUNC == "regression"):
SOURCE_SIGMAS = torch.autograd.Variable(torch.randn((len(sources),1), dtype=torch.float, device=device), requires_grad=True)
print("Done loading sources.")
print(len(SOURCE_MODEL_INFO))
embedding_size = 6
## Define Networks
## For Deformation
target_encoder = TargetEncoder(
TARGET_LATENT_DIM,
args["input_channels"],
)
target_encoder.to(device, dtype=torch.float)
## For Retrieval
retrieval_encoder = TargetEncoder(
TARGET_LATENT_DIM,
args["input_channels"],
)
retrieval_encoder.to(device, dtype=torch.float)
decoder_input_dim = TARGET_LATENT_DIM + SOURCE_LATENT_DIM + PART_LATENT_DIM
param_decoder = ParamDecoder2(decoder_input_dim, 256, embedding_size, use_bn=USE_BN)
param_decoder.to(device, dtype=torch.float)
## Define loss and optimizer
learning_rate = args["learning_rate"]
n_epochs = args["epochs"]
## To fine tune the retrieval module
if FINE_TUNE:
fname = os.path.join(REF_LOGDIR, "model.pth")
target_encoder.load_state_dict(torch.load(fname)["target_encoder"])
target_encoder.to(device)
target_encoder.eval()
param_decoder.load_state_dict(torch.load(fname)["param_decoder"])
param_decoder.to(device)
param_decoder.eval()
SOURCE_LATENT_CODES = torch.load(fname)["source_latent_codes"]
SOURCE_PART_LATENT_CODES = torch.load(fname)["part_latent_codes"]
for child in target_encoder.children():
if type(child)==nn.BatchNorm1d:
child.track_running_stats = False
elif type(child)==nn.Sequential:
for ii in range(len(child)):
if type(child[ii])==nn.BatchNorm1d:
child[ii].track_running_stats = False
for child in param_decoder.children():
if type(child)==nn.BatchNorm1d:
child.track_running_stats = False
if not SHARED_ENCODER:
retrieval_encoder.load_state_dict(torch.load(fname)["retrieval_encoder"])
retrieval_encoder.to(device)
retrieval_encoder.eval()
if (DIST_FUNC == "mahalanobis"):
SOURCE_VARIANCES = torch.load(fname)["source_variances"]
if not SHARE_SRC_LATENT:
RETRIEVAL_SOURCE_LATENT_CODES = torch.load(fname)["retrieval_source_latent_codes"]
FIXED_DEFORMATION = True
########
elif FIXED_DEFORMATION:
###Load a model and keep it fixed
fname = os.path.join(MODEL_INIT, "model.pth")
target_encoder.load_state_dict(torch.load(fname)["target_encoder"])
target_encoder.to(device)
target_encoder.eval()
param_decoder.load_state_dict(torch.load(fname)["param_decoder"])
param_decoder.to(device)
param_decoder.eval()
SOURCE_LATENT_CODES = torch.load(fname)["source_latent_codes"]
SOURCE_PART_LATENT_CODES = torch.load(fname)["part_latent_codes"]
for child in target_encoder.children():
if type(child)==nn.BatchNorm1d:
child.track_running_stats = False
elif type(child)==nn.Sequential:
for ii in range(len(child)):
if type(child[ii])==nn.BatchNorm1d:
child[ii].track_running_stats = False
for child in param_decoder.children():
if type(child)==nn.BatchNorm1d:
child.track_running_stats = False
else:
if (INIT_DEFORMATION):
#Load model
fname = os.path.join(MODEL_INIT, "model.pth")
target_encoder.load_state_dict(torch.load(fname)["target_encoder"])
target_encoder.to(device)
param_decoder.load_state_dict(torch.load(fname)["param_decoder"])
param_decoder.to(device)
SOURCE_LATENT_CODES = torch.load(fname)["source_latent_codes"]
SOURCE_PART_LATENT_CODES = torch.load(fname)["part_latent_codes"]
target_encoder_params = list(target_encoder.parameters())
decoder_params = list(param_decoder.parameters())
all_params = target_encoder_params + decoder_params
## For the deformation
optimizer_deformation = torch.optim.SGD(
all_params,
lr=args["learning_rate"],
momentum=args["momentum"],
weight_decay=args["weight_decay"],
)
optimizer_deformation.add_param_group({"params": SOURCE_LATENT_CODES})
optimizer_deformation.add_param_group({"params": SOURCE_PART_LATENT_CODES})
### Optimizer for retrieval
if not SHARED_ENCODER :
params_embedding = list(retrieval_encoder.parameters())
optimizer_embedding = torch.optim.SGD(
params_embedding,
lr=args["learning_rate"],
momentum=args["momentum"],
weight_decay=args["weight_decay"],
)
if not SHARE_SRC_LATENT:
optimizer_embedding.add_param_group({"params": RETRIEVAL_SOURCE_LATENT_CODES})
elif SHARE_SRC_LATENT and UPDATE_SRC_LATENT:
optimizer_embedding.add_param_group({"params": SOURCE_LATENT_CODES})
if (DIST_FUNC == "mahalanobis"):
optimizer_embedding.add_param_group({"params": SOURCE_VARIANCES})
if (LOSS_FUNC == "regression"):
optimizer_embedding.add_param_group({"params": SOURCE_SIGMAS, "lr": 0.1})
else:
if not SHARE_SRC_LATENT:
optimizer_embedding = torch.optim.SGD(
[RETRIEVAL_SOURCE_LATENT_CODES],
lr=args["learning_rate"],
momentum=args["momentum"],
weight_decay=args["weight_decay"],
)
if (DIST_FUNC == "mahalanobis"):
optimizer_embedding.add_param_group({"params": SOURCE_VARIANCES})
if (LOSS_FUNC == "regression"):
optimizer_embedding.add_param_group({"params": SOURCE_SIGMAS, "lr": 0.1})
elif SHARE_SRC_LATENT and UPDATE_SRC_LATENT:
optimizer_embedding = torch.optim.SGD(
[SOURCE_LATENT_CODES],
lr=args["learning_rate"],
momentum=args["momentum"],
weight_decay=args["weight_decay"],
)
if (DIST_FUNC == "mahalanobis"):
optimizer_embedding.add_param_group({"params": SOURCE_VARIANCES})
if (LOSS_FUNC == "regression"):
optimizer_embedding.add_param_group({"params": SOURCE_SIGMAS, "lr": 0.1})
else:
if (DIST_FUNC == "mahalanobis"):
optimizer_embedding = torch.optim.SGD(
[SOURCE_VARIANCES],
lr=args["learning_rate"],
momentum=args["momentum"],
weight_decay=args["weight_decay"],
)
elif (LOSS_FUNC == "regression"):
optimizer_embedding = torch.optim.SGD(
[SOURCE_SIGMAS],
lr=args["learning_rate"],
momentum=args["momentum"],
weight_decay=args["weight_decay"],
)
def construct_candidates_dict(loader, encoder):
print("Creating candidates dict.")
start_time = time.time()
for i, batch in enumerate(loader):
# target_shapes, target_ids, _, _, _ = batch
target_shapes, target_ids, _, _ = batch
x = [x.to(device, dtype=torch.float) for x in target_shapes]
x = torch.stack(x)
retrieval_latent_codes = encoder(x)
retrieval_latent_codes = retrieval_latent_codes.unsqueeze(0).repeat(len(SOURCE_MODEL_INFO),1,1)
retrieval_latent_codes = retrieval_latent_codes.view(-1, retrieval_latent_codes.shape[-1])
###Get dummy source labels
source_label_shape = torch.zeros(target_shapes.shape[0])
source_labels = source_label_shape.unsqueeze(0).repeat(len(SOURCE_MODEL_INFO),1)
source_labels = source_labels.view(-1)
#Get all labels
source_labels = get_all_source_labels(source_labels, len(SOURCE_MODEL_INFO))
if (NORMALIZE):
retrieval_latent_codes = F.normalize(retrieval_latent_codes)
retrieval_latent_codes = retrieval_latent_codes.view(len(SOURCE_MODEL_INFO), -1, TARGET_LATENT_DIM)
if USE_SRC_ENCODER_RETRIEVAL:
with torch.no_grad():
## Split to two batches for memory
src_latent_codes = []
num_sets = 20
interval = int(len(source_labels)/num_sets)
for j in range(num_sets):
if (j==num_sets-1):
curr_src_latent_codes = get_source_latent_codes_encoder(source_labels[j*interval:], SOURCE_MODEL_INFO, encoder, device=device)
else:
curr_src_latent_codes = get_source_latent_codes_encoder(source_labels[j*interval:(j+1)*interval], SOURCE_MODEL_INFO, encoder, device=device)
src_latent_codes.append(curr_src_latent_codes)
src_latent_codes = torch.cat(src_latent_codes).view(len(SOURCE_MODEL_INFO), -1, SOURCE_LATENT_DIM)
else:
if (SHARE_SRC_LATENT):
src_latent_codes = src_latent_codes.view(len(SOURCE_MODEL_INFO), -1, SOURCE_LATENT_DIM)
else:
src_latent_codes = get_source_latent_codes_fixed(source_labels, RETRIEVAL_SOURCE_LATENT_CODES, device=device)
src_latent_codes = src_latent_codes.view(len(SOURCE_MODEL_INFO), -1, SOURCE_LATENT_DIM)
if (DIST_FUNC == "mahalanobis"):
src_variances = get_source_latent_codes_fixed(source_labels, SOURCE_VARIANCES, device=device)
src_variances = src_variances.view(len(SOURCE_MODEL_INFO), -1, SOURCE_LATENT_DIM)
if (ACTIVATION_FN.lower() == "none"):
distances = compute_mahalanobis(retrieval_latent_codes, src_latent_codes, src_variances, clip_vec=CLIP_VEC)
elif (ACTIVATION_FN == "sigmoid"):
distances = compute_mahalanobis(retrieval_latent_codes, src_latent_codes, src_variances, activation_fn=torch.sigmoid, clip_vec=CLIP_VEC)
elif (ACTIVATION_FN == "relu"):
distances = compute_mahalanobis(retrieval_latent_codes, src_latent_codes, src_variances, activation_fn=torch.relu, clip_vec=CLIP_VEC)
elif (DIST_FUNC == "order"):
if (ACTIVATION_FN.lower() == "none"):
distances = order_embedding_distance(retrieval_latent_codes, src_latent_codes, device=device)
elif (ACTIVATION_FN == "sigmoid"):
distances = order_embedding_distance(retrieval_latent_codes, src_latent_codes, device=device, activation_fn=torch.sigmoid)
elif (ACTIVATION_FN == "relu"):
distances = order_embedding_distance(retrieval_latent_codes, src_latent_codes, device=device, activation_fn=torch.relu)
sorted_distances, sorted_indices = torch.sort(distances, dim=0)
sorted_indices = sorted_indices.to("cpu")
sorted_indices = sorted_indices.detach().numpy().T
distances = distances.to("cpu")
distances = distances.detach().numpy().T
target_ids = target_ids.to("cpu")
target_ids = target_ids.detach().numpy()
# print(sorted_indices)
for j in range(sorted_indices.shape[0]):
DEFORMATION_CANDIDATES[target_ids[j]] = sorted_indices[j]
DEFORMATION_DISTANCES[target_ids[j]] = distances[j]
if (i%20==0):
print("Time elapsed: "+str(time.time()-start_time)+" sec for batch "+str(i)+ "/"+ str(len(loader))+".")
return
def construct_candidates_dict_faster(loader, encoder):
print("Creating candidates dict. Faster version.")
start_time = time.time()
source_labels = np.expand_dims(np.arange(len(SOURCE_MODEL_INFO)), axis=1)
source_labels = np.reshape(source_labels, (-1))
print(source_labels.shape)
##Cache source latent codes
## Source latent codes
if USE_SRC_ENCODER_RETRIEVAL:
with torch.no_grad():
## Split to two batches for memory
src_latent_codes_template = []
num_sets = 20
interval = int(len(SOURCE_MODEL_INFO)/num_sets)
for j in range(num_sets):
if (j==num_sets-1):
curr_src_latent_codes = get_source_latent_codes_encoder(source_labels[j*interval:], SOURCE_MODEL_INFO, retrieval_encoder, device=device)
else:
curr_src_latent_codes = get_source_latent_codes_encoder(source_labels[j*interval:(j+1)*interval], SOURCE_MODEL_INFO, retrieval_encoder, device=device)
src_latent_codes_template.append(curr_src_latent_codes)
src_latent_codes_template = torch.cat(src_latent_codes_template).view(len(SOURCE_MODEL_INFO), -1, SOURCE_LATENT_DIM)
else:
if (SHARE_SRC_LATENT):
print("Error in creating dict with shared latent code.")
else:
src_latent_codes_template = get_source_latent_codes_fixed(source_labels, RETRIEVAL_SOURCE_LATENT_CODES, device=device)
src_latent_codes_template = src_lsrc_latent_codes_templateatent_codes.view(len(SOURCE_MODEL_INFO), -1, SOURCE_LATENT_DIM)
for i, batch in enumerate(loader):
# target_shapes, target_ids, _, _, _ = batch
target_shapes, target_ids, _, _ = batch
if COMPLEMENTME:
target_shapes[:,:,2] = -target_shapes[:,:,2]
x = [x.to(device, dtype=torch.float) for x in target_shapes]
x = torch.stack(x)
retrieval_latent_codes = encoder(x)
retrieval_latent_codes = retrieval_latent_codes.unsqueeze(0).repeat(len(SOURCE_MODEL_INFO),1,1)
retrieval_latent_codes = retrieval_latent_codes.view(-1, retrieval_latent_codes.shape[-1])
###Get dummy source labels
source_label_shape = torch.zeros(target_shapes.shape[0])
source_labels = source_label_shape.unsqueeze(0).repeat(len(SOURCE_MODEL_INFO),1)
source_labels = source_labels.view(-1)
#Get all labels
source_labels = get_all_source_labels(source_labels, len(SOURCE_MODEL_INFO))
if (NORMALIZE):
retrieval_latent_codes = F.normalize(retrieval_latent_codes)
retrieval_latent_codes = retrieval_latent_codes.view(len(SOURCE_MODEL_INFO), -1, TARGET_LATENT_DIM)
##Repeat the src_latent vector tensor
src_latent_codes = src_latent_codes_template.repeat(1, target_shapes.shape[0],1)
if (DIST_FUNC == "mahalanobis"):
src_variances = get_source_latent_codes_fixed(source_labels, SOURCE_VARIANCES, device=device)
src_variances = src_variances.view(len(SOURCE_MODEL_INFO), -1, SOURCE_LATENT_DIM)
if (ACTIVATION_FN.lower() == "none"):
distances = compute_mahalanobis(retrieval_latent_codes, src_latent_codes, src_variances, clip_vec=CLIP_VEC)
elif (ACTIVATION_FN == "sigmoid"):
distances = compute_mahalanobis(retrieval_latent_codes, src_latent_codes, src_variances, activation_fn=torch.sigmoid, clip_vec=CLIP_VEC)
elif (ACTIVATION_FN == "relu"):
distances = compute_mahalanobis(retrieval_latent_codes, src_latent_codes, src_variances, activation_fn=torch.relu, clip_vec=CLIP_VEC)
elif (DIST_FUNC == "order"):
if (ACTIVATION_FN.lower() == "none"):
distances = order_embedding_distance(retrieval_latent_codes, src_latent_codes, device=device)
elif (ACTIVATION_FN == "sigmoid"):
distances = order_embedding_distance(retrieval_latent_codes, src_latent_codes, device=device, activation_fn=torch.sigmoid)
elif (ACTIVATION_FN == "relu"):
distances = order_embedding_distance(retrieval_latent_codes, src_latent_codes, device=device, activation_fn=torch.relu)
sorted_distances, sorted_indices = torch.sort(distances, dim=0)
sorted_indices = sorted_indices.to("cpu")
sorted_indices = sorted_indices.detach().numpy().T
distances = distances.to("cpu")
distances = distances.detach().numpy().T
target_ids = target_ids.to("cpu")
target_ids = target_ids.detach().numpy()
# print(sorted_indices)
for j in range(sorted_indices.shape[0]):
DEFORMATION_CANDIDATES[target_ids[j]] = sorted_indices[j]
DEFORMATION_DISTANCES[target_ids[j]] = distances[j]
if (i%20==0):
print("Time elapsed: "+str(time.time()-start_time)+" sec for batch "+str(i)+ "/"+ str(len(loader))+".")
return
def construct_deformation_candidates_dict(loader, encoder):
print("Creating deformation candidates dict.")
for i, batch in enumerate(loader):
# target_shapes, target_ids, _, _, _ = batch
target_shapes, target_ids, _, _ = batch
x = [x.to(device, dtype=torch.float) for x in target_shapes]
x = torch.stack(x)
target_latent_codes = encoder(x)
target_latent_codes = target_latent_codes.unsqueeze(0).repeat(len(SOURCE_MODEL_INFO),1,1)
source_label_shape = torch.zeros(target_shapes.shape[0])
source_labels = source_label_shape.unsqueeze(0).repeat(len(SOURCE_MODEL_INFO),1)
## Reshape to (K*batch_size, ...) to feed into the network
## Source assignments have to be done accordingly
target_latent_codes = target_latent_codes.view(-1, target_latent_codes.shape[-1])
source_labels = source_labels.view(-1)
#Get all labels
source_labels = get_all_source_labels(source_labels, len(SOURCE_MODEL_INFO))
##Also overwrite x for chamfer distance
x_repeated = x.unsqueeze(0).repeat(source_labels.shape[0],1,1,1)
x_repeated = x_repeated.view(-1, x_repeated.shape[-2], x_repeated.shape[-1])
num_sub_epochs = int(source_labels.shape[0]/batch_size) + 1
all_cd_loss = []
for j in range(num_sub_epochs):
curr_source_labels = source_labels[j*batch_size:(j+1)*batch_size]
num_samples = curr_source_labels.shape[0]
if (num_samples <=0):
break
curr_target_latent_codes = target_latent_codes[j*batch_size:(j+1)*batch_size, :]
curr_x_repeated = x_repeated[j*batch_size:(j+1)*batch_size, :, :]
###Set up source A matrices and default params based on source_labels of the target
src_mats, src_default_params, src_connectivity_mat = get_source_info(curr_source_labels, SOURCE_MODEL_INFO, MAX_NUM_PARAMS, use_connectivity= USE_CONNECTIVITY)
###Set up source latent codes based on source_labels of the target
src_latent_codes = get_source_latent_codes_fixed(curr_source_labels, SOURCE_LATENT_CODES, device=device)
mat = [mat.to(device, dtype=torch.float) for mat in src_mats]
def_param = [def_param.to(device, dtype=torch.float) for def_param in src_default_params]
mat = torch.stack(mat)
def_param = torch.stack(def_param)
## If using connectivity
if (USE_CONNECTIVITY):
conn_mat = [conn_mat.to(device, dtype=torch.float) for conn_mat in src_connectivity_mat]
conn_mat = torch.stack(conn_mat)
concat_latent_code = torch.cat((src_latent_codes, curr_target_latent_codes), dim=1)
##Param Decoder per part
# Make the part latent codes of each source into a (K x PART_LATENT_DIM) tensor
all_params = []
for k in range(concat_latent_code.shape[0]):
curr_num_parts = SOURCE_MODEL_INFO[curr_source_labels[k]]["num_parts"]
curr_code = concat_latent_code[k]
curr_code_repeated = curr_code.view(1,curr_code.shape[0]).repeat(curr_num_parts, 1)
part_latent_codes = SOURCE_PART_LATENT_CODES[curr_source_labels[k]]
full_latent_code = torch.cat((curr_code_repeated, part_latent_codes), dim=1)
params = param_decoder(full_latent_code, use_bn=USE_BN)
## Pad with extra zero rows to cater to max number of parameters
if (curr_num_parts < MAX_NUM_PARTS):
dummy_params = torch.zeros((MAX_NUM_PARTS-curr_num_parts, embedding_size), dtype=torch.float, device=device)
params = torch.cat((params, dummy_params), dim=0)
params = params.view(-1, 1)
all_params.append(params)
params = torch.stack(all_params)
if (USE_CONNECTIVITY):
output_pcs = get_shape(mat, params, def_param, ALPHA, connectivity_mat=conn_mat)
else:
output_pcs = get_shape(mat, params, def_param, ALPHA)
cd_loss, _ = chamfer_distance(output_pcs, curr_x_repeated, batch_reduction=None)
cd_loss = cd_loss.to("cpu").detach().numpy()
all_cd_loss.append(cd_loss)
all_cd_loss = np.array(all_cd_loss)
all_cd_loss = np.reshape(all_cd_loss, (target_shapes.shape[0], -1))
distances = all_cd_loss
sorted_indices = np.argsort(distances, axis=1)
target_ids = target_ids.to("cpu")
target_ids = target_ids.detach().numpy()
# print(sorted_indices)
for j in range(sorted_indices.shape[0]):
DEFORMATION_CANDIDATES[target_ids[j]] = sorted_indices[j]
DEFORMATION_DISTANCES[target_ids[j]] = distances[j]
return
def get_dict_candidates(target_ids, K):
target_ids = target_ids.to("cpu")
target_ids = target_ids.detach().numpy()
all_selected = []
all_weights = []
for target_id in target_ids:
ranked_candidates = np.array(DEFORMATION_CANDIDATES[target_id])
distances_candidates = np.array(DEFORMATION_DISTANCES[target_id])
##softmax of distances
# distances_candidates = distances_candidates/np.min(distances_candidates)
if (SELECTION == "retrieval_candidates"):
distances_candidates = distances_candidates/100.0
distances_normalized = np.exp(-(distances_candidates - np.max(distances_candidates)))
probs = distances_normalized / distances_normalized.sum()
selected_candidates = np.random.choice(np.arange(len(SOURCE_MODEL_INFO)), size=K, replace=False, p= probs)
all_selected.append(selected_candidates)
weights = probs[selected_candidates]/np.sum(probs[selected_candidates])
all_weights.append(weights)
all_selected = np.array(all_selected).T
all_selected = all_selected.flatten()
all_weights = np.array(all_weights).T
print(all_weights.T[0])
print()
all_weights = all_weights.flatten()
return all_selected, all_weights
if (TO_TRAIN):
if not FIXED_DEFORMATION:
target_encoder.train()
param_decoder.train()
else:
target_encoder.eval()
param_decoder.eval()
if not SHARED_ENCODER:
retrieval_encoder.train()
best_loss = np.Inf
## Training loop
for epoch in range(n_epochs):
start = datetime.datetime.now()
scalars = defaultdict(list)
for i, batch in enumerate(loader):
'''
Per batch output:
self.target_points[index], self.target_ids[index], self.target_labels[index], self.target_semantics[index], \
self.corres_source_label[index]
'''
# target_shapes, target_ids, _, semantics, source_label_shape = batch
target_shapes, target_ids, _, semantics = batch
source_label_shape = torch.zeros(target_shapes.shape[0])
if COMPLEMENTME:
target_shapes[:,:,2] = -target_shapes[:,:,2]
x = [x.to(device, dtype=torch.float) for x in target_shapes]
x = torch.stack(x)
##Target Encoder
target_latent_codes = target_encoder(x)
## K is the number of sources selected for each target
## Repeat each K times
target_latent_codes = target_latent_codes.unsqueeze(0).repeat(K,1,1)
semantics = semantics.unsqueeze(0).repeat(K,1,1)
source_labels = source_label_shape.unsqueeze(0).repeat(K,1)
## Reshape to (K*batch_size, ...) to feed into the network
## Source assignments have to be done accordingly
target_latent_codes = target_latent_codes.view(-1, target_latent_codes.shape[-1])
semantics = semantics.view(-1, semantics.shape[-1])
source_labels = source_labels.view(-1)
## Get the source assignments
## For now, we get all sources 1,2,...,K
if (SELECTION == "exhaustive"):
source_labels = get_all_source_labels(source_labels, len(SOURCE_MODEL_INFO))
elif (SELECTION == "random"):
source_labels = get_random_labels(source_labels, len(SOURCE_MODEL_INFO))
elif (SELECTION == "retrieval_candidates"):
#after epochs where retrieval module is trained
if (epoch>30):
# if (1):
to_select_from_dict=1
else:
to_select_from_dict=0
if (to_select_from_dict):
##Dict has not been constructed
if len(DEFORMATION_CANDIDATES.keys())==0:
if SHARED_ENCODER:
target_encoder.eval()
construct_candidates_dict_faster(loader, target_encoder)
target_encoder.train()
else:
retrieval_encoder.eval()
construct_candidates_dict_faster(loader, retrieval_encoder)
retrieval_encoder.train()
source_labels, weights = get_dict_candidates(target_ids, K)
#get random
else:
source_labels = get_random_labels(source_labels, len(SOURCE_MODEL_INFO))
elif (SELECTION == "deformation_candidates"):
to_select_from_dict=1
if len(DEFORMATION_CANDIDATES.keys())==0:
target_encoder.eval()
construct_deformation_candidates_dict(loader, target_encoder)
target_encoder.train()
source_labels, weights = get_dict_candidates(target_ids, K)
##Also overwrite x for chamfer distance
x_repeat = x.unsqueeze(0).repeat(K,1,1,1)
x_repeat = x_repeat.view(-1, x_repeat.shape[-2], x_repeat.shape[-1])
###Set up source A matrices and default params based on source_labels of the target
src_mats, src_default_params, src_connectivity_mat = get_source_info(source_labels, SOURCE_MODEL_INFO, MAX_NUM_PARAMS, use_connectivity= USE_CONNECTIVITY)
# src_mats, src_default_params = get_source_info(source_labels, SOURCE_MODEL_INFO, MAX_NUM_PARAMS)
if USE_SRC_ENCODER:
##Use the encoder to get the source latent code
src_latent_codes = get_source_latent_codes_encoder(source_labels, SOURCE_MODEL_INFO, target_encoder, device=device)
else:
## Autodecoded: Set up source latent codes based on source_labels of the target
src_latent_codes = get_source_latent_codes_fixed(source_labels, SOURCE_LATENT_CODES, device=device)
mat = [mat.to(device, dtype=torch.float) for mat in src_mats]
def_param = [def_param.to(device, dtype=torch.float) for def_param in src_default_params]
mat = torch.stack(mat)
def_param = torch.stack(def_param)
## If using connectivity
if (USE_CONNECTIVITY):
conn_mat = [conn_mat.to(device, dtype=torch.float) for conn_mat in src_connectivity_mat]
conn_mat = torch.stack(conn_mat)
concat_latent_code = torch.cat((src_latent_codes, target_latent_codes), dim=1)
##Param Decoder per part
all_params = []
for j in range(concat_latent_code.shape[0]):
curr_num_parts = SOURCE_MODEL_INFO[source_labels[j]]["num_parts"]
curr_code = concat_latent_code[j]
curr_code_repeated = curr_code.view(1,curr_code.shape[0]).repeat(curr_num_parts, 1)
part_latent_codes = SOURCE_PART_LATENT_CODES[source_labels[j]]
full_latent_code = torch.cat((curr_code_repeated, part_latent_codes), dim=1)
params = param_decoder(full_latent_code, use_bn=USE_BN)
## Pad with extra zero rows to cater to max number of parameters
if (curr_num_parts < MAX_NUM_PARTS):
dummy_params = torch.zeros((MAX_NUM_PARTS-curr_num_parts, embedding_size), dtype=torch.float, device=device)
params = torch.cat((params, dummy_params), dim=0)
params = params.view(-1, 1)
all_params.append(params)
params = torch.stack(all_params)
# print(SOURCE_PART_LATENT_CODES[1])
if (USE_CONNECTIVITY):
output_pc = get_shape(mat, params, def_param, ALPHA, connectivity_mat=conn_mat)