-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathMinkowski_backbone.py
4585 lines (4001 loc) · 251 KB
/
Minkowski_backbone.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
from pickle import decode_long
from random import sample
import sys
import argparse
import time
from datetime import datetime
import math
from tkinter import E
import numpy
from chamferdist import knn_points
from chamferdist import knn_gather
from chamferdist import list_to_padded
from numpy.random.mtrand import f
import trimesh
from numpy.core.defchararray import _join_dispatcher
from torch.utils.tensorboard import SummaryWriter
if(os.path.exists("/blob")):
#for Philly training
running_onCluster = True
print("detected /blob directory, execute on cluster!")
else:
running_onCluster = False
print("not detected /blob directory, execute locally")
from tqdm import tqdm
from load_ply import *
m = 32 #Unet number of features
#HyperNets parameters
hn_pe_dim = 64
hn_mlp_dim = 64
flag_using_scale = False
def get_args_parser():
parser = argparse.ArgumentParser('Set transformer detector', add_help=False)
parser.add_argument('--no_output', action='store_true', help = 'not output for evaluation')
parser.add_argument('--reuseid', action='store_true', help = 'reuse id for distance computation')
parser.add_argument('--ori_mlp', action='store_true', help = 'use original version of MLPs')
parser.add_argument('--ckpt_interval', default=3000, type=int)
parser.add_argument('--dist_th', default=0.1, type=float)
parser.add_argument('--dist_th_tg', default=0.1, type=float)
parser.add_argument('--val_th', default=0.5, type=float)
parser.add_argument('--flag_cycleid', action = 'store_true', help = 'cycle id')
parser.add_argument('--parsenet', action = 'store_true', help = 'use parsenet data')
parser.add_argument('--ourresnet', action = 'store_true', help = 'use our resnet')
parser.add_argument('--backbone_bn', action = 'store_true', help = 'use backbone with batch-norm')
parser.add_argument('--m', default=64, type=int, help = 'set m value')
parser.add_argument('--hidden_dim_mlp', default=384, type=int, help = 'hidden dimension of MLP for ablation study')
#for hn
parser.add_argument('--hn_scale', action = 'store_true', help = 'original topo embed')
parser.add_argument('--no_tripath', action = 'store_true', help = 'no tripath, for ablation')
parser.add_argument('--no_topo', action = 'store_true', help = 'no topo, for ablation, please also set no_tripath as true')
parser.add_argument('--pe_sin', action = 'store_true', help = 'sin positional embedding')
parser.add_argument('--pe_sin_base', default=1.2, type=float)
parser.add_argument('--no_pe', action = 'store_true', help = 'not using positional encoding')
parser.add_argument('--spe', action = 'store_true', help = 'simple positional encoding')
parser.add_argument('--patch_normal', action = 'store_true', help = 'add tangent normal constraints for patch')
parser.add_argument('--patch_lap', action = 'store_true', help = 'add laplacian constraints for patch')
parser.add_argument('--patch_lapboundary', action = 'store_true', help = 'add boundary laplacian constraints for patch')
parser.add_argument('--data_medium', action = 'store_true', help = 'add boundary laplacian constraints for patch')
parser.add_argument('--vis_train', action = 'store_true', help = 'visualize training data')
parser.add_argument('--vis_test', action = 'store_true', help = 'visualize test data')
parser.add_argument('--eval_train', action = 'store_true', help = 'evaluate training data')
parser.add_argument('--geom_l2', action = 'store_true', help = 'use l2 norm for geometric terms')
parser.add_argument('--patch_grid', action = 'store_true', help = 'using patch grid')
parser.add_argument('--patch_close', action = 'store_true', help = 'predict patch closeness')
parser.add_argument('--batch_cd', action = 'store_true', help = 'compute chamfer distance in batch')
parser.add_argument('--patch_emd', action = 'store_true', help = 'using emd for patch loss computing')
parser.add_argument('--patch_uv', action = 'store_true', help = 'compute patch uv, and patch emd is computed based on patch uv')
parser.add_argument('--curve_open_loss', action = 'store_true', help = 'treat open curve seperately')
parser.add_argument('--backbone_expand', action = 'store_true', help = 'expand backbone coordinates and kernel size of the first convolution')
parser.add_argument('--output_normal', action = 'store_true', help = 'output normal for prediction')
parser.add_argument('--output_normal_diff_coef', default=1, type=float, help="loss coefficient for output normal diff loss")
parser.add_argument('--output_normal_tangent_coef', default=1, type=float, help="loss coefficient for output normal tangent lonss")
parser.add_argument('--enable_automatic_restore', action='store_true', help = 'find ckpt automatically when training is interrupted')
parser.add_argument('--quicktest', action='store_true', help = 'only test on 10 models, no validation is used')
parser.add_argument('--noise', default=0, type=int, help = 'add noise, 0:no, 1: 0.01, 2: 0.02, 3: 0.05')
parser.add_argument('--noisetest', default=0, type=int, help = 'add noise for testing, 0:no, 1: 0.01, 2: 0.02, 3: 0.05')
parser.add_argument('--partial', action='store_true', help = 'use partial data')
parser.add_argument('--experiment_name', type=str, required = True)
parser.add_argument('--lr', default=1e-4, type=float)
parser.add_argument('--lr_drop', default=5000, type=int)
parser.add_argument('--batch_size', default=1, type=int)
parser.add_argument('--points_per_patch_dim', default=20, type=int)
parser.add_argument('--eval_res_cov', action='store_true', help="evaluate residual loss and coverage")
parser.add_argument('--eval_matched', action='store_true', help="evaluate residual loss and coverage", default=True)
parser.add_argument('--eval_selftopo', action='store_true', help="evaluate self topo consistency")
parser.add_argument('--th_res', default=0.05, type=float, help="threshold for evaluating residual")
parser.add_argument('--eval_param', action='store_true', help="evaluate residual and converage by parameters")
parser.add_argument('--evalrest', action='store_true', help="evaluate rest data of 900 models")
parser.add_argument('--part', default=-1, type=int) #0,1,2,3, divide data into 4 groups
parser.add_argument('--regen', action='store_true', help="regen files")
parser.add_argument('--th_cov', default=0.01, type=float)
parser.add_argument('--rotation_augment', action='store_true', help="enable rotation augmentation")
parser.add_argument('--num_angles', type=int)
parser.add_argument('--random_angle', action='store_true', help="enable rotation augmentation with random angle")
parser.add_argument('--input_voxel_dim', default=128, type=int, help="voxel dimension of input")
parser.add_argument('--eval', action='store_true')
parser.add_argument('--evalfinal', action='store_true')
parser.add_argument('--evaltopo', action='store_true')
parser.add_argument('--fittingonce', action='store_true')
parser.add_argument('--dropout', default=0.0, type=float,
help="Dropout applied in the transformer")
parser.add_argument('--nheads', default=8, type=int,
help="Number of attention heads inside the transformer's attentions")
parser.add_argument('--num_corner_queries', default=100, type=int,help="Number of corner query slots")
parser.add_argument('--num_curve_queries', default=150, type=int,help="Number of curve query slots")
parser.add_argument('--num_patch_queries', default=100, type=int,help="Number of patch query slots")
parser.add_argument('--pre_norm', action='store_false') #true
parser.add_argument('--position_embedding', default='sine', type=str, choices=('sine', 'learned'),
help="Type of positional embedding to use on top of the image features")
# * BackBone unused
parser.add_argument('--backbone_feature_encode', action='store_true',
help="Using sin to encode features in backbone")
# * Transformer
parser.add_argument('--enc_layers', default=6, type=int,
help="Number of encoding layers in the transformer")
parser.add_argument('--dec_layers', default=6, type=int,
help="Number of decoding layers in the transformer")
parser.add_argument('--dim_feedforward', default=2048, type=int,
help="Intermediate size of the feedforward layers in the transformer blocks")
parser.add_argument('--local_attention', dest='using_local_attention',action='store_true',
help="Using local attention in transformer")
parser.add_argument("--topo_embed_dim", default=256, type=int, help="Feature Dimension Size For Topology Matching")
parser.add_argument("--normalize_embed_feature", action="store_true", help="Normalize Topo Feature before Matching")
parser.add_argument("--num_heads_dot", default=1, type=int, help="number of heads to compute similarity")
parser.add_argument("--matrix_eigen_similarity", action="store_true", help="Using Matrix Eigen Similarity")
# * Loss coefficients
parser.add_argument('--class_loss_coef', default=1, type=float)
parser.add_argument('--corner_geometry_loss_coef', default=1000, type=float, help="loss coefficient for geometric loss in corner matching and training")
parser.add_argument('--curve_geometry_loss_coef', default=1000, type=float, help="loss coefficient for geometric loss in curve matching and training")
parser.add_argument('--patch_geometry_loss_coef', default=1000, type=float, help="loss coefficient for geometric loss in patch matching and training")
parser.add_argument('--corner_avg_count', default=20.25, type=float, help="avg corner count for parsenet dataset")
parser.add_argument('--curve_avg_count', default=37.39, type=float, help="avg curve count for parsenet dataset")
parser.add_argument('--patch_avg_count', default=18.17, type=float, help="avg patch count for parsenet dataset")
parser.add_argument('--global_invalid_weight', default=1.0, type=float, help="avg patch count for parsenet dataset")
parser.add_argument('--curve_corner_topo_loss_coef', default=1, type=float)
parser.add_argument('--patch_curve_topo_loss_coef', default=1, type=float)
parser.add_argument('--patch_corner_topo_loss_coef', default=1, type=float)
parser.add_argument('--topo_loss_coef', default=1, type=float)
parser.add_argument('--curve_corner_geom_loss_coef', default=0, type=float)
parser.add_argument('--topo_acc', action='store_true',help="compute and show topo_acc")
parser.add_argument('--no_show_topo', action='store_true',help="not show three topo loss: curve_point, curve_patch, patch_close")
parser.add_argument('--patch_normal_loss_coef', default=1, type=float, help="loss coefficient for patch normal loss")
parser.add_argument('--patch_lap_loss_coef', default=1000, type=float, help="loss coefficient for patch normal loss")
parser.add_argument('--weight_decay', default=1e-4, type=float)
#transformer feature embedding
parser.add_argument("--curve_embedding_mlp_layers", default=3, type=int)
# training
parser.add_argument('--gpu', default="0,1,2", type=str,
help="gpu id to be used")
parser.add_argument("--checkpoint_path", default=None, type=str, help="checkpoint file (if have) to be used")
parser.add_argument("--input_feature_type", default='global', type=str, help="input feature type(supported type: local global occupancy)")
parser.add_argument("--input_normal_signals", action='store_true', help='input normal signals in voxel features')
parser.add_argument('--max_training_iterations', default=250001, type=int)
parser.add_argument('--skip_transformer_encoder', action='store_false', help = 'remove encoder part of transformer')
parser.add_argument('--clip_max_norm', default=0.0, type=float,
help='gradient clipping max norm')
parser.add_argument('--clip_value', action='store_true', help = 'clip value')
parser.add_argument('--single_dir_patch_chamfer', action='store_true', help = 'Single direction chamfer loss in patch processing')
parser.add_argument('--extra_single_chamfer', action='store_true', help = 'based on emd, add extra single chamfer distance from gt patch to predicted grid')
parser.add_argument('--extra_single_chamfer_weight', default=300.0, type=float)
parser.add_argument("--save_gt", action='store_true', help = 'save gt info in predicted pickle file')
parser.add_argument("--no_instance_norm", action='store_true', help = 'using instance normalization in mink backbone')
parser.add_argument("--sin", action='store_true', help = 'using sin activation in geometry mlp')
parser.add_argument("--suffix", default='_opt_mix_final.json', type=str, help="suffix for evaluation")
parser.add_argument("--folder", default=None, type=str, help="inter folder for evaluation")
parser.add_argument("--vis_inter_layer", default=-1, type=int)
# * Matcher
parser.add_argument("--using_prob_in_matching", action='store_true', help = 'using -p in matching cost')
'''
parser.add_argument('--set_cost_class', default=1, type=float,
help="Class coefficient in the matching cost")
parser.add_argument('--set_cost_bbox', default=5, type=float,
help="L1 box coefficient in the matching cost")
parser.add_argument('--set_cost_giou', default=2, type=float,
help="giou box coefficient in the matching cost")
'''
return parser
parser = argparse.ArgumentParser('DETR training and evaluation script', parents=[get_args_parser()])
args = parser.parse_args()
m = args.m
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu
num_of_gpus = len(args.gpu.split(","))
print("Utilize {} gpus".format(num_of_gpus))
from data_loader_abc import *
import MinkowskiEngine as ME
if not args.no_instance_norm: #false
print("using instance norm")
import mink_resnet_in as resnets
else:
import mink_resnet as resnets
import torch.nn as nn
import math
import torch.nn.functional as F
from transformer3d import build_transformer_tripath
from matcher_corner import build_matcher_corner
from matcher_curve import build_matcher_curve, cyclic_curve_points
from matcher_patch import build_matcher_patch, emd_by_id
import torch.multiprocessing as mp
voxel_dim = args.input_voxel_dim
out_voxel_dim = voxel_dim // 8 #16
import torch.distributed as dist
import tensorflow as tf
import plywrite
if args.eval_param:
from src.primitives import ComputePrimitiveDistance
points_per_curve = 34
points_per_patch_dim = args.points_per_patch_dim #10*10 points per patch
corner_eos_coef_cal = args.corner_avg_count / (args.num_corner_queries - args.corner_avg_count) * args.global_invalid_weight
curve_eos_coef_cal = args.curve_avg_count / (args.num_curve_queries - args.curve_avg_count) * args.global_invalid_weight
patch_eos_coef_cal = args.patch_avg_count / (args.num_patch_queries - args.patch_avg_count) * args.global_invalid_weight
# print('!!!!!!!corner eos: {} curve eos: {} patch eos: {}'.format(corner_eos_coef_cal, curve_eos_coef_cal, patch_eos_coef_cal))
curve_type_list = np.array(['Circle', 'BSpline', 'Line', 'Ellipse'])
patch_type_list = np.array(['Cylinder', 'Torus', 'BSpline', 'Plane', 'Cone', 'Sphere'])
curve_colormap = {'Circle': np.array([255,0,0]), 'BSpline': np.array([255,255,0]), 'Line': np.array([0,255,0]), 'Ellipse': np.array([0,0,255])}
perform_profile = False
profile_iter = 100
profile_dict = {'data_preparation':[], 'network_forwarding':[], 'backbone_forwarding':[], 'transformer_forwarding':[], 'embedding_forwarding':[], 'loss_computation':[], 'gradient_computation':[]}
def is_dist_avail_and_initialized():
if not dist.is_available():
return False
if not dist.is_initialized():
return False
return True
def get_world_size():
if not is_dist_avail_and_initialized():
return 1
return dist.get_world_size()
def get_patch_mesh_faces(dimu, dimv, uclose, begin_id = 0):
faces = []
for i in range(dimu - 1):
for j in range(dimv - 1):
id0 = i * dimv + j + begin_id
id1 = (i + 1) * dimv + j + begin_id
id2 = (i + 1) * dimv + j + 1 + begin_id
id3 = i * dimv + j + 1 + begin_id
faces.append([id0, id1, id2])
faces.append([id0, id2, id3])
if uclose:
for j in range(dimv - 1):
id0 = (dimu - 1) * dimv + j + begin_id
id1 = j + begin_id
id2 = j + 1 + begin_id
id3 = (dimu - 1) * dimv + j + 1 + begin_id
faces.append([id0, id1, id2])
faces.append([id0, id2, id3])
return np.array(faces)
# def normalize_numpy_pt(pt):
def normalized(a, axis=-1, order=2):
l2 = np.atleast_1d(np.linalg.norm(a, order, axis))
l2[l2==0] = 1
return a / np.expand_dims(l2, axis)
def get_patch_mesh_pts_faces(pts, dimu, dimv, uclose, begin_id = 0, flag_extend = False, extend_offset = 0.05):
if not flag_extend:
pts_new = pts
else:
pts_new = []
#update u v
pts = pts.reshape(dimu, dimv, 3)
uneg_dir = pts[:,1] - pts[:,0]
uneg_dir = normalized(uneg_dir)
uneg = pts[:, 0] - uneg_dir * extend_offset
upos_dir = pts[:,-1] - pts[:,-2]
upos_dir = normalized(upos_dir)
upos = pts[:,-1] + upos_dir * extend_offset
if uclose:
uneg = uneg.reshape(dimu, 1, 3)
upos = upos.reshape(dimu, 1, 3)
pts_new = np.concatenate([uneg, pts, upos], axis = 1)
dimv += 2
pts_new = pts_new.reshape(-1, 3)
else:
vneg_dir = pts[1] - pts[0]
vneg_dir = normalized(vneg_dir)
vneg = pts[0] - vneg_dir * extend_offset
vpos_dir = pts[-1] - pts[-2]
vpos_dir = normalized(vpos_dir)
vpos = pts[-1] + vpos_dir * extend_offset
unegneg_dir = uneg[1] - uneg[0]
unegneg_dir = normalized(unegneg_dir)
unegneg = uneg[0] - extend_offset * unegneg_dir
unegpos_dir = uneg[-1] - uneg[-2]
unegpos_dir = normalized(unegpos_dir)
unegpos = uneg[-1] + extend_offset * unegpos_dir
uposneg_dir = upos[1] - upos[0]
uposneg_dir = normalized(uposneg_dir)
uposneg = upos[0] - extend_offset * uposneg_dir
upospos_dir = upos[-1] - upos[-2]
upospos_dir = normalized(upospos_dir)
upospos = upos[-1] + extend_offset * upospos_dir
uneg = uneg.reshape(dimu, 1, 3)
upos = upos.reshape(dimu, 1, 3)
middle = np.concatenate([uneg, pts, upos], axis = 1)
vneg = np.concatenate([unegneg.reshape(1,-1), vneg, uposneg.reshape(1,-1)]).reshape(1, -1, 3)
vpos = np.concatenate([unegpos.reshape(1,-1), vpos, upospos.reshape(1,-1)]).reshape(1,-1,3)
pts_new = np.concatenate([vneg, middle, vpos], axis = 0)
dimv += 2
dimu += 2
pts_new = pts_new.reshape(-1,3)
faces = []
for i in range(dimu - 1):
for j in range(dimv - 1):
id0 = i * dimv + j + begin_id
id1 = (i + 1) * dimv + j + begin_id
id2 = (i + 1) * dimv + j + 1 + begin_id
id3 = i * dimv + j + 1 + begin_id
faces.append([id0, id1, id2])
faces.append([id0, id2, id3])
if uclose:
for j in range(dimv - 1):
id0 = (dimu - 1) * dimv + j + begin_id
id1 = j + begin_id
id2 = j + 1 + begin_id
id3 = (dimu - 1) * dimv + j + 1 + begin_id
faces.append([id0, id1, id2])
faces.append([id0, id2, id3])
return pts_new, np.array(faces)
def compute_overall_singlecd(patch_grids, patch_uclosed, input_pointcloud, matching_indices):
vert_id = 0
all_faces = []
all_pts = []
assert(patch_grids.shape[0] == patch_uclosed.shape[0])
set_match_id = set(matching_indices['indices'][0][0].tolist())
all_pts_matched = []
all_faces_matched = []
vert_id_matched = 0
for i in range(len(patch_grids)):
pts, faces = get_patch_mesh_pts_faces(patch_grids[i], points_per_patch_dim, points_per_patch_dim, patch_uclosed[i], vert_id, True, 0.05)
all_faces.append(faces)
vert_id += pts.shape[0]
all_pts.append(pts)
if args.eval_matched and i in set_match_id:
pts, faces = get_patch_mesh_pts_faces(patch_grids[i], points_per_patch_dim, points_per_patch_dim, patch_uclosed[i], vert_id_matched, True, 0.05)
all_faces_matched.append(faces)
vert_id_matched += pts.shape[0]
all_pts_matched.append(pts)
all_faces = np.concatenate(all_faces)
all_pts = np.concatenate(all_pts)
mesh = trimesh.Trimesh(vertices = all_pts, faces = all_faces)
(closest_points,distances,triangle_id) = mesh.nearest.on_surface(input_pointcloud[:,:3])
if not args.eval_matched:
return distances
else:
all_faces_matched = np.concatenate(all_faces_matched)
all_pts_matched = np.concatenate(all_pts_matched)
mesh_matched = trimesh.Trimesh(vertices = all_pts_matched, faces = all_faces_matched)
(closest_points,distances_matched,triangle_id) = mesh_matched.nearest.on_surface(input_pointcloud[:,:3])
return distances, distances_matched
def compute_overall_singlecd(patch_grids, patch_uclosed, input_pointcloud, patch_idx_filter):
vert_id = 0
all_faces = []
all_pts = []
assert(patch_grids.shape[0] == patch_uclosed.shape[0])
set_match_id = patch_idx_filter
all_pts_matched = []
all_faces_matched = []
vert_id_matched = 0
for i in range(len(patch_grids)):
pts, faces = get_patch_mesh_pts_faces(patch_grids[i], points_per_patch_dim, points_per_patch_dim, patch_uclosed[i], vert_id, True, 0.05)
all_faces.append(faces)
vert_id += pts.shape[0]
all_pts.append(pts)
if args.eval_matched and i in set_match_id:
pts, faces = get_patch_mesh_pts_faces(patch_grids[i], points_per_patch_dim, points_per_patch_dim, patch_uclosed[i], vert_id_matched, True, 0.05)
all_faces_matched.append(faces)
vert_id_matched += pts.shape[0]
all_pts_matched.append(pts)
all_faces = np.concatenate(all_faces)
all_pts = np.concatenate(all_pts)
mesh = trimesh.Trimesh(vertices = all_pts, faces = all_faces)
(closest_points,distances,triangle_id) = mesh.nearest.on_surface(input_pointcloud[:,:3])
#return single_cd, pcov001, pcov002
if not args.eval_matched:
return distances
else:
if len(all_faces_matched) == 0:
return distances, distances
all_faces_matched = np.concatenate(all_faces_matched)
all_pts_matched = np.concatenate(all_pts_matched)
mesh_matched = trimesh.Trimesh(vertices = all_pts_matched, faces = all_faces_matched)
(closest_points,distances_matched,triangle_id) = mesh_matched.nearest.on_surface(input_pointcloud[:,:3])
return distances, distances_matched
def compute_overall_singlecd_param(pred_data, input_pointcloud, matching_indices):
#input pointcloud is a numpy
#firstly, the grid parts
patch_close_logits = pred_data['closed_patch_logits'][0].detach().cpu().numpy()
patch_uclosed = patch_close_logits[:,0] < patch_close_logits[:,1]
if args.eval_matched:
distances, distances_matched = compute_overall_singlecd(pred_data['pred_patch_points'][0].detach().cpu().numpy(), patch_uclosed, input_pointcloud, matching_indices)
else:
distances = compute_overall_singlecd(pred_data['pred_patch_points'][0].detach().cpu().numpy(), patch_uclosed, input_pointcloud, matching_indices)
# print('distance shape: ', distances.shape)
cp_distance = ComputePrimitiveDistance(reduce = False)
routines = {
5: cp_distance.distance_from_sphere,
0: cp_distance.distance_from_cylinder,
4: cp_distance.distance_from_cone,
3: cp_distance.distance_from_plane,
}
src_patch_points = pred_data['pred_patch_points'][0]
src_with_param = pred_data['pred_patch_with_param'][0]
src_type_logits = pred_data['pred_patch_type'][0]
src_param = pred_data['pred_patch_param'][0]
input_pointcloud_torch = torch.tensor(input_pointcloud, device = src_patch_points.device)
all_dists = []
all_dists_matched = []
set_match_id = set(matching_indices['indices'][0][0].tolist())
print('all patch size: {} matched size: {}'.format(len(src_patch_points), len(set_match_id)))
for patch_idx in range(len(src_patch_points)):
if args.eval_param and src_with_param[patch_idx] > 0.5:
para_dist = routines[torch.argmax(src_type_logits[patch_idx]).item()](input_pointcloud_torch[:,:3], src_param[patch_idx], sqrt = True)
all_dists.append(para_dist.view([1, -1]))
if args.eval_matched and patch_idx in set_match_id:
all_dists_matched.append(para_dist.view([1, -1]))
res = distances
if len(all_dists) > 0:
all_dists = torch.cat(all_dists, axis = 0)
distances_all = np.concatenate([distances.reshape(1,-1), all_dists.detach().cpu().numpy()], axis = 0)
res = distances_all.min(0)
if args.eval_matched:
res_matched = distances_matched
if len(all_dists_matched) > 0:
all_dists_matched = torch.cat(all_dists_matched, axis = 0)
distances_all = np.concatenate([distances_matched.reshape(1,-1), all_dists_matched.detach().cpu().numpy()], axis = 0)
res_matched = distances_all.min(0)
return res, res_matched
return res
def compute_overall_singlecd_param(pred_data, input_pointcloud, patch_idx_filter):
#input pointcloud is a numpy
#firstly, the grid parts
patch_close_logits = pred_data['closed_patch_logits'][0].detach().cpu().numpy()
patch_uclosed = patch_close_logits[:,0] < patch_close_logits[:,1]
distances, distances_matched = compute_overall_singlecd(pred_data['pred_patch_points'][0].detach().cpu().numpy(), patch_uclosed, input_pointcloud, patch_idx_filter)
#param part
cp_distance = ComputePrimitiveDistance(reduce = False)
routines = {
5: cp_distance.distance_from_sphere,
0: cp_distance.distance_from_cylinder,
4: cp_distance.distance_from_cone,
3: cp_distance.distance_from_plane,
}
src_patch_points = pred_data['pred_patch_points'][0]
src_with_param = pred_data['pred_patch_with_param'][0]
src_type_logits = pred_data['pred_patch_type'][0]
src_param = pred_data['pred_patch_param'][0]
input_pointcloud_torch = torch.tensor(input_pointcloud, device = src_patch_points.device)
all_dists = []
all_dists_matched = []
set_match_id = patch_idx_filter
print('all patch size: {} matched size: {}'.format(len(src_patch_points), len(set_match_id)))
for patch_idx in range(len(src_patch_points)):
if args.eval_param and src_with_param[patch_idx] > 0.5:
para_dist = routines[torch.argmax(src_type_logits[patch_idx]).item()](input_pointcloud_torch[:,:3], src_param[patch_idx], sqrt = True)
all_dists.append(para_dist.view([1, -1]))
if args.eval_matched and patch_idx in set_match_id:
all_dists_matched.append(para_dist.view([1, -1]))
res = distances
if len(all_dists) > 0:
all_dists = torch.cat(all_dists, axis = 0)
distances_all = np.concatenate([distances.reshape(1,-1), all_dists.detach().cpu().numpy()], axis = 0)
res = distances_all.min(0)
if args.eval_matched:
res_matched = distances_matched
if len(all_dists_matched) > 0:
all_dists_matched = torch.cat(all_dists_matched, axis = 0)
distances_all = np.concatenate([distances_matched.reshape(1,-1), all_dists_matched.detach().cpu().numpy()], axis = 0)
res_matched = distances_all.min(0)
return res, res_matched
return res
def curve_type_to_id(str):
#Circle, BSpline, Line, Ellipse
if(str == 'Circle'):
return 0
if(str == 'BSpline'):
return 1
if(str == 'Line'):
return 2
assert(str == 'Ellipse')
return 3
def patch_type_to_id(str):
#Cylinder, Torus, BSpline, Plane, Cone, Sphere
#update 1011, add Extrusion and Revolution, label same as BSpline
if(str == 'Cylinder'):
return 0
if(str == 'Torus'):
return 1
if(str == 'BSpline' or str == 'Extrusion' or str == 'Revolution'):
return 2
if(str == 'Plane'):
return 3
if(str == 'Cone'):
return 4
assert(str == 'Sphere')
return 5
@torch.no_grad()
def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
if target.numel() == 0:
return [100.0 * torch.ones([], device=output.device)]
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].view(-1).float().sum(0)
res.append(correct_k.mul_(100.0 / batch_size))
return res
class Sparse_Backbone_Minkowski(ME.MinkowskiNetwork):
def __init__(self):
super(Sparse_Backbone_Minkowski, self).__init__(3) #dimension = 3
if(args.backbone_feature_encode): #false
self.sparseModel = resnets.ResFieldNet34(in_channels=3, out_channels=m*6, D=3)
elif args.ourresnet:
if not args.backbone_bn:
self.sparseModel = resnets.ResNetOur(in_channels=7 if args.input_normal_signals else 4, out_channels=m*6, D=3,flag_expand = args.backbone_expand) #position, normal, 1
else:
self.sparseModel = resnets.ResNetOurBn(in_channels=7 if args.input_normal_signals else 4, out_channels=m*6, D=3) #position, normal, 1
else:
self.sparseModel = resnets.ResNet34(in_channels=7 if args.input_normal_signals else 4, out_channels=m*6, D=3) #position, normal, 1
def forward(self,x):
input = ME.SparseTensor(features=x[1], coordinates=x[0])
#print(input.F)
#print(input.C)
out=self.sparseModel(input)
return out
class PositionEmbeddingSine3D(nn.Module):
"""
This is a more standard version of the position embedding, very similar to the one
used by the Attention is all you need paper, generalized to work on images.
"""
def __init__(self, voxel_dim, num_pos_feats=32, temperature=10000, normalize=False, scale=None):
super().__init__()
self.num_pos_feats = num_pos_feats
self.temperature = temperature
self.normalize = normalize
if scale is not None and normalize is False:
raise ValueError("normalize should be True if scale is passed")
if scale is None:
scale = 2 * math.pi
self.scale = scale
self.voxel_dim = voxel_dim
assert(voxel_dim > 0)
def forward(self, voxel_coord):
if self.normalize:
voxel_coord = self.scale * voxel_coord / (self.voxel_dim - 1)
dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=voxel_coord.device)
dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats)
pos = voxel_coord[:, :, None] / dim_t
pos_x = pos[:, 0]
pos_y = pos[:, 1]
pos_z = pos[:, 2]#in shape[n, pos_feature_dim]
pos_x = torch.stack((pos_x[:, 0::2].sin(), pos_x[:, 1::2].cos()), dim=2).flatten(1)
pos_y = torch.stack((pos_y[:, 0::2].sin(), pos_y[:, 1::2].cos()), dim=2).flatten(1)
pos_z = torch.stack((pos_z[:, 0::2].sin(), pos_z[:, 1::2].cos()), dim=2).flatten(1)
pos = torch.cat((pos_x, pos_y, pos_z), dim=1)#.permute(0, 3, 1, 2)
return pos
class MLP(nn.Module):
""" Very simple multi-layer perceptron (also called FFN)"""
def __init__(self, input_dim, hidden_dim, output_dim, num_layers, sin=False):
super().__init__()
self.num_layers = num_layers
h = [hidden_dim] * (num_layers - 1)
self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]))
self.sin_activation = sin
def forward(self, x):
for i, layer in enumerate(self.layers):
if(self.sin_activation):
x = layer(x).sin() if i < self.num_layers - 1 else layer(x)
else:
x = F.leaky_relu(layer(x)) if i < self.num_layers - 1 else layer(x)
return x
hn_hidden_dim = 128
flag_hidden_layer = True
class MLP_hn(nn.Module): #hypernets of MLP
def __init__(self, input_dim, hidden_dim, output_dim, num_layers, input_dim_fea):
super().__init__()
self.num_layers = num_layers
h = [hidden_dim] * (num_layers - 1)
h_plus = [hidden_dim + 1] * (num_layers - 1)
self.layers_dims = list(zip([input_dim + 1] + h_plus, h + [output_dim]))
self.layers_size = [a * b for a,b in self.layers_dims]
#ori version
if not flag_hidden_layer:
self.layer = nn.Linear(input_dim_fea, sum(self.layers_size))
else:
self.layer1 = nn.Linear(input_dim_fea, hn_hidden_dim)
self.layer2 = nn.Linear(hn_hidden_dim, sum(self.layers_size))
def forward(self, x, feature):
#ori version
if not flag_hidden_layer:
net_par = self.layer(feature)
#new version
else:
net_par = self.layer1(feature)
net_par = F.relu(net_par)
net_par = self.layer2(net_par)
if args.hn_scale:
net_par = net_par / math.sqrt(hn_pe_dim)
net_par_layers = torch.split(net_par, self.layers_size, dim=-1)
for i in range(len(self.layers_size)):
layer_par = net_par_layers[i].view(net_par.shape[0], net_par.shape[1], net_par.shape[2] ,self.layers_dims[i][0], self.layers_dims[i][1])
x = torch.einsum('...ij,...jk->...ik', x, layer_par[...,:-1,:]) + layer_par[...,-1:,:]
if i < self.num_layers - 1:
x = F.leaky_relu(x)
return x
@torch.no_grad()
def get_attention_mask(voxel_location, seq_length, tokens_each_sample, n_heads=8):
#*n_heads
mask_list = []
position_each_sample = torch.split(voxel_location, tokens_each_sample)
for i in range(args.batch_size):
voxel_position_cur_sample = position_each_sample[i].float()
cur_seq_length = voxel_position_cur_sample.shape[0]
pairwise_distance = torch.cdist(voxel_position_cur_sample, voxel_position_cur_sample)
cur_mask = F.pad(pairwise_distance > 3, (0, 0, 0, seq_length-cur_seq_length), value=False)
cur_mask = F.pad(cur_mask, (0, seq_length-cur_seq_length), value=True)
mask_list.append(cur_mask.view(1, seq_length, seq_length).repeat(n_heads, 1, 1)) #.repeat(n_heads, 1, 1)
mask = torch.cat(mask_list, 0)#
return mask
class BackBone2VoxelTokens(nn.Module):
def __init__(self, backbone, position_encoding):
super().__init__()
self.backbone = backbone
self.position_encoding = position_encoding
def forward(self, locations, features):
#for minkowski, batch index is in axis-0
locations_pos = locations[:,:3]
locations_batch_idx = locations[:,-1:]
locations = torch.cat([locations_batch_idx, locations_pos], dim=1)
output = self.backbone([locations, features])
sparse_locations = output.C#.to(device)
sparse_features = output.F
#Padding voxel features and corner points
batch_idx = sparse_locations[:,0]#which sample each voxel belongs to
sparse_locations = sparse_locations[:,1:] // output.tensor_stride[0]
input_padding_mask = torch.zeros_like(batch_idx, dtype=torch.bool, device=sparse_features.device)
batch_number_samples = []
for i in range(args.batch_size):
batch_number_samples.append((batch_idx == i).sum())
pad_dim = max(batch_number_samples)
if(args.using_local_attention):
attention_mask = get_attention_mask(sparse_locations, pad_dim, batch_number_samples, n_heads=args.nheads) #not used
else:
attention_mask = None
voxel_pos_embedding = self.position_encoding(sparse_locations)
voxel_feature = torch.split(sparse_features, batch_number_samples)
voxel_pos_embedding = torch.split(voxel_pos_embedding, batch_number_samples)
input_padding_mask = torch.split(input_padding_mask, batch_number_samples)
batch_voxel_feature = []
input_padding_mask_list = []
position_embedding_list = []
for i in range(args.batch_size):
batch_voxel_feature.append(nn.functional.pad(voxel_feature[i], (0, 0, 0, pad_dim - voxel_feature[i].shape[0])))
input_padding_mask_list.append(nn.functional.pad(input_padding_mask[i], (0, pad_dim - voxel_feature[i].shape[0]), value=True))
position_embedding_list.append(nn.functional.pad(voxel_pos_embedding[i], (0, 0, 0, pad_dim - voxel_feature[i].shape[0])))
voxel_features = torch.stack(batch_voxel_feature, dim=1)
voxel_features_padding_mask = torch.stack(input_padding_mask_list, dim=0)
voxel_position_encoding = torch.stack(position_embedding_list, dim=1)
return voxel_features, voxel_position_encoding, voxel_features_padding_mask, torch.split(torch.cat((batch_idx.view(-1,1), sparse_locations), dim=-1), batch_number_samples), attention_mask
class DETR_Corner_Tripath(nn.Module):
""" This is the DETR module that performs geometric primitive detection """
def __init__(self, num_queries, hidden_dim, aux_loss=False): #num_classes is not used for corner detection #backbone
""" Initializes the model.
Parameters:
backbone: torch module of the backbone to be used. See backbone.py
transformer: torch module of the transformer architecture. See transformer.py
num_classes: number of object classes
num_queries: number of object queries, ie detection slot. This is the maximal number of objects
DETR can detect in a single image. For COCO, we recommend 100 queries.
aux_loss: True if auxiliary decoding losses (loss at each decoder layer) are to be used.
"""
super().__init__()
self.num_queries = num_queries
self.empty_prediction_embed = nn.Linear(hidden_dim, 2)#num_classes + 1, empty or non-empty
self.corner_position_embed = MLP(hidden_dim, hidden_dim, 3, 3) #was bbox embed
self.aux_loss = aux_loss
if not args.no_topo:
if True:
self.corner_topo_embed_curve = MLP(hidden_dim, args.topo_embed_dim, args.topo_embed_dim, 1) #topo embed dim:256, matrix_eigen_similarity: False
self.corner_topo_embed_patch = MLP(hidden_dim, args.topo_embed_dim, args.topo_embed_dim, 1) #topo embed dim:256, matrix_eigen_similarity: False
def forward(self, hs):
""" The forward expects a NestedTensor, which consists of:
- samples.tensor: batched images, of shape [batch_size x 3 x H x W]
- samples.mask: a binary mask of shape [batch_size x H x W], containing 1 on padded pixels
It returns a dict with the following elements:
- "pred_logits": the classification logits (including no-object) for all queries.
Shape= [batch_size x num_queries x (num_classes + 1)]
- "pred_boxes": The normalized boxes coordinates for all queries, represented as
(center_x, center_y, height, width). These values are normalized in [0, 1],
relative to the size of each individual image (disregarding possible padding).
See PostProcess for information on how to retrieve the unnormalized bounding box.
- "aux_outputs": Optional, only returned when auxilary losses are activated. It is a list of
dictionnaries containing the two above keys for each decoder layer.
"""
outputs_corner_coord = self.corner_position_embed(hs).tanh()*0.5 # [-0.5,0.5] #6,1,100,3
outputs_class = self.empty_prediction_embed(hs) #to be consistent with curve and patch type prediction, we treat 0 as non-empty and 1 as empty
if not args.no_topo:
if(args.normalize_embed_feature):
output_corner_topo_embedding = F.normalize(self.corner_topo_embed(hs), dim=-1)
else:
if True:
output_corner_topo_embedding_curve = self.corner_topo_embed_curve(hs)
output_corner_topo_embedding_patch = self.corner_topo_embed_patch(hs)
if not args.no_topo:
if True:
out = {'pred_logits': outputs_class[-1], 'pred_corner_position': outputs_corner_coord[-1], 'corner_topo_embed_curve': output_corner_topo_embedding_curve[-1], 'corner_topo_embed_patch': output_corner_topo_embedding_patch[-1]} #only return last layer info
if self.aux_loss:
out['aux_outputs'] = self._set_aux_loss(outputs_class, outputs_corner_coord, output_corner_topo_embedding)
else:
out = {'pred_logits': outputs_class[-1], 'pred_corner_position': outputs_corner_coord[-1]} #only return last layer info
return out
@torch.jit.unused
def _set_aux_loss(self, outputs_class, outputs_coord, output_corner_topo_embedding):
# this is a workaround to make torchscript happy, as torchscript
return [{'pred_logits': a, 'pred_corner_position': b, 'corner_topo_embed': c}
for a, b, c in zip(outputs_class[:-1], outputs_coord[:-1], output_corner_topo_embedding[:-1])]
# detr curve
flag_hn_with_coord = True
class DETR_Curve_Tripath(nn.Module):
""" This is the DETR module that performs geometric primitive detection - Curves """
def __init__(self, num_queries, hidden_dim, aux_loss=False, device = None): #num_classes is not used for corner detection #backbone
""" Initializes the model.
Parameters:
backbone: torch module of the backbone to be used. See backbone.py
transformer: torch module of the transformer architecture. See transformer.py
num_classes: number of object classes
num_queries: number of object queries, ie detection slot. This is the maximal number of objects
DETR can detect in a single image. For COCO, we recommend 100 queries.
aux_loss: True if auxiliary decoding losses (loss at each decoder layer) are to be used.
"""
super().__init__()
self.num_queries = num_queries
self.valid_curve_embed = MLP(hidden_dim, hidden_dim, 2, args.curve_embedding_mlp_layers)
self.curve_type_prediction_embed = MLP(hidden_dim, hidden_dim, 4, args.curve_embedding_mlp_layers)
self.closed_curve_embed = MLP(hidden_dim, hidden_dim, 2, 3) #not closed, closed
self.aux_loss = aux_loss
self.curve_start_point_embed = MLP(hidden_dim, hidden_dim, 3, 3)
if args.no_pe:
if True:
#no pe
self.curve_shape_embed = MLP_hn(1, hn_mlp_dim, 3, 3, hidden_dim)
self.curve_pe = (torch.arange(points_per_curve, dtype=torch.float32, device=device) / (points_per_curve - 1)).view(points_per_curve,1)
elif not args.pe_sin:
if args.ori_mlp:
self.curve_shape_embed = MLP(hidden_dim + 1, hidden_dim, 3, 6, sin=args.sin) #ori version
else:
if flag_hn_with_coord:
self.curve_shape_embed = MLP_hn(hn_pe_dim + 1, hn_mlp_dim, 3, 3, hidden_dim)
else:
self.curve_shape_embed = MLP_hn(hn_pe_dim, hn_mlp_dim, 3, 3, hidden_dim)
self.curve_pe = nn.Embedding(points_per_curve, hn_pe_dim)
else:
self.curve_shape_embed = MLP_hn(hn_pe_dim, hn_mlp_dim, 3, 3, hidden_dim)
coord = (torch.arange(points_per_curve, dtype=torch.float32, device=device) / (points_per_curve - 1)).view(-1,1)
exp = torch.arange(hn_pe_dim//2, dtype=torch.float32, device=device)
base = args.pe_sin_base * torch.ones([hn_pe_dim//2], dtype=torch.float32, device=device)
coeff = 2 * math.pi * torch.pow(base, exp).view(1,-1)
mat = torch.mm(coord, coeff)
sin_mat = torch.sin(mat).view(-1,1)
cos_mat = torch.cos(mat).view(-1,1)
self.curve_pe = torch.cat([sin_mat, cos_mat], dim=1).view(points_per_curve, hn_pe_dim)
if not args.no_topo:
if True:
self.curve_topo_embed_corner = MLP(hidden_dim, args.topo_embed_dim, args.topo_embed_dim, 1)
self.curve_topo_embed_patch = MLP(hidden_dim, args.topo_embed_dim, args.topo_embed_dim, 1)
if flag_using_scale:
self.curve_shape_scale_embed = MLP(hidden_dim, hidden_dim, 1, 3)
'''
self.line_embed = MLP(hidden_dim, hidden_dim, 6, 3) #predict start point position, end point position
self.circle_embed = MLP(hidden_dim, hidden_dim, 11, 3) #predict center of circle, radius, start points of arc(axis=0), angle of arc, axis-1(make orthogonal to axis-0)
self.ellipse_embed = MLP(hidden_dim, hidden_dim, 7, 3) #predict center of ellipse, axis-0 radius, start(axis-0 direction), axis-1 direction and radius, end points of arc, angle of arc
self.bSpline_startpoint_embed = MLP(hidden_dim, hidden_dim, 5, 3) #predict start position as well as parameterization space of spline
self.bSpline_shape_embed = MLP(hidden_dim+1, hidden_dim, 3, 3) #predict shape of spline
'''
def forward(self, hs):
""" The forward expects a NestedTensor, which consists of:
- samples.tensor: batched images, of shape [batch_size x 3 x H x W]
- samples.mask: a binary mask of shape [batch_size x H x W], containing 1 on padded pixels
It returns a dict with the following elements:
- "pred_logits": the classification logits (including no-object) for all queries.
Shape= [batch_size x num_queries x (num_classes + 1)]
- "pred_boxes": The normalized boxes coordinates for all queries, represented as
(center_x, center_y, height, width). These values are normalized in [0, 1],
relative to the size of each individual image (disregarding possible padding).
See PostProcess for information on how to retrieve the unnormalized bounding box.
- "aux_outputs": Optional, only returned when auxilary losses are activated. It is a list of
dictionnaries containing the two above keys for each decoder layer.
"""
outputs_start_point_coord = self.curve_start_point_embed(hs).tanh()*0.5 # [-0.5,0.5]
if not flag_using_scale:
curve_shape_scale = 1#F.elu(self.curve_shape_scale_embed(hs)).unsqueeze(-2) + 1.0
else:
curve_shape_scale = F.elu(self.curve_shape_scale_embed(hs)).unsqueeze(-2) + 1.0
parameterization_coord = (torch.arange(points_per_curve, dtype=torch.float32, device=hs.device) / (points_per_curve - 1)).view(1, 1, 1, points_per_curve, 1).repeat(1, args.batch_size, args.num_curve_queries, 1, 1)
if args.no_pe:
if True:
sampled_points_feature = self.curve_pe.view(1,1,1,points_per_curve, 1).repeat(1, args.batch_size, args.num_curve_queries, 1,1)
sampled_points = outputs_start_point_coord.unsqueeze(-2).repeat(1,1,1,points_per_curve,1) + self.curve_shape_embed(sampled_points_feature, hs)
elif not args.pe_sin:
if args.ori_mlp:
sampled_points_feature = torch.cat([hs.unsqueeze(-2).repeat(1, 1, 1, points_per_curve, 1), parameterization_coord], dim=-1)
sampled_points = outputs_start_point_coord.unsqueeze(-2).repeat(1,1,1,points_per_curve,1) + curve_shape_scale*self.curve_shape_embed(sampled_points_feature)
else:
if flag_hn_with_coord:
sampled_points_feature = torch.cat([self.curve_pe.weight.view(1,1,1,points_per_curve, hn_pe_dim).repeat(1, args.batch_size, args.num_curve_queries, 1,1), parameterization_coord], dim=-1)
else:
sampled_points_feature = self.curve_pe.weight.view(1,1,1,points_per_curve, hn_pe_dim).repeat(1, args.batch_size, args.num_curve_queries, 1,1)
sampled_points = outputs_start_point_coord.unsqueeze(-2).repeat(1,1,1,points_per_curve,1) + self.curve_shape_embed(sampled_points_feature, hs)
else:
sampled_points_feature = self.curve_pe.view(1,1,1,points_per_curve, hn_pe_dim).repeat(1, args.batch_size, args.num_curve_queries, 1,1)
sampled_points = outputs_start_point_coord.unsqueeze(-2).repeat(1,1,1,points_per_curve,1) + self.curve_shape_embed(sampled_points_feature, hs)
is_curve_closed_logits = self.closed_curve_embed(hs)
is_curve_valid_pred = self.valid_curve_embed(hs)
outputs_class = self.curve_type_prediction_embed(hs) #Circle, BSpline, Line, Ellipse or non-empty
if not args.no_topo:
if(args.normalize_embed_feature):
output_curve_topo_embedding = F.normalize(self.curve_topo_embed(hs), dim=-1)
else:
if True:
output_curve_topo_embedding_corner = self.curve_topo_embed_corner(hs)
output_curve_topo_embedding_patch = self.curve_topo_embed_patch(hs)
if not args.no_topo:
if True:
out = {'pred_curve_logits': is_curve_valid_pred[-1], 'pred_curve_type': outputs_class[-1], 'pred_curve_points': sampled_points[-1], 'closed_curve_logits':is_curve_closed_logits[-1], 'curve_topo_embed_corner': output_curve_topo_embedding_corner[-1], 'curve_topo_embed_patch': output_curve_topo_embedding_patch[-1]}
if self.aux_loss:
out['aux_outputs'] = self._set_aux_loss(is_curve_valid_pred, outputs_class, sampled_points, is_curve_closed_logits, output_curve_topo_embedding)
else:
out = {'pred_curve_logits': is_curve_valid_pred[-1], 'pred_curve_type': outputs_class[-1], 'pred_curve_points': sampled_points[-1], 'closed_curve_logits':is_curve_closed_logits[-1]}
return out
@torch.jit.unused
def _set_aux_loss(self, is_curve_valid_pred, outputs_class, outputs_coord, closed_curve_logits, output_curve_topo_embedding):
# this is a workaround to make torchscript happy, as torchscript
# doesn't support dictionary with non-homogeneous values, such
# as a dict having both a Tensor and a list.
return [{'pred_curve_logits': e, 'pred_curve_type': a, 'pred_curve_points': b, 'closed_curve_logits': c, "curve_topo_embed": d}
for a, b, c, d, e in zip(outputs_class[:-1], outputs_coord[:-1], closed_curve_logits[:-1], output_curve_topo_embedding[:-1], is_curve_valid_pred[:-1])]
class DETR_Patch_Tripath(nn.Module):
""" This is the DETR module that performs geometric primitive detection - Curves """
def __init__(self, num_queries,hidden_dim, aux_loss=False, device = None): #num_classes is not used for corner detection #backbone
""" Initializes the model.
Parameters:
backbone: torch module of the backbone to be used. See backbone.py
transformer: torch module of the transformer architecture. See transformer.py
num_classes: number of object classes
num_queries: number of object queries, ie detection slot. This is the maximal number of objects
DETR can detect in a single image. For COCO, we recommend 100 queries.
aux_loss: True if auxiliary decoding losses (loss at each decoder layer) are to be used.
"""
super().__init__()
self.num_queries = num_queries
self.valid_patch_embed = MLP(hidden_dim, hidden_dim, 2, args.curve_embedding_mlp_layers)
#Cylinder, Torus, BSpline, Plane, Cone, Sphere
self.patch_type_prediction_embed = MLP(hidden_dim, hidden_dim, 6, args.curve_embedding_mlp_layers)
if args.patch_close:
self.closed_patch_embed = MLP(hidden_dim, hidden_dim, 2, 3) #not closed, closed
self.aux_loss = aux_loss
self.patch_center_embed = MLP(hidden_dim, hidden_dim, 3, 3)
if flag_using_scale:
self.patch_shape_scale_embed = MLP(hidden_dim, hidden_dim, 1, 3)
output_dim = 3
if args.output_normal:
output_dim = 6
if args.no_pe:
self.patch_shape_embed = MLP_hn(2, hn_mlp_dim, output_dim, 3, hidden_dim)
self.patch_pe_x = (torch.arange(points_per_patch_dim, dtype=torch.float32, device=device) / (points_per_patch_dim - 1)).view(points_per_patch_dim,1)
self.patch_pe_y = (torch.arange(points_per_patch_dim, dtype=torch.float32, device=device) / (points_per_patch_dim - 1)).view(points_per_patch_dim,1)
elif args.spe:
self.patch_shape_embed = MLP_hn(6, hn_mlp_dim, output_dim, 3, hidden_dim)
coordx = (torch.arange(points_per_patch_dim, dtype=torch.float32, device=device) / (points_per_patch_dim - 1)).view(points_per_patch_dim,1)
sin_mat_x = torch.sin(2 * math.pi * coordx).view(-1,1)
cos_mat_x = torch.cos(2 * math.pi * coordx).view(-1,1)
self.patch_pe_x = torch.cat([coordx, sin_mat_x, cos_mat_x], dim=1).view(points_per_patch_dim, 3)
coordy = (torch.arange(points_per_patch_dim, dtype=torch.float32, device=device) / (points_per_patch_dim - 1)).view(points_per_patch_dim,1)
sin_mat_y = torch.sin(2 * math.pi * coordy).view(-1,1)
cos_mat_y = torch.cos(2 * math.pi * coordy).view(-1,1)