forked from gabrieletiboni/MaskPlanner
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloss_handler.py
More file actions
1818 lines (1334 loc) · 86.5 KB
/
loss_handler.py
File metadata and controls
1818 lines (1334 loc) · 86.5 KB
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
"""Handler class for loss function terms
To add a loss term:
- insert its name and its method name in the constructor
- add the method implementation itself
- add a --weight_<lossname> arg parameter
"""
from threadpoolctl import threadpool_limits
import pdb
import numpy as np
from scipy.optimize import linear_sum_assignment
import torch
import torch.nn.functional as F
import torch.nn as nn
from torch.autograd import Variable
try:
from pytorch3d_chamfer import chamfer_distance
except ImportError:
print(f'Warning! Unable to import pytorch3d package.'\
f'Chamfer distance with velocities won\'t be available.'\
f'(Check troubleshooting.txt for info on how to install pytorch3d)')
pass
from models.dgcnn import DGCNNDiscriminator
from models.pointnet2_cls_ssg import PointNet2Regressor
from models.pointnet import PointNetRegressor
from models.mlp import MLP
from models.gradient_penalty import GradientPenalty
from utils import orient_in
from utils.pointcloud import get_dim_traj_points, mean_knn_distance
class LossHandler():
def __init__(self, loss, config=None):
"""
loss : list of str
list of loss terms, each weighted by the
corresponding specified weight as command argument
config : dict with loss term weights
"""
self.loss_names = ['chamfer',
'repulsion',
'mse',
'align',
'velcosine',
'intra_align',
'discriminator',
'wdiscriminator',
'attraction_chamfer',
'rich_attraction_chamfer',
'contrastive_v1',
'asymm_segment_chamfer',
'reverse_asymm_point_chamfer',
'stoch_reverse_asymm_segment_chamfer',
'reverse_asymm_segment_chamfer',
'chamfer_bbox',
'mse_strokes',
'chamfer_strokes',
'asymm_v6_chamfer_strokes',
'masked_mse_strokes',
'masked_mse_strokes_v2',
'symm_segment_chamfer',
'symm_point_chamfer',
'mse_nexttoken', # used for autoregressive_v1 rollout task
'mse_nexttoken_v2', # used for autoregressive_v2 rollout task
'emd', # Earth mover's distance (hungarian matching + MSE)
'chamfer_with_stroke_masks', # chamfer distance + loss on matched stroke masks
'asymm_v6_chamfer_with_stroke_masks', # asymm_chamfer_v6.yaml + loss on matched stroke masks
'asymm_v11_chamfer_with_stroke_masks', # asymm_chamfer_v11.yaml + loss on matched stroke masks
'symm_v1_chamfer_with_stroke_masks',
'masked_mse_strokes_from_segments',
'hungarian_SoPs'
]
self.loss_methods = [self.get_chamfer,
self.get_repulsion,
self.get_mse,
self.get_align_loss,
self.get_vel_cosine,
self.get_intra_align,
self.get_discr_loss,
self.get_wdiscr_loss,
self.get_attraction_chamfer,
self.get_rich_attraction_chamfer,
self.get_contrastive_v1,
self.get_asymm_segment_chamfer,
self.get_reverse_asymm_point_chamfer,
self.get_stoch_reverse_asymm_segment_chamfer,
self.get_reverse_asymm_segment_chamfer,
self.get_chamfer_bbox,
self.get_mse_strokes,
self.get_chamfer_strokes,
self.get_asymm_v6_chamfer_strokes,
self.get_masked_mse_strokes,
self.get_masked_mse_strokes_v2,
self.get_symm_segment_chamfer,
self.get_symm_point_chamfer,
self.get_mse_nexttoken,
self.get_mse_nexttoken_v2,
self.get_emd,
self.get_chamfer_with_stroke_masks,
self.get_asymm_v6_chamfer_with_stroke_masks,
self.get_asymm_v11_chamfer_with_stroke_masks,
self.get_symm_v1_chamfer_with_stroke_masks,
self.masked_mse_strokes_from_segments,
self.get_hungarian_SoPs]
self.loss_index = {loss_name: i for i, loss_name in enumerate(self.loss_names)}
assert (set(loss) <= set(self.loss_names)), f'Specified loss list {loss} contains non-valid names ({self.loss_names})'
self.loss = list(loss)
self.config = config
"""
Loss initializations
"""
if 'discriminator' in self.loss: # Initialize discriminator
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.D = DGCNNDiscriminator(inputdim=3, k=self.config['knn_gcn']).to(self.device)
self.minimax_loss = nn.BCEWithLogitsLoss().cuda()
self.D_optimizer = torch.optim.Adam(self.D.parameters(), lr=0.0001, betas=(0.9, 0.999))
if 'wdiscriminator' in self.loss: # Initialize wasserstein discriminator
assert not (config.discr_input_type == 'singlestrokes' and config.discr_backbone != 'mlp'), f'Discr input type "singlestrokes" only supports discr_backbone "mlp".'
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
outdim = get_dim_traj_points(config.extra_data) # Single pose dimensionality
if config.discr_input_type == 'pointcloud':
discr_input_dim = outdim
elif config.discr_input_type == 'strokecloud':
discr_input_dim = outdim*config.stroke_points
elif config.discr_input_type == 'singlestrokes':
discr_input_dim = outdim*config.stroke_points
else:
ValueError(f'Discriminator input type is not valid: {config.discr_input_type}')
if config.discr_backbone == 'dgcnn':
self.D = DGCNNDiscriminator(inputdim=discr_input_dim, k=self.config['knn_gcn']).to(self.device)
elif config.discr_backbone == 'pointnet2':
self.D = PointNet2Regressor(inputdim=discr_input_dim,
out_vectors=1,
outdim=1,
outdim_orient=0,
hidden_size=[512, 128]).to(self.device)
elif config.discr_backbone == 'pointnet':
self.D = PointNetRegressor(inputdim=discr_input_dim,
out_vectors=1,
outdim=1,
hidden_size=[512, 128]).to(self.device)
elif config.discr_backbone == 'mlp':
self.D = MLP(input_size=discr_input_dim, hidden_sizes=[512, 256, 128], output_size=1).to(self.device)
else:
raise ValueError(f'Discriminator backbone is not valid: {config.discr_backbone}')
self.GradPenalty = GradientPenalty(self.config['discr_lambdaGP'], gamma=1, device=self.device)
self.D_optimizer = torch.optim.Adam(self.D.parameters(), lr=0.0001, betas=(0.9, 0.999))
if 'contrastive_v1' in self.loss:
self.margin = config.contrastive_loss_margin
self.contrastive_balance_negatives = config.contrastive_balance_negatives
self.max_workers = config.max_workers
if 'masked_mse_strokes' in self.loss or \
'masked_mse_strokes_v2' in self.loss:
self.bcewithlogits = nn.BCEWithLogitsLoss(reduction='none').cuda()
if 'emd' in self.loss or 'hungarian_SoPs' in self.loss:
from models.hungarianMatcher import HungarianMatcher
self.matcher = HungarianMatcher()
"""
Asserts for loss compatibility
"""
for l in self.loss:
assert 'weight_'+str(l) in self.config.keys(), f'weight parameter does not exist in the current config' \
f' for loss {l}. Make sure to include a --weight_<loss_name> arg par for each loss you use.'
assert not ('chamfer' in self.loss and 'mse' in self.loss), f'Incompatible losses: chamfer with mse'
if self.config['lambda_points'] > 1:
assert set(loss) <= {'hungarian_SoPs', 'masked_mse_strokes_from_segments', 'asymm_v6_chamfer_with_stroke_masks', 'symm_v1_chamfer_with_stroke_masks', 'asymm_v11_chamfer_with_stroke_masks', 'chamfer_with_stroke_masks', 'emd', 'chamfer', 'symm_segment_chamfer', 'symm_point_chamfer', 'intra_align', 'attraction_chamfer', 'rich_attraction_chamfer', 'repulsion', 'contrastive_v1', 'asymm_segment_chamfer', 'reverse_asymm_point_chamfer', 'stoch_reverse_asymm_segment_chamfer', 'reverse_asymm_segment_chamfer', 'chamfer_strokes', 'mse_nexttoken', 'mse_nexttoken_v2'}, 'Losses must be one of the following when lambda > 1.'
assert not ('discriminator' in self.loss and 'wdiscriminator' in self.loss), 'Choose between Minimax discriminator and Wasserstein Discriminator'
if 'intra_align' in self.loss:
assert self.config['lambda_points'] > 3, 'Fitting a plane to 3 points in 3D would always have degenerate covariance matrix.'
if 'align' in self.loss:
assert 'mse' not in self.loss, 'Align loss is not meant to be used with MSE'
assert self.config['knn_repulsion'] > 1, 'Using Align loss with 1 NN -> unexplained variance would always be zero.'
if 'attraction_chamfer' in self.loss:
assert self.config['lambda_points'] > 1
if 'rich_attraction_chamfer' in self.loss:
assert self.config['lambda_points'] > 1
assert orient_in(self.config['extra_data'])[0]
assert 'vel' not in self.config['extra_data']
if 'asymm_segment_chamfer' in self.loss or 'stoch_reverse_asymm_segment_chamfer' in self.loss or 'reverse_asymm_point_chamfer' in self.loss or 'reverse_asymm_segment_chamfer' in self.loss:
assert self.config['lambda_points'] > 1
if 'masked_mse_strokes' in self.loss:
assert self.config['lambda_points'] == 1, 'the number of GT points per stroke is computed automatically from the traj, and lambda must be one to create it correctly.'
if 'masked_mse_strokes_v2' in self.loss:
assert self.config['lambda_points'] == 1, 'the number of GT points per stroke is computed automatically from the traj, and lambda must be one to create it correctly.'
if 'symm_point_chamfer' in self.loss:
assert self.config['lambda_points'] > 1, 'symm_point_chamfer is designed for weight scheduling which progressively give more importance to segments predictions. Why are you using it with lambda=1?'
return
def compute(self, return_list=True, **loss_args):
"""Return loss function
return_list: bool
if True, additionally return seperate loss terms as list
"""
loss_val = 0
loss_val_list = []
for l in self.loss: # Compute each loss term
l_ind = self.loss_index[l]
l_value = self.loss_methods[l_ind]( **loss_args ) # (y_pred, y, **loss_args) as input parameters
loss_val += self.config['weight_'+str(l)]*l_value # Weight * loss_term
loss_val_list.append(l_value.detach().cpu().numpy())
if return_list:
return loss_val, np.array(loss_val_list)
else:
return loss_val
def log_on_wandb(self, loss_list, wandb, epoch, suffix='_train_loss'):
"""Log loss list on wandb"""
loss_list_names = self.loss.copy()
if 'discriminator' in self.loss or 'wdiscriminator' in self.loss:
if self.last_discr_internal_loss is not None:
loss_list_names.append('discr_internal')
loss_list = np.append(loss_list, self.last_discr_internal_loss.detach().cpu().numpy())
for loss_term, train_loss_term in zip(loss_list_names, loss_list):
wandb.log({str(loss_term)+str(suffix): train_loss_term, "epoch": (epoch+1)})
def pprint(self, loss_values, prefix=''):
"""Pretty print loss values"""
print(prefix)
for name, value in zip(self.loss, loss_values):
print(f"{name}:\t{round(value, 3)}")
print('------------')
"""
Loss list
"""
def get_discr_loss(self, y_pred, y, **args):
"""A discriminator is used to learn a loss
function adversarially (mesh-agnostic).
"""
y, y_pred = y.permute(0, 2, 1), y_pred.permute(0, 2, 1) # B, outdim*stroke_points, n_stroke
###### DISCRIMINATOR TRAINING ######
if 'train' not in args or args['train'] == True:
self.D.train()
self.D.zero_grad()
real_out = self.D(y)
real_loss = self.minimax_loss(real_out, Variable(torch.ones(real_out.size()).to(self.device))) # -log(D(traj_real))
fake_out = self.D(y_pred.detach())
fake_loss = self.minimax_loss(fake_out, Variable(torch.zeros(fake_out.size()).to(self.device))) # -log(1-D(traj_predicted))
d_loss = self.config['weight_discr_training']*(real_loss + fake_loss)
d_loss.backward()
self.D_optimizer.step()
self.last_discr_internal_loss = d_loss
else:
self.D.train(False)
self.last_discr_internal_loss = torch.zeros(1)
####################################
###### Learned loss term #########
D_out = self.D(y_pred)
learned_loss = self.minimax_loss(D_out, Variable(torch.ones(D_out.size()).to(self.device))) # -log(D(traj_predicted))
####################################
return learned_loss
def get_wdiscr_loss(self, y_pred, y, **args):
"""Wasserstein-loss discriminator
https://github.com/jtpils/TreeGAN
"""
if self.config.discr_input_type == 'pointcloud': # Reshape strokes as 3D point-clouds
outdim = get_dim_traj_points(self.config.extra_data)
B = y.shape[0]
y = y.reshape(B, -1, outdim) # (B, traj_points, 3)
y_pred = y_pred.reshape(B, -1, outdim) # (B, traj_points, 3)
y, y_pred = y.permute(0, 2, 1), y_pred.permute(0, 2, 1) # B, outdim*stroke_points, n_strokes
elif self.config.discr_input_type == 'strokecloud':
y, y_pred = y.permute(0, 2, 1), y_pred.permute(0, 2, 1) # B, outdim*stroke_points, n_strokes
elif self.config.discr_input_type == 'singlestrokes': # Stack all individual strokes in batch_size dimension
outdim = get_dim_traj_points(self.config.extra_data)
B = y.shape[0]
y = y.view(B*self.config.n_strokes, -1) # (B*n_strokes, stroke_points*outdim)
y_pred = y_pred.view(B*self.config.n_strokes, -1)
if self.config.singlestrokes_norm: # Standardize single strokes to zero mean
y = y.reshape(B*self.config.n_strokes, self.config.stroke_points, outdim) # shape is (B*n_strokes, N, 3)
y_mean = y.mean(dim=1, keepdim=True) # shape is (B*n_strokes, 1, 3)
y = y - y_mean # shape is (B*n_strokes, N, 3)
y_pred = y_pred.reshape(B*self.config.n_strokes, self.config.stroke_points, outdim) # shape is (B*n_strokes, N, 3)
y_pred_mean = y_pred.mean(dim=1, keepdim=True) # shape is (B*n_strokes, 1, 3)
y_pred = y_pred - y_pred_mean # shape is (B*n_strokes, N, 3)
# --- Standardization to unit scale is ill-posed as cuboids have zero-variance on one dimension (flat strokes)
# y_std = y.std(dim=1, keepdim=True) # shape is (B*n_strokes, 1, 3)
# y = y / y_std # shape is (B*n_strokes, N, 3)
# --- visualize set of points y
# fig = plt.figure()
# ax = fig.add_subplot(111, projection='3d')
# ax.scatter(y[:6, :, 0].detach().cpu().numpy(), y[:6, :, 1].detach().cpu().numpy(), y[:6, :, 2].detach().cpu().numpy())
# plt.show()
y = y.reshape(B*self.config.n_strokes, self.config.stroke_points*outdim) # shape is (N*n_strokes, N*3)
y_pred = y_pred.reshape(B*self.config.n_strokes, self.config.stroke_points*outdim) # shape is (N*n_strokes, N*3)
# -------------------- Discriminator -------------------- #
discr_train_frequency_mask = ('epoch' not in args) or (args['epoch'] % self.config.discr_train_freq == 0) # Train discriminator once every self.config.discr_train_freq epochs
discr_train_flag = ('train' not in args or args['train'] == True)
if discr_train_flag and discr_train_frequency_mask: # Train discriminator
self.D.train()
for d_iter in range(self.config['discr_train_iter']):
self.D.zero_grad()
D_real = self.D(y)
D_realm = D_real.mean()
D_fake = self.D(y_pred.detach())
D_fakem = D_fake.mean()
gp_loss = self.GradPenalty(self.D, y.data, y_pred.detach().data)
d_loss = self.config.weight_discr_training*(-D_realm + D_fakem)
d_loss_gp = d_loss + gp_loss
d_loss_gp.backward()
self.D_optimizer.step()
self.last_discr_internal_loss = d_loss_gp
else:
self.last_discr_internal_loss = None
# ---------------------- Generator ---------------------- #
self.D.train(False)
G_fake = self.D(y_pred)
G_fakem = G_fake.mean()
g_loss = -G_fakem
return g_loss
def get_wdiscr_loss_chatgpt(self, y_pred, y, **args):
"""Code generated by chatGPT when asked to create
a WGAN"""
# config.discr_on_point_clouds is deprecated (use discr_input_type)
# if self.config.discr_on_point_clouds: # Reshape strokes as 3D point-clouds
# outdim = get_dim_traj_points(self.config.extra_data)
# B = y.shape[0]
# y = y.reshape(B, -1, outdim) # (B, traj_points, 3)
# y_pred = y_pred.reshape(B, -1, outdim) # (B, traj_points, 3)
y, y_pred = y.permute(0, 2, 1), y_pred.permute(0, 2, 1) # B, outdim*stroke_points, n_strokes
# -------------------- Discriminator -------------------- #
discr_train_frequency_mask = ('epoch' not in args) or (args['epoch'] % self.config.discr_train_freq == 0) # Train discriminator once every self.config.discr_train_freq epochs
discr_train_flag = ('train' not in args or args['train'] == True)
if discr_train_flag and discr_train_frequency_mask: # Train discriminator
self.D.train()
for d_iter in range(self.config['discr_train_iter']):
# Compute the output of the discriminator for the real and generated data
real_output = self.D(y)
generated_output = self.D(y_pred)
# Compute the Wasserstein loss and gradients for the discriminator
D_loss = wasserstein_loss_chatgpt(real_output, generated_output)
D_loss.backward()
# Update the weights of the discriminator using the optimizer
self.D_optimizer.step()
self.last_discr_internal_loss = D_loss
else:
self.last_discr_internal_loss = None
# ---------------------- Generator ---------------------- #
self.D.eval()
generated_output = self.D(y_pred)
# Compute the Wasserstein loss and gradients for the generator
G_loss = wasserstein_loss(torch.ones_like(generated_output), generated_output, generator=True)
# G_loss.backward()
# Update the weights of the generator using the optimizer
# optimizer_G.step()
return G_loss
def wasserstein_loss_chatgpt(real_output, generated_output, generator=False):
# Compute the Wasserstein distance between the real and generated distributions
if generator:
w_loss = -torch.mean(generated_output)
else:
w_loss = -torch.mean(real_output) + torch.mean(generated_output)
# Implement the gradient penalty term
alpha = torch.rand(real_output.size(0), 1)
interpolated = alpha * real_output + (1 - alpha) * generated_output
interpolated = torch.autograd.Variable(interpolated, requires_grad=True)
interpolated_output = discriminator(interpolated)
grad = torch.autograd.grad(outputs=interpolated_output, inputs=interpolated,
grad_outputs=torch.ones_like(interpolated_output),
create_graph=True, retain_graph=True)[0]
grad_penalty = 10 * torch.mean((grad.norm(2, dim=1) - 1) ** 2)
# Return the total loss
return w_loss + grad_penalty
def get_rich_attraction_chamfer(self, y_pred, **args):
"""first and last points are enriched with orientation and inferred velocity.
See attraction_loss for the standard version.
"""
outdim = get_dim_traj_points(self.config['extra_data'])
starting_points = y_pred[:, :, :outdim]
ending_points = y_pred[:, :, -outdim:]
inferred_vel_starting = y_pred[:, :, outdim:outdim+3] - y_pred[:, :, :3]
inferred_vel_ending = y_pred[:, :, -outdim:-(outdim-3)] - y_pred[:, :, -(outdim*2):-(outdim*2-3)]
starting_points = torch.cat((starting_points, inferred_vel_starting), dim=-1)
ending_points = torch.cat((ending_points, inferred_vel_starting), dim=-1)
if not self.config['soft_attraction']:
# Full version (all points get attracted, a different 2nd-nn sequence is taken into account in case same sequence is 1st-nn)
chamfer = 100*chamfer_distance(starting_points, ending_points, padded=False, avoid_in_sequence_collapsing=True)[0]
else:
# Soft version (only a few points are attracted, those whose 1-nn is not in-sequence)
chamfer = 100*chamfer_distance(starting_points,
ending_points,
padded=False,
avoid_in_sequence_collapsing=True,
soft_attraction=True,
point_reduction=None,
batch_reduction=None)[0]
return chamfer
def get_contrastive_v1(self, latent_segments, stroke_ids, **args):
"""Pairwise contrastive loss as in https://arxiv.org/abs/2003.13834,
with public code at: https://github.com/matheusgadelha/PointCloudLearningACD
In practice, we have a loss term for all pair of latent_segments (i,j),
where each pair is encouraged to be further if i and j don't belong to
the same stroke, and viceversa.
"""
with threadpool_limits(user_api="openmp", limits=self.max_workers):
n_pts = latent_segments.size(1)
feat = latent_segments.permute(0, 2, 1)
target = stroke_ids
feat = F.normalize(feat, p=2, dim=1)
pair_sim = torch.bmm(feat.transpose(1,2), feat) # (n_pts, n_pts): for each point, dot product with all other points
one_hot_target = F.one_hot(target).float() # (n_pts, num_strokes): for each point, one-hot encoding of stroke it belongs to
pair_target = torch.bmm(one_hot_target, one_hot_target.transpose(1,2)) # (n_pts, n_pts): for each point, 1 for points that belong to the same stroke, 0 otherwise
cosine_loss = pair_target * (1. - pair_sim) + (1. - pair_target) * F.relu(pair_sim - self.margin) # pair-wise contrastive loss (Eq. 4 in https://arxiv.org/abs/2003.13834): (n_pts, n_pts)
with torch.no_grad():
"""
Balance positive and negative pairs.
In practice: positive are often much fewer than negatives.
Therefore, we only consider a subset of negatives that is roughly
equal to the number of positive.
"""
if self.contrastive_balance_negatives:
pos_fraction = (pair_target.data == 1).float().mean() # fraction of positives
sample_neg = torch.zeros(pair_target.shape, dtype=torch.float32, device='cuda').uniform_() > 1 - pos_fraction # roughly as many points as positives
else:
sample_neg = torch.zeros(pair_target.shape, dtype=torch.float32, device='cuda').uniform_() > 0
sample_mask = (pair_target.data == 1) | sample_neg # sample all positives, and a subset of the negatives
diag_mask = 1 - torch.eye(n_pts) # Discard diag elems, i.e. do not compute loss on pairs (i,j) for i=j. It's always zero but it affects the .mean()
cosine_loss = diag_mask.unsqueeze(0).cuda() * sample_mask.type(torch.cuda.FloatTensor) * cosine_loss
total_loss = cosine_loss.mean()
return total_loss
def get_attraction_chamfer(self, y_pred, **args):
"""Chamfer loss between ending points (1st point-cloud) and starting points (2nd point-cloud).
It encourages predicted mini-sequences to be contiguous.
y_pred: (B, n_strokes, outdim*stroke_points) torch tensor
"""
starting_points = y_pred[:, :, :3]
ending_points = y_pred[:, :, -3:]
chamfer = 100*chamfer_distance(starting_points, ending_points, padded=False)[0]
return chamfer
def get_chamfer(self, y_pred, y, **args):
"""Compute chamfer distance
y: (B, n_strokes, outdim*stroke_points) torch tensor
y_pred: (B, n_strokes, outdim*stroke_points) torch tensor
"""
if 'vel' in self.config['extra_data']: # Fallback to custom chamfer distance for velocities
chamfer = 100*chamfer_distance(y_pred, y, velocities=True)[0]
# elif self.config['lambda_points'] > 1 or self.config['stroke_pred'] == True:
is_gt_padded = True if self.config['stroke_pred'] == False else False # No padding if stroke_pred (TEMPORARY)
chamfer = 100*chamfer_distance(y_pred, y, padded=is_gt_padded, min_centroids=self.config['min_centroids'])[0] # Handle padded GT trajs for dataloader
return chamfer
def _transform_segment_distance_to_confidence(self, distance):
"""Transformation: a given distance among segments is mapped to
a value in [0, 1] as described in https://www.desmos.com/calculator/esc9rs7jl2
such that higher distance leads to lower confidence values.
"""
# Coeffs
c = 2.17
d = -4.63
return -1 * ( 1 / ( 1 + torch.exp(-c*torch.log10(distance) + d) ) ) + 1
def _get_per_segment_confidence_loss(self, nn_distance, logits):
"""Learn a confidence score for each predicted segment,
proportionally to how close it is to the nearest GT segment.
In practice, the target is set using such transformation
(https://www.desmos.com/calculator/esc9rs7jl2) and it's
followed with an L2 loss.
This is inspired by the confidence learned in YOLO, which aims
at learning the IoU with the GT with an L2 loss.
Params:
nn_distance: [B, out_segments]
distance with nearest GT segment, for each predicted segment
logits: [B, out_segments]
network pred confidence logits in [0, 1] for each predicted segment
Returns:
L2 loss scalar
"""
# Get targets for the given distances
targets = self._transform_segment_distance_to_confidence(nn_distance)
# L2 loss
per_segment_confidence_loss = (logits - targets).square().sum(-1).mean()
loss = self.config['explicit_weight_segments_confidence']*per_segment_confidence_loss
return loss
def get_asymm_v6_chamfer_with_stroke_masks(self, y_pred, y, pred_stroke_masks, mask_scores, seg_logits, stroke_ids, traj_as_pc, **kwargs):
"""Computes:
- asymm_chamfer_v6.yaml distance among segments
- (optional) loss on confidence for each segment (proportional to closest GT segment)
- loss on stroke masks
"""
# 1. asymm_segment_chamfer
preds_to_gt_segments_chamfer_noReduction, _, pred_to_gt_match, _ = chamfer_distance(y_pred,
y,
padded=True,
asymmetric=True,
return_matching=True,
point_reduction=None,
batch_reduction=None)
preds_to_gt_segments_chamfer = 100*(preds_to_gt_segments_chamfer_noReduction.mean())
# 1.1 per-segment confidence loss, proportional to distance
if self.config.per_segment_confidence:
per_segment_confidence_loss = self._get_per_segment_confidence_loss(nn_distance=preds_to_gt_segments_chamfer_noReduction,
logits=seg_logits)
else:
per_segment_confidence_loss = 0
# 2. reverse_asymm_point_chamfer
B = y_pred.shape[0]
outdim = get_dim_traj_points(self.config['extra_data'])
if not traj_as_pc.is_cuda:
traj_as_pc = traj_as_pc.to('cuda', dtype=torch.float)
point_wise_y_pred = y_pred.reshape(B, -1, outdim) # From pred segments to point-cloud
gt_to_preds_points_chamfer = 100*chamfer_distance(point_wise_y_pred,
traj_as_pc,
padded=True,
reverse_asymmetric=True)[0] # reverse asymmetric instead of reverting the first two arguments, because padding only exists in the second argument
traj_as_pc = traj_as_pc.cpu()
# 3. reverse_asymm_segment_chamfer
gt_to_preds_segment_chamfer = 100*chamfer_distance(y_pred,
y,
padded=True,
reverse_asymmetric=True)[0] # reverse asymmetric instead of reverting the first two arguments, because padding only exists in the second argument
# 4. stroke masks loss
stroke_masks_loss = self.get_stroke_masks_loss(pred_to_gt_match,
pred_stroke_masks,
mask_scores,
stroke_ids,
nn_distance=preds_to_gt_segments_chamfer_noReduction,
smooth_targets=self.config.smooth_target_stroke_masks,
**kwargs)
loss = self.config['weight_asymm_segment_chamfer']*preds_to_gt_segments_chamfer + \
per_segment_confidence_loss + \
self.config['weight_reverse_asymm_point_chamfer']*gt_to_preds_points_chamfer + \
self.config['weight_reverse_asymm_segment_chamfer']*gt_to_preds_segment_chamfer + \
stroke_masks_loss
return loss
def get_asymm_v11_chamfer_with_stroke_masks(self, y_pred, y, pred_stroke_masks, mask_scores, seg_logits, stroke_ids, traj_as_pc, **kwargs):
"""Computes:
- asymm_chamfer_v11.yaml chamfer distance + loss on stroke masks
- forward pred-to-gt: segment-wise
- reverse gt-to-pred: point-wise
"""
# 1. asymm_segment_chamfer
preds_to_gt_segments_chamfer_noReduction, _, pred_to_gt_match, _ = chamfer_distance(y_pred,
y,
padded=True,
asymmetric=True,
return_matching=True,
point_reduction=None,
batch_reduction=None)
preds_to_gt_segments_chamfer = 100*(preds_to_gt_segments_chamfer_noReduction.mean())
# 1.1 per-segment confidence loss, proportional to distance
if self.config.per_segment_confidence:
per_segment_confidence_loss = self._get_per_segment_confidence_loss(nn_distance=preds_to_gt_segments_chamfer_noReduction,
logits=seg_logits)
else:
per_segment_confidence_loss = 0
# 2. reverse_asymm_point_chamfer
B = y_pred.shape[0]
outdim = get_dim_traj_points(self.config['extra_data'])
if not traj_as_pc.is_cuda:
traj_as_pc = traj_as_pc.to('cuda', dtype=torch.float)
point_wise_y_pred = y_pred.reshape(B, -1, outdim) # From pred segments to point-cloud
gt_to_preds_points_chamfer = 100*chamfer_distance(point_wise_y_pred,
traj_as_pc,
padded=True,
reverse_asymmetric=True)[0] # reverse asymmetric instead of reverting the first two arguments, because padding only exists in the second argument
traj_as_pc = traj_as_pc.cpu()
# 3. stroke masks loss
stroke_masks_loss = self.get_stroke_masks_loss(pred_to_gt_match,
pred_stroke_masks,
mask_scores,
stroke_ids,
nn_distance=preds_to_gt_segments_chamfer_noReduction,
smooth_targets=self.config.smooth_target_stroke_masks,
**kwargs)
loss = self.config['weight_asymm_segment_chamfer']*preds_to_gt_segments_chamfer + \
per_segment_confidence_loss + \
self.config['weight_reverse_asymm_point_chamfer']*gt_to_preds_points_chamfer + \
stroke_masks_loss
return loss
def get_symm_v1_chamfer_with_stroke_masks(self, y_pred, y, pred_stroke_masks, mask_scores, seg_logits, stroke_ids, traj_as_pc, **kwargs):
"""Computes:
- symm_v1.yaml chamfer distance + loss on stroke masks
- you start point-wise, and progressively give more importance to segment-wise
"""
if self.config.smooth_target_stroke_masks:
raise NotImplementedError()
if self.config.per_segment_confidence:
raise NotImplementedError()
# 1. symm_segment_chamfer
symm_segment_wise, _, pred_to_gt_match, _ = chamfer_distance(y_pred, y, padded=True, return_matching=True) # pred_to_gt_match: [B, num_pred_segments]
symm_segment_wise *= 100
# 2. symm_point_chamfer
B = y_pred.shape[0]
outdim = get_dim_traj_points(self.config['extra_data'])
if not traj_as_pc.is_cuda:
traj_as_pc = traj_as_pc.to('cuda', dtype=torch.float)
point_wise_y_pred = y_pred.reshape(B, -1, outdim) # From pred segments to point-cloud
symm_point_wise = 100*chamfer_distance(point_wise_y_pred,
traj_as_pc,
padded=True)[0]
traj_as_pc = traj_as_pc.cpu()
# 3. stroke masks loss
stroke_masks_loss = self.get_stroke_masks_loss(pred_to_gt_match,
pred_stroke_masks,
mask_scores,
stroke_ids,
**kwargs)
loss = self.config['weight_symm_segment_chamfer']*symm_segment_wise + \
self.config['weight_symm_point_chamfer']*symm_point_wise + \
stroke_masks_loss
return loss
def get_chamfer_with_stroke_masks(self, y_pred, y, pred_stroke_masks, mask_scores, stroke_ids, **kwargs):
"""Computes (1) chamfer distance among segments + (2) loss on stroke masks (target stroke id matched
using closest GT segment to pred i-th segment)
"""
if self.config.smooth_target_stroke_masks:
raise NotImplementedError()
if self.config.per_segment_confidence:
raise NotImplementedError()
# Chamfer loss for segments prediction
chamfer, _, pred_to_gt_match, _ = chamfer_distance(y_pred, y, padded=True, return_matching=True) # pred_to_gt_match: [B, num_pred_segments]
chamfer *= 100
stroke_masks_loss = self.get_stroke_masks_loss(pred_to_gt_match,
pred_stroke_masks,
mask_scores,
stroke_ids,
**kwargs)
loss = chamfer + stroke_masks_loss
return loss
def _compute_stroke_mask_loss(self, input, target, kind='bce'):
"""Compute loss on given stroke masks.
No batch reduction is performed.
"""
if kind == 'bce':
return F.binary_cross_entropy_with_logits(input, target, reduction="none").sum(-1)
elif kind == 'mse':
return (input - target).square().sum(-1)
else:
raise NotImplementedError()
def get_stroke_masks_loss(self, pred_to_gt_match, pred_stroke_masks, scores, stroke_ids, nn_distance=None, smooth_targets=False, **kwargs):
"""Loss on predicted stroke masks (target stroke id matched
using closest GT segment to pred i-th segment)
Params:
nn_distance: [B, out_segments]
distance with nearest GT segment, for each predicted segment
smooth_targets: bool
if set, the target_stroke_ids are transformed into continuous-valued
stroke masks instead of binary stroke masks, where the positive target values
of 1 are replaced with f(distance), i.e. a value in [0, 1] inv. proportional to the distance
with the closest GT segment. This way, we implicitly learn a confidence on the segment,
and do not learn very confident stroke masks for segments that are badly placed.
"""
stroke_mask_loss_kind = 'bce' if smooth_targets is False else 'mse'
"""
Construct target_stroke_masks for predicted segments
stroke id of pred i-th segment = stroke id of GT segment that's closest to pred i-th segment
"""
# Assign stroke_ids to pred segments according to closest GT segment
target_stroke_ids = stroke_ids.cuda().gather(dim=1, index=pred_to_gt_match) # target_stroke_ids [B, out_segments]
# Split for readability
if smooth_targets:
# Create real-valued stroke masks from stroke_ids
target_stroke_masks = [self._from_stroke_ids_to_masks(batch_target_stroke_ids, nn_distance=batch_nn_distance, smooth_targets=smooth_targets)
for batch_target_stroke_ids, batch_nn_distance in zip(target_stroke_ids, nn_distance)] # list of size B [n_strokes[b], out_segments]
else:
# Create binary stroke masks from stroke ids,
target_stroke_masks = [self._from_stroke_ids_to_masks(batch_target_stroke_ids)
for batch_target_stroke_ids in target_stroke_ids] # list of size B [n_strokes[b], out_segments]
# Temp sanity checks
assert not torch.any(target_stroke_ids == -1), 'temp sanity check: no pred segment should be associated with the fake stroke id -1'
if not smooth_targets:
assert torch.all(torch.stack([torch.all(b_target_stroke_mask.sum(0) == 1) for b_target_stroke_mask in target_stroke_masks])), 'temp sanity check: masks should be mutually exclusive across strokes, hence all equal to ones when summed.'
"""
Find hungarian matching between pred_stroke_masks and target_stroke_masks
"""
B, n_pred_masks, out_segments = pred_stroke_masks.shape
indices = []
with torch.no_grad():
for b, (b_pred_stroke_masks, b_target_stroke_masks) in enumerate(zip(pred_stroke_masks, target_stroke_masks)): # iterate over batch elements
# Compute cost matrix for this batch
n_target_masks = b_target_stroke_masks.shape[0]
# all pairs in single-column format for loss computation ([n_pred_masks, n_target_masks] as [n_pred_masks*n_target_masks, 1])
exp_b_pred_stroke_masks = b_pred_stroke_masks.repeat_interleave(n_target_masks, dim=0)
exp_b_target_stroke_masks = b_target_stroke_masks.repeat(n_pred_masks, 1)
# bce = F.binary_cross_entropy_with_logits(exp_b_pred_stroke_masks, exp_b_target_stroke_masks.float(), reduction="none").sum(-1)
bce = self._compute_stroke_mask_loss(exp_b_pred_stroke_masks, exp_b_target_stroke_masks.float(), kind=stroke_mask_loss_kind)
bce = bce.view(n_pred_masks, n_target_masks).cpu() # cost matrix [n_pred_masks, n_target_masks]
indices.append(linear_sum_assignment(bce)) # solve LAP
indices = [(torch.as_tensor(i, dtype=torch.int64), torch.as_tensor(j, dtype=torch.int64)) for i, j in indices] # list of size B, with elements (index_i, index_j). index_* is Tensor
"""
Compute stroke masks loss given optimal matching
"""
pred_idx = self._get_pred_permutation_idx(indices) # tuple for indexing pred masks
gt_idx = self._get_gt_permutation_idx(indices) # tuple for indexing target masks
matched_pred_masks = pred_stroke_masks[pred_idx] # (stacked) sub-selected pred masks given optimal matching ([tot num of gt masks in batch, out_segments])
# Pad target masks with fake masks for easy indexing (fake stroke masks aren't used in the LAP, so they won't be matched to any pred mask anyways)
if smooth_targets:
padded_target_stroke_masks = torch.stack([self._concat_fake_vectors(
self._from_stroke_ids_to_masks(batch_target_stroke_ids, nn_distance=batch_nn_distance, smooth_targets=smooth_targets),
tot_desired=n_pred_masks
)
for batch_target_stroke_ids, batch_nn_distance in zip(target_stroke_ids, nn_distance)]) # Tensor [B, n_pred_masks, out_segments]
else:
padded_target_stroke_masks = torch.stack([self._concat_fake_vectors(
self._from_stroke_ids_to_masks(batch_target_stroke_ids),
tot_desired=n_pred_masks
)
for batch_target_stroke_ids in target_stroke_ids]) # Tensor [B, n_pred_masks, out_segments]
matched_target_masks = padded_target_stroke_masks[gt_idx] # (stacked) selected gt masks given optimal matching ([tot num of gt masks in batch, out_segments])
assert not torch.any(matched_target_masks == -100), 'temp sanity check: no fake stroke masks should be selected given the matching'
# stroke_mask_loss = F.binary_cross_entropy_with_logits(matched_pred_masks, matched_target_masks.float(), reduction="none").sum(-1).mean()
stroke_mask_loss = self._compute_stroke_mask_loss(matched_pred_masks, matched_target_masks.float(), kind=stroke_mask_loss_kind).mean()
# F.loss -> [tot num of gt masks in batch, out_segments]
# .sum(-1) -> [tot num of gt masks in batch,]
# .mean() -> []
"""
Compute confidence loss (`strokeness`)
scores: Tensor of dim [B, max_n_strokes]
Confidence scores for each pred mask
"""
# targets for scores (1.0 for masks matched with Hungarian to GT masks, 0 otherwise)
target_scores = torch.zeros(scores.shape)
target_scores[pred_idx] = 1.
# weights for BCE
weights = self.config['explicit_no_stroke_weight']*torch.ones(scores.shape) # less weight to predictions of "no stroke", as often times there are many more predicted masks than needed
weights[pred_idx] = 1.
target_scores = target_scores.to(scores.get_device())
weights = weights.to(scores.get_device())
confidence_loss = F.binary_cross_entropy_with_logits(scores, target_scores, reduction="none", weight=weights).mean() # mean over all predicted masks
loss = self.config['explicit_weight_stroke_masks']*stroke_mask_loss + self.config['explicit_weight_stroke_masks_confidence']*confidence_loss
return loss
def _from_stroke_ids_to_masks(self, stroke_ids, smooth_targets=False, nn_distance=None):
"""Returns n_strokes binary masks given the stroke_ids tensor
Params:
stroke_ids: Tensor of dim [N] with K unique values (stroke ids)
smooth_targets: if set, real-valued masks in output instead of binary masks
nn_distance: Tensor of dim [N] with distance to nearest GT segment
N: num of segments
Returns:
Tensor of dim [K, N] with binary stroke masks
"""
assert stroke_ids.ndim == 1, 'a batch dimension is not expected'
stroke_masks = []
for stroke_id in torch.unique(stroke_ids):
if stroke_id == -1: # padding value for fake segments
continue
stroke_mask = (stroke_ids == stroke_id).int()
if smooth_targets:
segments_confidence = self._transform_segment_distance_to_confidence(nn_distance)
segments_in_stroke_mask = stroke_mask == 1
stroke_mask = stroke_mask.float() # from binary to real-valued
stroke_mask[segments_in_stroke_mask] = segments_confidence[segments_in_stroke_mask]
stroke_masks.append(stroke_mask)
return torch.stack(stroke_masks)
def _concat_fake_vectors(self, tens, tot_desired):
"""Concat a number of fake tensors to first dim of given tensor `tens`,
so that total number of vectors is tot_desired
fake tensors have a symbolic value of -100
"""
pad_value = -100
shape = tens.shape
n_fakes = tot_desired - tens.shape[0]
if n_fakes > 0:
fake_shape = list(tens.shape)
fake_shape[0] = n_fakes
return torch.cat((tens, pad_value*torch.ones(fake_shape).to(tens.device)), dim=0)
else:
return tens
def get_emd(self, y_pred, y, **kwargs):
"""Computes Earth Mover's distance (hungarian match + MSE loss between matched segments)
Params:
y_pred: predicted segments
y: padded GT segments
"""
# Remove fake GT segments
y_unpadded_list = [self.remove_padding_from_tensors(gt_segments) for gt_segments in y]
indices = self.matcher(outputs=y_pred, targets=y_unpadded_list) # list of size B, with elements (index_i, index_j). index_* is tensor