-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprimitive_diffusion.py
1682 lines (1468 loc) · 89.7 KB
/
primitive_diffusion.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 numpy as np
import os
import os.path as osp
import torch
from torch import nn
import torch.nn.functional as F
import time
import bson
from typing import Tuple, Optional
from loguru import logger
from learning.components.mlp import MLP_V2
import pytorch_lightning as pl
from learning.net.resunet import SparseResUNet
from learning.net.pointnet import MiniPointNetfeat
from learning.net.transformer import Transformer
from common.datamodels import PredictionMessage, ActionTypeDef, GeneralObjectState, GarmentSmoothingStyle, ObjectState, ActionIteratorMessage
import MinkowskiEngine as ME
from diffusers.schedulers.scheduling_ddim import DDIMScheduler
from diffusers.schedulers.scheduling_ddpm import DDPMScheduler
from learning.net.attentionnet import AttentionNet
from sklearn.metrics import roc_auc_score
import py_cli_interaction
class CustomScheduler:
"""
add useful tools for DDIMScheduler
"""
def get_noise(
self,
original_samples: torch.FloatTensor,
noisy_samples: torch.FloatTensor,
timesteps: torch.IntTensor,
) -> torch.FloatTensor:
# Make sure alphas_cumprod and timestep have same device and dtype as original_samples
alphas_cumprod = self.alphas_cumprod.to(device=original_samples.device, dtype=original_samples.dtype)
timesteps = timesteps.to(original_samples.device)
sqrt_alpha_prod = alphas_cumprod[timesteps] ** 0.5
sqrt_alpha_prod = sqrt_alpha_prod.flatten()
while len(sqrt_alpha_prod.shape) < len(original_samples.shape):
sqrt_alpha_prod = sqrt_alpha_prod.unsqueeze(-1)
sqrt_one_minus_alpha_prod = (1 - alphas_cumprod[timesteps]) ** 0.5
sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.flatten()
while len(sqrt_one_minus_alpha_prod.shape) < len(original_samples.shape):
sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.unsqueeze(-1)
noise = (noisy_samples - sqrt_alpha_prod * original_samples) / sqrt_one_minus_alpha_prod
return noise
def get_minsnr_weights(
self,
timesteps: torch.IntTensor,
) -> torch.FloatTensor:
alphas_cumprod = self.alphas_cumprod.to(device=timesteps.device)
SNR = alphas_cumprod / (1 - alphas_cumprod)
FIVE = torch.ones_like(SNR) * 5.0
ONE = torch.ones_like(SNR)
if self.config.prediction_type == "sample":
weights = torch.minimum(SNR, FIVE)
elif self.config.prediction_type == "epsilon":
weights = torch.minimum(FIVE / SNR, ONE)
else:
raise NotImplementedError
weights = weights[timesteps]
weights = weights.flatten()
return weights
class CustomDDIMScheduler(DDIMScheduler, CustomScheduler):
pass
class CustomDDPMScheduler(DDPMScheduler, CustomScheduler):
pass
class DiffusionHead(pl.LightningModule):
def __init__(
self,
weight_decay: float,
# diffusion params
scheduler_type: str = 'ddim',
ddim_eta: float = 0.0,
num_training_steps: int = 100,
beta_start: float = 0.0001,
beta_end: float = 0.02,
beta_schedule: str = 'squaredcos_cap_v2',
clip_sample: bool = True,
set_alpha_to_one: bool = True,
steps_offset: int = 0,
prediction_type: str = 'sample',
num_inference_steps: Optional[int] = 10,
num_of_grasp_points: int = 8,
num_gripper_points: int = 2,
# data params
data_format: str = 'nocs',
adaptive_xyz: bool = False,
match_idx: Optional[Tuple] = None,
# model params
feature_dim: int = 240,
num_diffusion_net_layers: int = 2,
num_diffusion_net_heads: int = 4,
action_input_mlp_nn_channels: Tuple[int, int] = (120, 240),
action_output_mlp_nn_channels: Tuple[int, int] = (240, 120),
use_positional_encoding_in_attention_net: bool = False,
**kwargs,
):
super().__init__()
self.save_hyperparameters()
self.weight_decay = weight_decay
self.data_format = data_format
self.feature_dim = feature_dim
self.num_of_grasp_points = num_of_grasp_points
self.num_gripper_points = num_gripper_points
self.kwargs = kwargs
if data_format == 'nocs' or data_format == 'xyz':
self.data_dim = 3
self.adaptive_xyz = False
elif data_format == 'xyznocs':
self.data_dim = 6
self.adaptive_xyz = adaptive_xyz
else:
raise NotImplementedError
self.match_idx = match_idx
assert action_input_mlp_nn_channels[-1] == feature_dim and action_output_mlp_nn_channels[0] == feature_dim, \
"The channel of action MLP should match the feature dim"
self.model = AttentionNet(
data_dim=self.data_dim,
feature_dim=feature_dim,
num_layers=num_diffusion_net_layers,
num_heads=num_diffusion_net_heads,
num_gripper_points=num_gripper_points,
use_positional_encoding=use_positional_encoding_in_attention_net,
action_input_mlp_nn_channels=action_input_mlp_nn_channels,
action_output_mlp_nn_channels=action_output_mlp_nn_channels,
)
assert scheduler_type in ['ddim', 'ddpm'], "Only support DDIM and DDPM scheduler now"
if prediction_type == 'epsilon':
assert data_format == 'xyz', "Only support xyz data format for epsilon prediction type"
logger.warning("Only support xyz data format for epsilon prediction type")
logger.warning("The variety error has no meaning for epsilon prediction type")
if scheduler_type == 'ddim':
self.noise_scheduler = CustomDDIMScheduler(
num_train_timesteps=num_training_steps,
beta_start=beta_start,
beta_end=beta_end,
beta_schedule=beta_schedule,
clip_sample=clip_sample,
set_alpha_to_one=set_alpha_to_one,
steps_offset=steps_offset,
prediction_type=prediction_type,
)
elif scheduler_type == 'ddpm':
self.noise_scheduler = CustomDDPMScheduler(
num_train_timesteps=num_training_steps,
beta_start=beta_start,
beta_end=beta_end,
beta_schedule=beta_schedule,
clip_sample=clip_sample,
prediction_type=prediction_type,
)
self.scheduler_type = scheduler_type
self.ddim_eta = ddim_eta
if num_inference_steps is None:
num_inference_steps = num_training_steps
self.num_inference_steps = num_inference_steps
self.num_training_steps = num_training_steps
def _get_action_xyz_nocs(self,
action: torch.Tensor,
pc_xyz: torch.Tensor,
pred_pc_nocs: torch.Tensor) -> Tuple[torch.tensor, torch.tensor]:
if self.data_format == 'nocs' or self.adaptive_xyz:
pred_pc_nocs_expanded = pred_pc_nocs.unsqueeze(1).expand(-1, self.num_of_grasp_points, -1, -1)
action_expanded = action.unsqueeze(2).expand(-1, -1, pred_pc_nocs.shape[1], -1)
if self.data_format == 'nocs':
action_nocs = action
action_nocs_expanded = action_expanded
elif self.data_format == 'xyznocs':
action_nocs = action[..., 3:]
action_nocs_expanded = action_expanded[..., 3:]
distance = torch.norm(pred_pc_nocs_expanded - action_nocs_expanded, dim=-1)
index = torch.argmin(distance, dim=2)
action_xyz = pc_xyz.gather(1, index.unsqueeze(-1).expand(-1, -1, 3))
else:
action_xyz = action[..., :3]
if self.data_format == 'xyz':
pc_xyz_expanded = pc_xyz.unsqueeze(1).expand(-1, self.num_of_grasp_points, -1, -1)
action_xyz_expanded = action_xyz.unsqueeze(2).expand(-1, -1, pc_xyz.shape[1], -1)
distance = torch.norm(pc_xyz_expanded - action_xyz_expanded, dim=-1)
index = torch.argmin(distance, dim=2)
action_nocs = pred_pc_nocs.gather(1, index.unsqueeze(-1).expand(-1, -1, 3))
elif self.data_format == 'xyznocs':
action_nocs = action[..., 3:]
return action_xyz, action_nocs
def _get_data(self, data_xyz: torch.Tensor, data_nocs: torch.Tensor) -> torch.tensor:
if self.data_format == 'nocs':
data = data_nocs
elif self.data_format == 'xyz':
data = data_xyz
elif self.data_format == 'xyznocs':
data = torch.cat([data_xyz, data_nocs], dim=-1)
else:
raise NotImplementedError
return data
def _get_matched_action_gt(self,
action_noisy: torch.Tensor,
multiple_action_xyz_gt: torch.Tensor,
multiple_action_nocs_gt: torch.Tensor,
timesteps: torch.Tensor) -> torch.tensor:
B, N, _, D1 = multiple_action_xyz_gt.shape
multiple_action_xyz_gt = multiple_action_xyz_gt.reshape(B*N, self.num_gripper_points, D1)
_, _, _, D2 = multiple_action_nocs_gt.shape
multiple_action_nocs_gt = multiple_action_nocs_gt.reshape(B*N, self.num_gripper_points, D2)
multiple_action_gt = self._get_data(multiple_action_xyz_gt, multiple_action_nocs_gt)
M = self.num_of_grasp_points // self.num_gripper_points
action_noisy = action_noisy.reshape(B, M, self.num_gripper_points, -1)
multiple_action_gt = multiple_action_gt.reshape(B, N, self.num_gripper_points, -1)
B, N, _, D = multiple_action_gt.shape
sym_multiple_action_gt = multiple_action_gt.clone()
sym_multiple_action_gt[:, :, 0, :] = multiple_action_gt[:, :, 1, :]
sym_multiple_action_gt[:, :, 1, :] = multiple_action_gt[:, :, 0, :]
action_noisy_expanded = action_noisy.unsqueeze(2).expand(-1, -1, N, -1, -1)
multiple_action_gt_expanded = multiple_action_gt.unsqueeze(1).expand(-1, M, -1, -1, -1)
sym_multiple_action_gt_expanded = sym_multiple_action_gt.unsqueeze(1).expand(-1, M, -1, -1, -1)
# choose the best match according to the distance from the noisy action
metric = torch.nn.MSELoss(reduction='none')
# only consider the match range
if self.match_idx is None:
self.match_idx = np.arange(D)
else:
match_idx = torch.tensor(self.match_idx).to(torch.long)
distance = torch.minimum(
metric(action_noisy_expanded[..., match_idx], multiple_action_gt_expanded[..., match_idx]).mean(dim=(3, 4)),
metric(action_noisy_expanded[..., match_idx], sym_multiple_action_gt_expanded[..., match_idx]).mean(dim=(3, 4)))
index = torch.argmin(distance, dim=2)
if self.noise_scheduler.config.prediction_type == 'sample':
action_gt = multiple_action_gt_expanded.gather(2, index.unsqueeze(-1).unsqueeze(-1).unsqueeze(-1).expand(-1, -1, -1, 2, D))
else:
noise_expanded = self.noise_scheduler.get_noise(multiple_action_gt_expanded, action_noisy_expanded, timesteps)
action_gt = noise_expanded.gather(2, index.unsqueeze(-1).unsqueeze(-1).unsqueeze(-1).expand(-1, -1, -1, 2, D))
action_gt = action_gt.reshape(B, M*2, D)
return action_gt
def get_minsnr_weights(self, timesteps: torch.IntTensor) -> torch.FloatTensor:
return self.noise_scheduler.get_minsnr_weights(timesteps)
def forward(self,
action: torch.Tensor,
timestep: torch.Tensor,
context: torch.Tensor,
context_pos: torch.Tensor) -> torch.tensor:
return self.model(action, timestep, context, context_pos)
def diffuse_denoise(self,
action_xyz_gt: torch.Tensor,
action_nocs_gt: torch.Tensor,
context: torch.Tensor,
pc_xyz: torch.Tensor,
pc_nocs: torch.Tensor,
use_matched_action_gt: bool = True,
multiple_action_xyz_gt: torch.Tensor = None,
multiple_action_nocs_gt: torch.Tensor = None,
timesteps: torch.Tensor = None,
noise: torch.Tensor = None,
replicate_action: bool = True) -> Tuple[torch.Tensor, torch.Tensor]:
action_gt = self._get_data(action_xyz_gt, action_nocs_gt)
context_pos = self._get_data(pc_xyz, pc_nocs)
B, D = action_gt.shape[0], action_gt.shape[-1]
device = action_gt.device
noise_scheduler = self.noise_scheduler
if replicate_action:
action_gt = action_gt.unsqueeze(1).expand(-1, self.num_of_grasp_points // self.num_gripper_points, -1, -1).reshape(B, -1, D)
if noise is None:
noise = torch.randn_like(action_gt)
if timesteps is None:
timesteps = torch.randint(
0,
noise_scheduler.config.num_train_timesteps,
(B,),
device=device
).long()
action_noisy = self.noise_scheduler.add_noise(action_gt, noise, timesteps)
action_pred = self.forward(action_noisy, timesteps, context, context_pos)
action_xyz_pred, action_nocs_pred = self._get_action_xyz_nocs(action_pred, pc_xyz, pc_nocs)
if use_matched_action_gt and multiple_action_xyz_gt is not None and multiple_action_nocs_gt is not None:
action_gt = self._get_matched_action_gt(action_noisy, multiple_action_xyz_gt, multiple_action_nocs_gt, timesteps)
else:
if self.noise_scheduler.config.prediction_type == 'epsilon':
action_gt = noise
return action_gt, action_pred, action_xyz_pred, action_nocs_pred, timesteps, noise
def conditional_sample(self,
context: torch.Tensor,
pc_xyz: torch.Tensor,
pred_pc_nocs: torch.Tensor,
generator=None,
**kwargs) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
scheduler = self.noise_scheduler
action = torch.randn(
context.shape[0], self.num_of_grasp_points, self.data_dim
).to(context.device)
action_xyz_list = []
action_xyz, action_nocs = self._get_action_xyz_nocs(action, pc_xyz, pred_pc_nocs)
if self.adaptive_xyz:
action[..., :3] = action_xyz
action_xyz_list.append(action_xyz)
context_pos = self._get_data(pc_xyz, pred_pc_nocs)
scheduler.set_timesteps(self.num_inference_steps)
for t in scheduler.timesteps:
model_output = self.forward(action, t, context, context_pos)
if self.scheduler_type == 'ddim':
action = scheduler.step(
model_output, t, action, eta=self.ddim_eta, generator=generator, **kwargs
).prev_sample
else:
action = scheduler.step(
model_output, t, action, generator=generator, **kwargs
).prev_sample
action_xyz, action_nocs = self._get_action_xyz_nocs(action, pc_xyz, pred_pc_nocs)
if self.adaptive_xyz:
action[..., :3] = action_xyz
action_xyz_list.append(action_xyz)
return action_xyz, action_nocs, action_xyz_list
class StateHead(pl.LightningModule):
"""concat nocs feature, global feature, dense feature as nocs feature input"""
def __init__(self,
global_nn_channels: tuple = (128, 256, 1024),
cls_base_nn_channels: tuple = (1024, 256, 128),
pointnet_channels: tuple = (3, 64, 128, 512),
grasp_nocs_feat_nn_channels: tuple = (512 + 64 + 1024 + 128, 512, 256),
nocs_nn_channels: tuple = (128, 256, 128, 3),
offset_nn_channels: tuple = (128, 256, 128, 1), # only predict (x, y) coordinate
att_nn_channels: tuple = (128, 256, 128, 1),
num_smoothing_style: int = 4, # short: (down, up, left, right)
num_keypoints: int = 4, # (left shoulder, right shoulder, left waist, right waist)
min_gt_nocs_ratio: float = 0.2,
gt_nocs_ratio_decay_factor: float = 0.98, # for 100 epoch setting
num_pred_candidates: int = 4, # number of possible candidates
use_xyz_variety_loss: bool = False,
use_gt_nocs_pred_for_distance_weight: bool = False,
nocs_distance_weight_alpha: float = 30.0,
use_nocs_for_dense_feat: bool = True,
detach_for_classifier: bool = False,
detach_for_detector: bool = False,
**kwargs):
super().__init__()
self.save_hyperparameters()
self.num_action_type = num_smoothing_style
self.num_pred_candidates = num_pred_candidates
self.num_keypoints = num_keypoints
self.nocs_pointnet = MiniPointNetfeat(nn_channels=pointnet_channels)
self.grasp_nocs_feat_mlp = MLP_V2(grasp_nocs_feat_nn_channels, transpose_input=True)
self.offset_mlp_list = nn.ModuleList([
MLP_V2(offset_nn_channels, transpose_input=True) for _ in range(num_keypoints)
])
self.att_mlp_list = nn.ModuleList([
MLP_V2(att_nn_channels, transpose_input=True) for _ in range(num_keypoints)
])
self.global_mlp = MLP_V2(global_nn_channels, transpose_input=True)
self.nocs_mlp = MLP_V2(nocs_nn_channels, transpose_input=True)
self.smoothed_cls_mlp = MLP_V2(cls_base_nn_channels + (1,), transpose_input=True)
self.smoothing_style_mlp = MLP_V2(cls_base_nn_channels + (num_smoothing_style,), transpose_input=True)
self.gt_nocs_ratio = 1.0
self.min_gt_nocs_ratio = min_gt_nocs_ratio
self.gt_nocs_ratio_decay_factor = gt_nocs_ratio_decay_factor
self.use_xyz_variety_loss = use_xyz_variety_loss
self.use_gt_nocs_pred_for_distance_weight = use_gt_nocs_pred_for_distance_weight
self.nocs_distance_weight_alpha = nocs_distance_weight_alpha
self.use_nocs_for_dense_feat = use_nocs_for_dense_feat
self.detach_for_classifier = detach_for_classifier
self.detach_for_detector = detach_for_detector
def forward(self, pc_xyz: torch.Tensor, dense_feat: torch.Tensor, gt_pc_nocs: torch.Tensor = None):
dense_feat_extra = self.global_mlp(dense_feat) # (B, N, C')
global_feat = torch.max(dense_feat_extra, dim=1)[0] # (B, C)
if self.detach_for_classifier:
smoothed_logits = self.smoothed_cls_mlp(global_feat.detach()) # stop gradient
smoothing_style_logits = self.smoothing_style_mlp(global_feat.detach()) # stop gradient
else:
smoothed_logits = self.smoothed_cls_mlp(global_feat)
smoothing_style_logits = self.smoothing_style_mlp(global_feat)
pred_nocs = self.nocs_mlp(dense_feat) # (B, N, 3)
if self.training and gt_pc_nocs is not None:
# use GT NOCS during training
self.gt_nocs_ratio = max(self.min_gt_nocs_ratio,
self.gt_nocs_ratio_decay_factor ** self.current_epoch)
use_gt_nocs = torch.rand(1).item() < self.gt_nocs_ratio
else:
use_gt_nocs = False
input_pc_nocs = gt_pc_nocs.transpose(1, 2) if use_gt_nocs else pred_nocs.detach().transpose(1, 2) # (B, 3, N)
dense_nocs_feat, _ = self.nocs_pointnet(input_pc_nocs) # (B, C", N)
num_pts = dense_feat_extra.shape[1]
global_feat_expand = global_feat.unsqueeze(-1).expand(-1, -1, num_pts) # (B, C, N)
if self.use_nocs_for_dense_feat:
dense_nocs_feat_cat = torch.cat([dense_nocs_feat, global_feat_expand], dim=1).transpose(1, 2) # (B, N, C+C")
else:
dense_nocs_feat_cat = global_feat_expand.transpose(1, 2)
dense_nocs_feat_cat = torch.cat([dense_nocs_feat_cat, dense_feat], dim=2) # (B, N, C+C'+C")
dense_nocs_feat_fuse = self.grasp_nocs_feat_mlp(dense_nocs_feat_cat) # (B, N, C''')\
keypoints = []
for idx in range(self.num_keypoints):
if self.detach_for_detector:
offset = self.offset_mlp_list[idx](dense_feat.detach()) # stop gradient
att = self.att_mlp_list[idx](dense_feat.detach()) # stop gradient
else:
offset = self.offset_mlp_list[idx](dense_feat)
att = self.att_mlp_list[idx](dense_feat)
att = torch.softmax(att, dim=1)
keypoint = ((pc_xyz + offset) * att).sum(dim=1) # (B, 3)
keypoints.append(keypoint)
keypoints = torch.stack(keypoints, dim=1) # (B, num_keypoints, 3)
return pred_nocs, use_gt_nocs, dense_nocs_feat_fuse, smoothed_logits, smoothing_style_logits, keypoints
class RewardPredictionHead(pl.LightningModule):
def __init__(self,
num_classes: int = 1,
num_layers: int = 2,
num_heads: int = 4,
feature_dim: int = 240,
action_input_mlp_nn_channels: Tuple[int, int] = (120, 240),
action_output_mlp_nn_channels: Tuple[int, int] = (240, 120),
use_positional_encoding_in_attention_net: bool = False,
**kwargs):
super().__init__()
self.save_hyperparameters()
self.feature_dim = feature_dim
self.model = AttentionNet(
data_dim=feature_dim, # only for output dim
feature_dim=feature_dim,
num_layers=num_layers,
num_heads=num_heads,
num_gripper_points=2,
use_positional_encoding=use_positional_encoding_in_attention_net,
action_input_mlp_nn_channels=action_input_mlp_nn_channels,
action_output_mlp_nn_channels=action_output_mlp_nn_channels,
enable_extra_outputting_dims=True
)
self.output_mlp = MLP_V2((feature_dim * 2, num_classes), transpose_input=True)
def forward(self, action: torch.Tensor, context: torch.Tensor, context_pos: torch.Tensor) -> torch.tensor:
B = action.size(0)
# hack: fixed timestep
timestep = torch.zeros(B, device=action.device)
pred = self.model(action, timestep, context, context_pos)
_, gp_dim, _ = pred.shape
gp_dim //= 4
pred1, pred2 = torch.chunk(pred, 2, dim=1)
pred1 = pred1.reshape((-1, gp_dim, self.feature_dim * 2))
pred2 = pred2.reshape((-1, gp_dim, self.feature_dim * 2))
output1, output2 = self.output_mlp(pred1), self.output_mlp(pred2)
return torch.cat([output1, output2], dim=2)
def get_grasp_pair_scores(self, rankings: torch.Tensor):
B, N = rankings.shape
scores = torch.zeros(B, N, 2, device=rankings.device)
weights = torch.zeros(B, N, 2, device=rankings.device)
win_mask = (rankings == 0)
scores[win_mask] = torch.tensor([1, 0], device=rankings.device, dtype=torch.float)
weights[win_mask] = torch.tensor([1, 1], device=rankings.device, dtype=torch.float)
lose_mask = (rankings == 1)
scores[lose_mask] = torch.tensor([0, 1], device=rankings.device, dtype=torch.float)
weights[lose_mask] = torch.tensor([1, 1], device=rankings.device, dtype=torch.float)
return scores, weights
class PrimitiveDiffusion(pl.LightningModule):
"""
Use Res-UNet3D as backbone, use Point cloud as input
use Transformer to encode dense per-point feature
use attention + offset to predict grasp points and release points
predict K grasp-points for each action
factorized reward prediction
"""
def __init__(self,
# sparse uned3d encoder params
sparse_unet3d_encoder_params,
# transformer params
transformer_params,
# action head params
state_head_params,
# diffusion head params
diffusion_head_params,
# reward head params
reward_prediction_head_params = None,
# hyper-params
rescale_nocs: bool = False,
use_multiple_poses: bool = False,
use_minsnr_reweight: bool = False,
use_matched_action_gt: bool = True,
# compatible with more tasks
valid_primitive_idx: int = ActionTypeDef.FLING.value,
valid_smoothed_values: tuple = (GeneralObjectState.to_int(GeneralObjectState.DISORDERED), GeneralObjectState.to_int(GeneralObjectState.ORGANIZED)),
valid_smoothing_style_values: tuple = (GarmentSmoothingStyle.to_int(GarmentSmoothingStyle.DOWN),
GarmentSmoothingStyle.to_int(GarmentSmoothingStyle.UP),
GarmentSmoothingStyle.to_int(GarmentSmoothingStyle.LEFT),
GarmentSmoothingStyle.to_int(GarmentSmoothingStyle.RIGHT)), # should be consecutive
gripper_points_idx: tuple = (0, 2), # (0, 1), (0, 1, 2, 3)
num_gripper_points: int = 2,
use_sym_loss: bool = True,
# loss weights
loss_cls_weight: float = 0.1,
loss_keypoint_weight: float = 1.0,
loss_nocs_weight: float = 100.0,
loss_diffusion_weight: float = 1.0,
loss_diffusion_finetune_weight: float = 1.0,
loss_diffusion_finetune_sft_equal_weight: float = 1.0,
loss_diffusion_finetune_sft_weight: float = 1.0,
loss_reward_prediction_weight: float = 1.0,
finetune_loss_type: str = 'dpo',
dpo_beta: float = 1000,
cpl_lambda: float = 1.0,
use_sft_for_equal_samples: bool = False,
use_sft_for_gt_data: bool = False,
# optimizer params
use_cos_lr: bool = False,
cos_t_max: int = 100,
init_lr: float = 1e-4,
# others
use_virtual_reward_for_inference: bool = True,
random_select_diffusion_action_pair_for_inference: bool = False,
manually_select_diffusion_action_pair_for_inference: bool = False,
use_dpo_reward_for_inference: bool = False,
use_reward_prediction_for_inference: bool = False,
dpo_reward_sample_num: int = 10,
reference_model_path: str = None,
enable_new_pipeline_finetune: bool = False,
enable_new_pipeline_supervised_classification_detection: bool = False,
enable_new_pipeline_reward_prediction: bool = False,
original_classification_model_path: str = None,
**kwargs):
super().__init__()
self.save_hyperparameters()
self.rescale_nocs = rescale_nocs
self.use_multiple_poses = use_multiple_poses
self.use_minsnr_reweight = use_minsnr_reweight
self.use_matched_action_gt = use_matched_action_gt
# compatible with more tasks
self.valid_primitive_idx = valid_primitive_idx
self.valid_smoothed_values = valid_smoothed_values
self.valid_smoothing_style_values = valid_smoothing_style_values
self.gripper_points_idx = gripper_points_idx
self.num_gripper_points = num_gripper_points
self.use_sym_loss = use_sym_loss
# loss weights
self.loss_cls_weight = loss_cls_weight
self.loss_keypoint_weight = loss_keypoint_weight
self.loss_nocs_weight = loss_nocs_weight
self.loss_diffusion_weight = loss_diffusion_weight
self.loss_reward_prediction_weight = loss_reward_prediction_weight
self.loss_diffusion_finetune_weight = loss_diffusion_finetune_weight
self.loss_diffusion_finetune_sft_euqal_weight = loss_diffusion_finetune_sft_equal_weight
self.loss_diffusion_finetune_sft_weight = loss_diffusion_finetune_sft_weight
if finetune_loss_type is not None:
assert finetune_loss_type in ['dpo', 'cpl'], "Only support DPO and CPL loss"
else:
assert use_sft_for_gt_data or enable_new_pipeline_reward_prediction, \
"Finetune loss type should be provided when not using SFT for GT data and not enable bew pipeline reward prediction"
self.finetune_loss_type = finetune_loss_type
self.dpo_beta = dpo_beta
self.cpl_lambda = cpl_lambda
if use_sft_for_equal_samples:
assert finetune_loss_type in ['dpo', 'cpl'], "Only support DPO and CPL loss when using SFT for equal samples"
self.use_sft_for_equal_samples = use_sft_for_equal_samples
self.use_sft_for_gt_data = use_sft_for_gt_data
# optimizer params
self.use_cos_lr = use_cos_lr
self.cos_t_max = cos_t_max
self.init_lr = init_lr
# others
self.use_virtual_reward_for_inference = use_virtual_reward_for_inference
if use_dpo_reward_for_inference:
assert not use_virtual_reward_for_inference, "DPO reward inference is not compatible with virtual reward inference"
assert not use_reward_prediction_for_inference, "DPO reward inference is not compatible with reward prediction inference"
assert not random_select_diffusion_action_pair_for_inference, "DPO reward inference is not compatible with randomly select action pair"
self.use_dpo_reward_for_inference = use_dpo_reward_for_inference
self.dpo_reward_sample_num = dpo_reward_sample_num
if use_reward_prediction_for_inference:
assert not use_virtual_reward_for_inference, "reward prediction inference is not compatible with virtual reward inference"
assert not use_dpo_reward_for_inference, "reward prediction inference is not compatible with DPO reward inference"
assert not random_select_diffusion_action_pair_for_inference, "reward prediction inference is not compatible with randomly select action pair"
self.use_reward_prediction_for_inference = use_reward_prediction_for_inference
if random_select_diffusion_action_pair_for_inference:
assert not use_virtual_reward_for_inference, "randomly select action pair is not compatible with virtual reward inference"
assert not use_dpo_reward_for_inference, "randomly select action pair is not compatible with DPO reward inference"
assert not use_reward_prediction_for_inference, "randomly select action pair is not compatible with reward prediction inference"
self.random_select_diffusion_action_pair_for_inference = random_select_diffusion_action_pair_for_inference
if manually_select_diffusion_action_pair_for_inference:
if not random_select_diffusion_action_pair_for_inference:
logger.warning("manually select action pair is not enabled when randomly select action pair is disabled")
manually_select_diffusion_action_pair_for_inference = False
self.manually_select_diffusion_action_pair_for_inference = manually_select_diffusion_action_pair_for_inference
self.backbone = SparseResUNet(**sparse_unet3d_encoder_params)
self.transformer = Transformer(**transformer_params)
self.state_head = StateHead(**state_head_params)
self.diffusion_head = DiffusionHead(**diffusion_head_params)
self.sigmoid = nn.Sigmoid()
if enable_new_pipeline_finetune:
assert reference_model_path is not None, "reference model path should be provided for new pipeline finetuning"
self.enable_new_pipeline_finetune = enable_new_pipeline_finetune
if enable_new_pipeline_supervised_classification_detection:
assert not enable_new_pipeline_finetune, "new pipeline supervised smoothing style is not compatible with new pipeline finetuning"
if original_classification_model_path is not None and osp.exists(original_classification_model_path):
checkpoint_dir = osp.join(original_classification_model_path, 'checkpoints')
checkpoint_path = osp.join(checkpoint_dir, 'last.ckpt')
classification_original_model = PrimitiveDiffusion.load_from_checkpoint(checkpoint_path, strict=False)
self.load_state_dict(classification_original_model.state_dict(), strict=False)
else:
logger.warning("original classification model path is not provided or not exists, train from scratch for new pipeline supervised classification detection")
self.enable_new_pipeline_supervised_classification_detection = enable_new_pipeline_supervised_classification_detection
if enable_new_pipeline_reward_prediction:
assert enable_new_pipeline_finetune, "new pipeline reward prediction is only compatible with new pipeline finetuning"
self.reward_head = RewardPredictionHead(**reward_prediction_head_params)
self.enable_new_pipeline_reward_prediction = enable_new_pipeline_reward_prediction
# reference model for new pipeline finetuning
if reference_model_path is not None:
checkpoint_dir = osp.join(reference_model_path, 'checkpoints')
checkpoint_path = osp.join(checkpoint_dir, 'last.ckpt')
reference_model = PrimitiveDiffusion.load_from_checkpoint(checkpoint_path, strict=True)
reference_model.eval()
reference_model.requires_grad_(False)
self.load_state_dict(reference_model.state_dict(), strict=True)
self.reference_model = reference_model
self.sync_reference_model_settings()
else:
self.reference_model = None
if use_dpo_reward_for_inference or use_reward_prediction_for_inference:
assert self.reference_model is not None, "reference model should be provided for DPO reward inference"
def sync_reference_model_settings(self):
self.reference_model.use_virtual_reward_for_inference = self.use_virtual_reward_for_inference
self.reference_model.random_select_diffusion_action_pair_for_inference = self.random_select_diffusion_action_pair_for_inference
self.reference_model.manually_select_diffusion_action_pair_for_inference = self.manually_select_diffusion_action_pair_for_inference
self.reference_model.use_dpo_reward_for_inference = self.use_dpo_reward_for_inference
self.reference_model.use_reward_prediction_for_inference = self.use_reward_prediction_for_inference
self.reference_model.dpo_reward_sample_num = self.dpo_reward_sample_num
self.reference_model.diffusion_head.num_of_grasp_points = self.diffusion_head.num_of_grasp_points
self.reference_model.state_head.num_pred_candidates = self.state_head.num_pred_candidates
self.reference_model.diffusion_head.scheduler_type = self.diffusion_head.scheduler_type
self.reference_model.diffusion_head.num_inference_steps = self.diffusion_head.num_inference_steps
self.reference_model.diffusion_head.ddim_eta = self.diffusion_head.ddim_eta
def configure_optimizers(self):
if self.enable_new_pipeline_supervised_classification_detection:
freeze_net = [self.diffusion_head]
for net in freeze_net:
for param in net.parameters():
param.requires_grad = False
all_parameters = [{"params": self.state_head.parameters()},
{"params": self.backbone.parameters()},
{"params": self.transformer.parameters()}]
else:
optim_groups = self.diffusion_head.model.get_optim_groups(weight_decay=self.diffusion_head.weight_decay)
all_parameters = optim_groups + [{"params": self.state_head.parameters()},
{"params": self.backbone.parameters()},
{"params": self.transformer.parameters()}]
if self.enable_new_pipeline_reward_prediction:
all_parameters += [{"params": self.reward_head.parameters()}]
optimizer = torch.optim.AdamW(all_parameters, lr=self.init_lr, betas=[0.9, 0.95])
if self.use_cos_lr:
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=self.cos_t_max)
else:
scheduler = torch.optim.lr_scheduler.ExponentialLR(optimizer, gamma=0.97)
return [optimizer], [scheduler]
def forward(self, coords: torch.Tensor, feat: torch.Tensor, pc_xyz: torch.Tensor, gt_pc_nocs: torch.Tensor = None):
input = ME.SparseTensor(feat, coordinates=coords)
dense_feat = self.backbone(input) # (B*N, C)
dense_feat_att = self.transformer(dense_feat, pc_xyz.view(-1, 3)) # (B, N, C)
# TODO: add rotation angle prediction
pred_nocs, use_gt_nocs, dense_nocs_feat_fuse, smoothed_logits, smoothing_style_logits, keypoints = \
self.state_head(pc_xyz, dense_feat_att, gt_pc_nocs=gt_pc_nocs)
return dense_feat_att, pred_nocs, use_gt_nocs, dense_nocs_feat_fuse, smoothed_logits, smoothing_style_logits, keypoints
@staticmethod
def bce_loss(prediction, target, weights=None):
if weights is None:
weights = 1.0
valid_count = max(weights[:, 0].sum().item(), 1.0)
return (weights * nn.BCEWithLogitsLoss(reduction='none')(prediction, target.float())).mean(dim=1).sum() / valid_count
@staticmethod
def sym_grasp_mse_variety_cls_err(pred_grasp_nocs, pred_pc_nocs,
pc_xyz, xyz_target, nocs_target, weights=None,
use_xyz_variety_loss=False, alpha=30.0):
"""
only used for validate the training process
:param pred_grasp_nocs: (B, K, 3)
:param pred_grasp_score: (B, K)
:param pred_pc_nocs: (B, N, 3)
:param pc_xyz: (B, N, 3)
:param xyz_target: (B, 2, 3)
:param nocs_target: (B, 2, 3)
:param weights:
:param use_xyz_variety_loss: bool, whether to calculate xyz variety loss
:param alpha: float, the weight for exponential function in nocs-distance weight calculation
:return:
"""
B = pred_grasp_nocs.shape[0]
K = pred_grasp_nocs.shape[1]
N = pc_xyz.shape[1]
device = pred_grasp_nocs.device
if weights is None:
weights = 1.0
valid_count = max(weights.sum().item(), 1.0)
# nocs variety loss
nocs_metric = torch.nn.MSELoss(reduction='none')
left_target_nocs = nocs_target[:, 0, :].unsqueeze(1).expand(-1, K, -1) # (B, K, 3)
right_target_nocs = nocs_target[:, 1, :].unsqueeze(1).expand(-1, K, -1) # (B, K, 3)
left_grasp_loss_nocs = nocs_metric(pred_grasp_nocs, left_target_nocs).mean(dim=-1) # (B, K)
right_grasp_loss_nocs = nocs_metric(pred_grasp_nocs, right_target_nocs).mean(dim=-1) # (B, K)
left_variety_loss_nocs, left_target_idxs_nocs = torch.min(left_grasp_loss_nocs, dim=1) # (B, )
right_variety_loss_nocs, right_target_idxs_nocs = torch.min(right_grasp_loss_nocs, dim=1) # (B, )
variety_loss_nocs = (left_variety_loss_nocs + right_variety_loss_nocs) / 2.0 # (B, )
loss_grasp_variety_nocs = (variety_loss_nocs * weights).sum() / valid_count
if use_xyz_variety_loss:
# xyz variety loss with nocs-distance as weights
xyz_metric = torch.nn.MSELoss(reduction='none')
left_target_xyz = xyz_target[:, 0, :].unsqueeze(1).expand(-1, K, -1) # (B, K, 3)
right_target_xyz = xyz_target[:, 1, :].unsqueeze(1).expand(-1, K, -1) # (B, K, 3)
pred_grasp_nocs_expand = pred_grasp_nocs.unsqueeze(2).expand(-1, -1, N, -1) # (B, K, N, 3)
# detach pred_grasp_nocs to avoid gradient flow back to pred_grasp_nocs
pred_pc_nocs_expand = pred_pc_nocs.detach().unsqueeze(1).expand(-1, K, -1, -1) # (B, K, N, 3)
nocs_distance = torch.norm(pred_grasp_nocs_expand - pred_pc_nocs_expand, dim=-1) # (B, K, N)
nocs_distance_weight = torch.exp(-alpha * nocs_distance) # (B, K, N)
normalized_nocs_distance_weight = nocs_distance_weight / nocs_distance_weight.sum(dim=-1, keepdim=True) + 1e-6 # (B, K, N)
pc_xyz_expand = pc_xyz.unsqueeze(1).expand(-1, K, -1, -1) # (B, K, N, 3)
pred_grasp_xyz = torch.sum(pc_xyz_expand * normalized_nocs_distance_weight.unsqueeze(-1), dim=2) # (B, K, 3)
left_grasp_loss_xyz = xyz_metric(pred_grasp_xyz, left_target_xyz).mean(dim=-1) # (B, K)
right_grasp_loss_xyz = xyz_metric(pred_grasp_xyz, right_target_xyz).mean(dim=-1) # (B, K)
batch_range = torch.arange(B, device=device) # (B, )
left_variety_loss_xyz = left_grasp_loss_xyz[batch_range, left_target_idxs_nocs] # (B, )
right_variety_loss_xyz = right_grasp_loss_xyz[batch_range, right_target_idxs_nocs] # (B, )
variety_loss_xyz = (left_variety_loss_xyz + right_variety_loss_xyz) / 2.0 # (B, )
loss_grasp_variety_xyz = (variety_loss_xyz * weights).sum() / valid_count
return loss_grasp_variety_nocs.detach(), loss_grasp_variety_xyz.detach()
else:
return loss_grasp_variety_nocs.detach(), torch.zeros_like(loss_grasp_variety_nocs)
@staticmethod
def sym_nocs_huber_loss(prediction: torch.Tensor, target: torch.Tensor, rescale_nocs: bool = False) -> torch.Tensor:
metric = torch.nn.HuberLoss(delta=0.1, reduction='none')
sym_target = target.clone()
# symmetric target: 180 deg rotation around z-axis in NOCS space
if rescale_nocs:
sym_target[:, :, 0] = - sym_target[:, :, 0]
sym_target[:, :, 1] = - sym_target[:, :, 1]
else:
sym_target[:, :, 0] = 1.0 - sym_target[:, :, 0]
sym_target[:, :, 1] = 1.0 - sym_target[:, :, 1]
loss = torch.minimum(metric(prediction, target).mean((1, 2)),
metric(prediction, sym_target).mean((1, 2))
).mean()
return loss
@staticmethod
def sym_diffusion_mse_loss(action_gt: torch.Tensor,
action_pred: torch.Tensor,
weights: torch.Tensor = None,
minsnr_weights: torch.Tensor = None,
use_sym_loss: bool = True) -> torch.Tensor:
metric = torch.nn.MSELoss(reduction='none')
B, K, D = action_gt.shape
action_gt = action_gt.reshape(B, K//2, 2, D)
action_pred = action_pred.reshape(B, K//2, 2, D)
if use_sym_loss:
sym_action_gt = action_gt.clone()
sym_action_gt[:, :, 0, :] = action_gt[:, :, 1, :]
sym_action_gt[:, :, 1, :] = action_gt[:, :, 0, :]
loss = torch.minimum(metric(action_pred, action_gt).mean((2, 3)),
metric(action_pred, sym_action_gt).mean((2, 3))
).mean(1)
else:
loss = metric(action_pred, action_gt).mean((1, 2, 3))
if weights is None:
weights = torch.tensor(1.0)
valid_count = max(weights.sum().item(), 1.0)
if minsnr_weights is None:
minsnr_weights = torch.tensor(1.0)
return (loss * weights).sum() / valid_count, (loss * weights * minsnr_weights).sum() / valid_count
@staticmethod
def epsilon_diffusion_mse_loss(noise_gt: torch.Tensor,
action_pred: torch.Tensor,
weights: torch.Tensor = None,
minsnr_weights: torch.Tensor = None) -> torch.Tensor:
metric = torch.nn.MSELoss(reduction='none')
B, K, D = noise_gt.shape
noise_gt = noise_gt.reshape(B, K//2, 2, D)
action_pred = action_pred.reshape(B, K//2, 2, D)
loss = metric(action_pred, noise_gt).mean((1, 2, 3))
if weights is None:
weights = torch.tensor(1.0)
valid_count = max(weights.sum().item(), 1.0)
if minsnr_weights is None:
minsnr_weights = torch.tensor(1.0)
return (loss * weights).sum() / valid_count, (loss * weights * minsnr_weights).sum() / valid_count
@staticmethod
def diffusion_dpo_loss(action_gt: torch.Tensor,
action_pred: torch.Tensor,
action_pred_reference: torch.Tensor,
rankings: torch.Tensor,
weights: torch.Tensor = None,
minsnr_weights: torch.Tensor = None,
beta: float = 1000) -> torch.Tensor:
metric = torch.nn.MSELoss(reduction='none')
sigmoid = torch.nn.Sigmoid()
win_mask = (rankings == 0) # win
win_weights = win_mask.float()
lose_mask = (rankings == 1) # lose
lose_weights = lose_mask.float() * -1
equal_mask = (rankings == 2) # equal
equal_weights = equal_mask.float()
action_gt_1, action_gt_2 = action_gt.chunk(2, dim=1)
action_pred_1, action_pred_2 = action_pred.chunk(2, dim=1)
action_pred_reference_1, action_pred_reference_2 = action_pred_reference.chunk(2, dim=1)
elbo1 = metric(action_pred_1, action_gt_1).mean((2, 3))
elbo2 = metric(action_pred_2, action_gt_2).mean((2, 3))
elbo1_reference = metric(action_pred_reference_1, action_gt_1).mean((2, 3))
elbo2_reference = metric(action_pred_reference_2, action_gt_2).mean((2, 3))
loss = (elbo1 - elbo1_reference) - (elbo2 - elbo2_reference)
loss = loss * win_weights + loss * lose_weights
if minsnr_weights is None:
minsnr_weights = torch.tensor(1.0)
else:
minsnr_weights = minsnr_weights.unsqueeze(1)
loss_constant_weighted = - sigmoid( - beta * loss)
loss_snr_weighted = - sigmoid( - beta * minsnr_weights * loss)
loss_sft_constant_weighted = equal_weights * (elbo1 + elbo2) / 2
loss_sft_snr_weighted = equal_weights * (elbo1 + elbo2) / 2
valid_mask = win_mask | lose_mask
valid_weight = valid_mask.float()
if weights is None:
valid_weight = valid_weight * weights.unsqueeze(1)
valid_count = max(valid_weight.sum().item(), 1.0)
valid_weight_equal = equal_weights.clone()
if weights is None:
valid_weight_equal = valid_weight_equal * weights.unsqueeze(1)
valid_count_equal = max(valid_weight_equal.sum().item(), 1.0)
return (loss_constant_weighted * valid_weight).sum() / valid_count, (loss_snr_weighted * valid_weight).sum() / valid_count, \
(loss_sft_constant_weighted * valid_weight_equal).sum() / valid_count_equal, (loss_sft_snr_weighted * valid_weight_equal).sum() / valid_count_equal
@staticmethod
def diffusion_cpl_loss(action_gt: torch.Tensor,
action_pred: torch.Tensor,
rankings: torch.Tensor,
weights: torch.Tensor = None,
minsnr_weights: torch.Tensor = None,
cpl_lambda: float = 1.0) -> torch.Tensor:
metric = torch.nn.MSELoss(reduction='none')
win_mask = (rankings == 0) # win
win_weights = win_mask.float()
lose_mask = (rankings == 1) # lose
lose_weights = lose_mask.float() * -1
equal_mask = (rankings == 2) # equal
equal_weights = equal_mask.float()
action_gt_1, action_gt_2 = action_gt.chunk(2, dim=1)
action_pred_1, action_pred_2 = action_pred.chunk(2, dim=1)
elbo1 = metric(action_pred_1, action_gt_1).mean((2, 3))
elbo2 = metric(action_pred_2, action_gt_2).mean((2, 3))
if minsnr_weights is None:
minsnr_weights = torch.tensor(1.0)
else:
minsnr_weights = minsnr_weights.unsqueeze(1)
elbo_perfer = elbo1 * win_weights - elbo2 * lose_weights
elbo_not_perfer = - elbo1 * lose_weights + elbo2 * win_weights
#TODO: support using cpl lambda for regularization
loss_constant_weighted = - torch.log(torch.exp(-elbo_perfer) / (torch.exp(-elbo_perfer) + torch.exp(- elbo_not_perfer)))
loss_snr_weighted = - torch.log(torch.exp(-minsnr_weights * elbo_perfer) / (torch.exp(-minsnr_weights * elbo_perfer) + torch.exp(-minsnr_weights * elbo_not_perfer)))
loss_sft_constant_weighted = equal_weights * (elbo1 + elbo2) / 2
loss_sft_snr_weighted = equal_weights * (elbo1 + elbo2) / 2
valid_mask = win_mask | lose_mask
valid_weight = valid_mask.float()
if weights is None:
valid_weight = valid_weight * weights.unsqueeze(1)
valid_count = max(valid_weight.sum().item(), 1.0)
valid_weight_equal = equal_weights.clone()
if weights is None:
valid_weight_equal = valid_weight_equal * weights.unsqueeze(1)
valid_count_equal = max(valid_weight_equal.sum().item(), 1.0)
return (loss_constant_weighted * valid_weight).sum() / valid_count, (loss_snr_weighted * valid_weight).sum() / valid_count, \
(loss_sft_constant_weighted * valid_weight_equal).sum() / valid_count_equal, (loss_sft_snr_weighted * valid_weight_equal).sum() / valid_count_equal
@staticmethod
def ranking_loss(pred: torch.Tensor, gt_score: torch.Tensor, weights = None) -> torch.Tensor:
"""
Input:
pred: (B, K, 2) Tensor
gt_score: (B, K, 2) Tensor
"""
# pred_all = torch.stack([pred1, pred2], dim=-1) # (B, K, 2)
if weights is None:
weights = torch.ones_like(gt_score)
pred = pred * weights
pred_all = pred
gt_score = gt_score * weights