-
Notifications
You must be signed in to change notification settings - Fork 0
/
adaptation_online_single.py
1835 lines (1522 loc) · 78.8 KB
/
adaptation_online_single.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
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
import MinkowskiEngine as ME
from sklearn.metrics import jaccard_score
from tqdm import tqdm
import csv
import pickle
import open3d as o3d
from knn_cuda import KNN
from sklearn.metrics import davies_bouldin_score
from utils.losses import CELoss, SoftCELoss, DICELoss, SoftDICELoss, HLoss, SCELoss
from utils.collation import CollateSeparated, CollateStream
from utils.sampler import SequentialSampler
from utils.dataset_online import PairedOnlineDataset, FrameOnlineDataset
from models import MinkUNet18_HEADS, MinkUNet18_SSL, MinkUNet18_MCMC
from knn_cuda import KNN
import csv
import random
import copy
from pytorch3d.ops import knn_points, knn_gather
import math
import time
MemoryBank_Data = []
MemoryBank_Label = []
Label_Bank = []
Coordinate_Bank = []
prototypes = torch.zeros(7, 96).cuda()
score_list = []
score_list_new = []
time_lists = []
# freeze BN
def freeze_bn(m):
classname = m.__class__.__name__
if classname.find('BatchNorm') != -1:
m.eval()
def get_cbst_th(preds, vals):
pc = torch.unique(preds)
c_th = torch.zeros(pc.max()+1)
for c in pc:
c_idx = preds == c
vals_c, _ = torch.sort(vals[c_idx], descending=False)
p = 0.8
c_th[c] = vals_c[torch.floor(torch.tensor((vals_c.shape[0]-1)*p)).long()]
return c_th
def get_cbst_th_2(preds, vals, p=0.5):
pc = torch.unique(preds)
c_th = torch.zeros(pc.max()+1)
for c in pc:
c_idx = preds == c
vals_c, _ = torch.sort(vals[c_idx], descending=False)
c_th[c] = vals_c[torch.floor(torch.tensor((vals_c.shape[0]-1)*p)).long()]
return c_th
class EMA(object):
def __init__(self, model, alpha):
self.step = 0
self.model = model
self.alpha = alpha
def update(self, model):
# decay = min(1 - 1 / (self.step + 1), self.alpha)
decay = self.alpha
for ema_param, param in zip(self.model.parameters(), model.parameters()):
ema_param.data = decay * ema_param.data + (1 - decay) * param.data
# if self.step > 1000:
# for ema_param, param in zip(self.model.parameters(), model.parameters()):
# ema_param.data = decay * ema_param.data + (1 - decay) * param.data
# else:
# pass
self.step += 1
def negative_index_sampler(samp_num, seg_num_list):
negative_index = []
for i in range(samp_num.shape[0]):
for j in range(samp_num.shape[1]):
negative_index += np.random.randint(low=sum(seg_num_list[: j]),
high=sum(seg_num_list[: j+1]),
size=int(samp_num[i, j])).tolist()
return negative_index
def label_onehot(inputs, num_class):
'''
inputs is class label
return one_hot label
dim will be increasee
'''
inputs = torch.relu(inputs)
outputs = torch.zeros([inputs.shape[0], num_class]).to(inputs.device)
return outputs.scatter_(1, inputs.unsqueeze(1), 1.0)
def BMD_prototype_update(prototypes, all_cls_out, all_emd_feat):
class_num = 7
topk_seg = 3
alpha = 0.99
topk_num = max(all_emd_feat.shape[0] // (class_num * topk_seg), 1)
_, all_psd_label = torch.max(all_cls_out, dim=1)
for cls_idx in range(class_num):
with torch.no_grad():
feat_samp_idx = torch.topk(all_cls_out[:, cls_idx], topk_num)[1]
feat_cls_sample = all_emd_feat[feat_samp_idx, :]
proto_rep_ = torch.mean(feat_cls_sample, dim=0, keepdim=True)
if (prototypes[cls_idx].sum() == torch.tensor(0.0)):
prototypes[cls_idx] = proto_rep_
else:
# Update gloal prototype
prototypes[cls_idx] = alpha * prototypes[cls_idx] + (1 - alpha) * proto_rep_
def prototype_update(rep, label, mask, prototypes):
num_segments = 7
topk_seg = 3
alpha = 0.99
valid_pixel_all_prt = label * mask.unsqueeze(-1).repeat(1, num_segments)
for i in range(num_segments): #7
valid_pixel_gather = valid_pixel_all_prt[:, i]
if valid_pixel_gather.sum() == 0:
continue
with torch.no_grad():
proto_rep_ = torch.mean((rep[valid_pixel_gather.bool()]), dim=0, keepdim=True)
if (prototypes[i].sum() == torch.tensor(0.0)):
prototypes[i] = proto_rep_
else:
# Update gloal prototype
prototypes[i] = alpha * prototypes[i] + (1 - alpha) * proto_rep_
class Contrast_Loss(nn.Module):
def __init__(self, num_queries=256, num_negatives=512, temp=0.5, mean=False, strong_threshold=0.9, alpha=0.99):
super(Contrast_Loss, self).__init__()
self.temp = temp
self.mean = mean
self.num_queries = num_queries
self.num_negatives = num_negatives
self.strong_threshold = strong_threshold
self.alpha = alpha
def forward(self, rep, label, mask, prob, prototypes):
# we gather all representations (mu and sigma) cross mutiple GPUs during this progress
with torch.no_grad():
rep_prt = rep # For protoype computing on all cards (w/o gradients)
size, num_feat = rep.shape
num_segments = label.shape[1] #7
valid_pixel_all = label * mask.unsqueeze(-1).repeat(1, num_segments)
with torch.no_grad():
valid_pixel_all_prt = (valid_pixel_all) # For protoype computing on all cards
rep_all_list = []
rep_hard_list = []
num_list = []
proto_rep_list = []
for i in range(num_segments): #7
valid_pixel = valid_pixel_all[:, i]
valid_pixel_gather = valid_pixel_all_prt[:, i]
if valid_pixel.sum() == 0:
continue
prob_seg = prob[:, i]
rep_mask_hard = (prob_seg < self.strong_threshold) * valid_pixel.bool() # Only on single card
with torch.no_grad():
proto_rep_ = torch.mean((rep_prt[valid_pixel_gather.bool()]), dim=0, keepdim=True)
if (prototypes[i].sum() == torch.tensor(0.0)):
proto_rep_list.append(proto_rep_)
prototypes[i] = proto_rep_
else:
# Update gloal prototype
prototypes[i] = self.alpha * prototypes[i] + (1 - self.alpha) * proto_rep_
proto_rep_list.append(prototypes[i].unsqueeze(0))
rep_all_list.append(rep[valid_pixel.bool()])
rep_hard_list.append(rep[rep_mask_hard])
num_list.append(int(valid_pixel.sum().item()))
# Compute Probabilistic Representation Contrastive Loss
if (len(num_list) <= 1) : # in some rare cases, a small mini-batch only contain 1 or no semantic class
return torch.tensor(0.0) + 0 * rep.sum() # A trick for avoiding data leakage in DDP training
else:
contrast_loss = torch.tensor(0.0)
proto_rep = torch.cat(proto_rep_list) # [c]
valid_num = len(num_list)
seg_len = torch.arange(valid_num)
for i in range(valid_num):
if len(rep_hard_list[i]) > 0:
# Random Sampling anchor representations
sample_idx = torch.randint(len(rep_hard_list[i]), size=(self.num_queries, ))
anchor_rep = rep_hard_list[i][sample_idx]
else:
continue
with torch.no_grad():
# Select negatives
id_mask = torch.cat(([seg_len[i: ], seg_len[: i]]))
proto_sim = torch.cosine_similarity(proto_rep[id_mask[0]].unsqueeze(0), proto_rep[id_mask[1:]], dim=1)
proto_prob = torch.softmax(proto_sim / self.temp, dim=0)
negative_dist = torch.distributions.categorical.Categorical(probs=proto_prob)
samp_class = negative_dist.sample(sample_shape=[self.num_queries, self.num_negatives])
samp_num = torch.stack([(samp_class == c).sum(1) for c in range(len(proto_prob))], dim=1)
negative_num_list = num_list[i+1: ] + num_list[: i]
negative_index = negative_index_sampler(samp_num, negative_num_list)
negative_rep_all = torch.cat(rep_all_list[i+1: ] + rep_all_list[: i])
negative_rep = negative_rep_all[negative_index].reshape(self.num_queries, self.num_negatives, num_feat)
positive_rep = proto_rep[i].unsqueeze(0).unsqueeze(0).repeat(self.num_queries, 1, 1)
all_rep = torch.cat((positive_rep, negative_rep), dim=1)
logits = torch.cosine_similarity(anchor_rep.unsqueeze(1), all_rep, dim=2)
contrast_loss = contrast_loss + F.cross_entropy(logits / self.temp, torch.zeros(self.num_queries).long().cuda())
return contrast_loss / valid_num
class OnlineTrainer(object):
def __init__(self,
model,
eval_dataset,
adapt_dataset,
source_model=None,
optimizer_name='SGD',
criterion='CELoss',
epsilon=0.,
ssl_criterion='Cosine',
ssl_beta=0.5,
seg_beta=1.0,
temperature=0.5,
lr=1e-3,
stream_batch_size=1,
adaptation_batch_size=2,
weight_decay=1e-5,
momentum=0.8,
val_batch_size=6,
train_num_workers=10,
val_num_workers=10,
num_classes=7,
clear_cache_int=2,
scheduler_name='ExponentialLR',
pseudor=None,
use_random_wdw=False,
freeze_list=None,
delayed_freeze_list=None,
num_mc_iterations=10,
use_global=False,
collate_fn_eval=None,
collate_fn_adapt=None,
device='cpu',
default_root_dir=None,
weights_save_path=None,
loggers=None,
save_checkpoint_every=2,
source_checkpoint=None,
student_checkpoint=None,
boost=True,
save_predictions=False,
is_double=True,
is_pseudo=True,
use_mcmc=True,
sub_epochs=0,
args=None):
super().__init__()
for name, value in list(vars().items()):
if name != "self":
setattr(self, name, value)
# loss
if criterion == 'CELoss':
self.criterion = CELoss(ignore_label=self.adapt_dataset.ignore_label,
weight=None)
elif criterion == 'WCELoss':
self.criterion = CELoss(ignore_label=self.adapt_dataset.ignore_label,
weight=self.adapt_dataset.weights)
elif criterion == 'SoftCELoss':
self.criterion = SoftCELoss(ignore_label=self.adapt_dataset.ignore_label)
elif criterion == 'DICELoss':
self.criterion = DICELoss(ignore_label=self.adapt_dataset.ignore_label)
elif criterion == 'SoftDICELoss':
self.criterion = SoftDICELoss(ignore_label=self.adapt_dataset.ignore_label,
neg_range=True, eps=self.args.loss_eps)
elif criterion == 'SCELoss':
self.criterion = SCELoss(alpha=1, beta=0.1, num_classes=self.num_classes, ignore_label=self.adapt_dataset.ignore_label)
else:
raise NotImplementedError
if self.ssl_criterion == 'CosineSimilarity':
self.ssl_criterion = nn.CosineSimilarity(dim=-1)
else:
raise NotImplementedError
self.ignore_label = self.eval_dataset.ignore_label
self.global_step = 0
self.max_time_wdw = self.eval_dataset.max_time_wdw
self.delayed_freeze_list = delayed_freeze_list
self.topk_matches = 0
self.dataset_name = self.adapt_dataset.name
self.configure_optimizers()
########################################
if device is not None:
self.device = torch.device(f'cuda:{device}')
else:
self.device = torch.device('cpu')
self.default_root_dir = default_root_dir
self.weights_save_path = weights_save_path
self.loggers = loggers
self.save_checkpoint_every = save_checkpoint_every
self.source_checkpoint = source_checkpoint
self.student_checkpoint = student_checkpoint
self.is_double = is_double
self.use_mcmc = use_mcmc
self.model = model
if self.is_double:
self.source_model = source_model
self.eval_dataset = eval_dataset
self.adapt_dataset = adapt_dataset
self.max_time_wdw = self.eval_dataset.max_time_wdw
self.eval_dataset.eval()
self.adapt_dataset.train()
self.online_sequences = np.arange(self.adapt_dataset.num_sequences())
self.num_frames = len(self.eval_dataset)
self.collate_fn_eval = collate_fn_eval
self.collate_fn_adapt = collate_fn_adapt
self.collate_fn_eval.device = self.device
self.collate_fn_adapt.device = self.device
self.sequence = -1
self.adaptation_results_dict = {s: [] for s in self.online_sequences}
self.source_results_dict = {s: [] for s in self.online_sequences}
# for speed up
self.eval_dataloader = None
self.adapt_dataloader = None
self.boost = boost
self.save_predictions = save_predictions
self.is_pseudo = is_pseudo
self.sub_epochs = sub_epochs
self.num_classes = num_classes
self.args = args
def freeze(self):
# here we freeze parts that have to be frozen forever
if self.freeze_list is not None:
for name, p in self.model.named_parameters():
for pf in self.freeze_list:
if pf in name:
p.requires_grad = False
def delayed_freeze(self, frame):
# here we freeze parts that have to be frozen only for a certain period
if self.delayed_freeze_list is not None:
for name, p in self.model.named_parameters():
for pf, frame_act in self.delayed_freeze_list.items():
if pf in name and frame <= frame_act:
p.requires_grad = False
def entropy_loss(self, p):
p = F.softmax(p, dim=1)
log_p = F.log_softmax(p, dim=1)
loss = -torch.sum(p * log_p, dim=1)
return loss
def configure_optimizers(self):
parameters = self.model.parameters()
if self.scheduler_name is None:
if self.optimizer_name == 'SGD':
optimizer = torch.optim.SGD(parameters,
lr=self.lr,
momentum=self.momentum,
weight_decay=self.weight_decay)
elif self.optimizer_name == 'Adam':
optimizer = torch.optim.Adam(parameters,
lr=self.lr,
weight_decay=self.weight_decay)
else:
raise NotImplementedError
self.optimizer = optimizer
self.scheduler = None
else:
if self.optimizer_name == 'SGD':
optimizer = torch.optim.SGD(parameters,
lr=self.lr,
momentum=self.momentum,
weight_decay=self.weight_decay)
elif self.optimizer_name == 'Adam' or self.optimizer_name == 'ADAM':
optimizer = torch.optim.Adam(parameters,
lr=self.lr,
weight_decay=self.weight_decay)
else:
raise NotImplementedError
if self.scheduler_name == 'CosineAnnealingLR':
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=10)
elif self.scheduler_name == 'ExponentialLR':
scheduler = torch.optim.lr_scheduler.ExponentialLR(optimizer, gamma=0.99)
elif self.scheduler_name == 'CyclicLR':
scheduler = torch.optim.lr_scheduler.CyclicLR(optimizer, base_lr=self.lr/10000, max_lr=self.lr,
step_size_up=5, mode="triangular2")
else:
raise NotImplementedError
self.optimizer = optimizer
self.scheduler = scheduler
def get_online_dataloader(self, dataset, is_adapt=False):
if is_adapt:
collate = CollateSeparated(torch.device('cpu'))
sampler = SequentialSampler(dataset, is_adapt=True, adapt_batchsize=self.adaptation_batch_size,
max_time_wdw=self.max_time_wdw)
dataloader = DataLoader(dataset,
collate_fn=collate,
sampler=sampler,
pin_memory=False,
num_workers=self.train_num_workers)
else:
# collate = CollateFN(torch.device('cpu'))
collate = CollateStream(torch.device('cpu'))
sampler = SequentialSampler(dataset, is_adapt=False, adapt_batchsize=self.stream_batch_size)
dataloader = DataLoader(dataset,
collate_fn=collate,
sampler=sampler,
pin_memory=False,
num_workers=self.train_num_workers)
return dataloader
def save_pcd(self, batch, preds, labels, save_path, frame, is_global=False):
pcd = o3d.geometry.PointCloud()
if not is_global:
pts = batch['coordinates']
pcd.points = o3d.utility.Vector3dVector(pts[:, 1:])
else:
pts = batch['global_points'][0]
pcd.points = o3d.utility.Vector3dVector(pts)
if self.num_classes == 7 or self.num_classes == 2:
pcd.colors = o3d.utility.Vector3dVector(self.eval_dataset.color_map[labels+1])
else:
pcd.colors = o3d.utility.Vector3dVector(self.eval_dataset.color_map[labels])
# os.makedirs(os.path.join(save_path, 'gt'), exist_ok=True)
# o3d.io.write_point_cloud(os.path.join(save_path, 'gt', str(frame)+'.ply'), pcd)
if self.num_classes == 7 or self.num_classes == 2:
pcd.colors = o3d.utility.Vector3dVector(self.eval_dataset.color_map[preds+1])
else:
pcd.colors = o3d.utility.Vector3dVector(self.eval_dataset.color_map[preds])
os.makedirs(os.path.join(save_path, 'preds'), exist_ok=True)
o3d.io.write_point_cloud(os.path.join(save_path, 'preds', str(frame)+'.ply'), pcd)
def save_pcd_wogt_1(self, batch, preds, labels, save_path, frame, is_global=False):
pcd = o3d.geometry.PointCloud()
if not is_global:
pts = batch['coordinates_all'][0]
pcd.points = o3d.utility.Vector3dVector(pts[:, :])
else:
pts = batch['global_pts'][0]
pcd.points = o3d.utility.Vector3dVector(pts)
if self.num_classes == 7 or self.num_classes == 2:
pcd.colors = o3d.utility.Vector3dVector(self.eval_dataset.color_map[preds+1])
else:
pcd.colors = o3d.utility.Vector3dVector(self.eval_dataset.color_map[preds])
os.makedirs(os.path.join(save_path, 'preds'), exist_ok=True)
o3d.io.write_point_cloud(os.path.join(save_path, 'preds', str(frame)+'.ply'), pcd)
def save_pcd_wogt_2(self, batch, preds, labels, save_path, frame, is_global=False):
pcd = o3d.geometry.PointCloud()
if not is_global:
pts = batch['coordinates0']
pcd.points = o3d.utility.Vector3dVector(pts[:, 1:])
else:
pts = batch['global_pts'][0]
pcd.points = o3d.utility.Vector3dVector(pts)
if self.num_classes == 7 or self.num_classes == 2:
pcd.colors = o3d.utility.Vector3dVector(self.eval_dataset.color_map[preds+1])
else:
pcd.colors = o3d.utility.Vector3dVector(self.eval_dataset.color_map[preds])
os.makedirs(os.path.join(save_path, 'preds'), exist_ok=True)
o3d.io.write_point_cloud(os.path.join(save_path, 'preds', str(frame)+'.ply'), pcd)
def adaptation_double_pseudo_step(self, batch, frame):
self.model.train()
self.freeze()
self.source_model.eval()
coords = batch["coordinates_all"][0]
batch_all = torch.zeros([coords.shape[0], 1])
coords_all = torch.cat([batch_all, coords], dim=-1)
feats_all = torch.ones([coords_all.shape[0], 1]).float()
# we assume that data the loader gives frames in pairs
stensor_all = ME.SparseTensor(coordinates=coords_all.int().to(self.device),
features=feats_all.to(self.device),
quantization_mode=ME.SparseTensorQuantizationMode.UNWEIGHTED_AVERAGE)
# pseudo label generation
with torch.no_grad():
global score_list
if self.args.use_ema:
self.ema.model.eval()
source_tmp, source_feats, source_bottle = self.ema.model(stensor_all, is_train=False)
else:
self.source_model.eval()
source_tmp, source_feats, source_bottle = self.source_model(stensor_all, is_train=False)
source_tmp = F.softmax(source_tmp, dim=-1).unsqueeze(0) # [1, N, C]
if self.args.use_pseudo_new:
# local geometric label aggregation
K = self.args.pseudo_knn
class_num = source_tmp.shape[-1]
global_pts = batch["global_pts0"].unsqueeze(0).float().cuda() # [1,N,3]
dists, idx, nn = knn_points(global_pts, global_pts, K=K, return_nn=True) # [1, N, K], [1, N, K], [1, N, K, 3]
knn_tmp = knn_gather(source_tmp, idx) #[1, N, K, 7]
if self.args.use_hard_label:
knn_predict = torch.argmax(knn_tmp.squeeze().reshape(-1, class_num), dim=-1) # [N*K]
knn_one_hot = F.one_hot(knn_predict, num_classes=class_num).float() # [N*K, 7]
knn_tmp = knn_one_hot.reshape(1, -1, K, class_num) # [1, N, K, 7]
knn_dist = torch.exp(-dists) # [1,N,K]
knn_dist = knn_dist / knn_dist.sum(dim=-1, keepdim=True)
knn_dist = knn_dist.unsqueeze(-1).repeat(1,1,1,class_num) # [1,N,K,7]
source_label = torch.sum(knn_tmp * knn_dist, dim=2) / K # [1,N,7]
# local purity
p = source_label
point_certainty = 1.0 - torch.sum(-p * torch.log(p + 1e-6), dim=-1) / math.log(class_num) #[1, N]
predict = torch.argmax(p.squeeze(), dim=-1) # [N]
one_hot = F.one_hot(predict, num_classes=class_num).float() # [N, 7]
knn_label = knn_gather(one_hot.unsqueeze(0), idx) #[1, N, K, 7]
knn_label = torch.mean(knn_label, dim=2)
region_purity = 1.0 - torch.sum( - knn_label * torch.log(knn_label + 1e-6), dim=-1) / math.log(class_num) # [1, N]
score = point_certainty * region_purity # [1, N]
if self.args.only_certainty:
score = point_certainty
if self.args.only_purity:
score = region_purity
else:
# local purity
p = source_tmp # [1, N, C]
class_num = source_tmp.shape[-1]
source_label = source_tmp
point_certainty = 1.0 - torch.sum(-p * torch.log(p + 1e-6), dim=-1) / math.log(class_num) #[1, N]
score = point_certainty
score_list.append(score.detach())
# compute pseudo labels
pseudo_logits_rep, pseudo_labels_rep = torch.max(source_label.squeeze(), dim=1)
pseudo = pseudo_labels_rep
pseudo_logits_rep = score.squeeze()
class_th = get_cbst_th_2(pseudo, pseudo_logits_rep, p=self.args.pseudo_th)
present_classes = torch.unique(pseudo)
new_pseudo = -torch.ones(pseudo.shape[0]).long().cuda()
main_idx = torch.arange(pseudo.shape[0])
valid_pseudo = []
for c in present_classes:
c_idx = main_idx[pseudo == c]
pseudo_logits_rep_c = pseudo_logits_rep[c_idx]
valid_unc = pseudo_logits_rep_c > class_th[c]
c_idx = c_idx[valid_unc]
new_pseudo[c_idx] = c
valid_pseudo.append(c_idx)
valid_pseudo = torch.cat(valid_pseudo)
pseudo0 = new_pseudo.detach()
pseudo_all = pseudo_labels_rep.clone().detach()
if self.args.save_predictions or self.args.save_gem_predictions:
save_path = os.path.join(self.weights_save_path, 'pcd')
phase = 'Gem_pseudo'
save_path_tmp = os.path.join(save_path, phase)
preds = pseudo0
labels = batch['labels0'].long().cuda()
self.save_pcd_wogt_1(batch, preds.cpu().numpy(),
labels.cpu().numpy(), save_path_tmp, frame,
is_global=False)
# knn-pseudo
if self.args.use_pre_label:
if len(Label_Bank) == 0:
Label_Bank.append(pseudo0.clone())
Coordinate_Bank.append(batch["global_pts0"].unsqueeze(0).float().cuda().clone()) #[1,N,3]
previous_label = pseudo0.clone()
else:
Label_Bank.append(pseudo0.clone())
Coordinate_Bank.append(batch["global_pts0"].unsqueeze(0).float().cuda().clone()) #[1,N,3]
if len(Label_Bank) > self.args.pre_label_num:
Label_Bank.pop(0)
Coordinate_Bank.pop(0)
previous_label_list = []
for i in range(len(Label_Bank)-1):
global_pts0 = Coordinate_Bank[-1].clone()
global_pts1 = Coordinate_Bank[i].clone()
K = self.args.pre_label_knn
dists, idx, _ = knn_points(global_pts0, global_pts1, K=K, return_nn=True) # [1, N, K], [1, N, K], [1, N, K, 3]
previous_label = knn_gather(Label_Bank[i].unsqueeze(0).unsqueeze(-1).clone(), idx) #[1, N, K, C]
previous_label = previous_label.squeeze(-1) #[N, K]
previous_label_list.append(previous_label)
previous_label_list = torch.cat(previous_label_list, dim=0) #[pre_label_num, N, K]
previous_label_list = previous_label_list.permute(1, 0, 2) #[N, pre_label_num, K]
N = previous_label_list.shape[0]
previous_label_list = previous_label_list.reshape(N, -1) #[N, pre_label_num*K]
# 取出现次数最多的label
# torch one-hot
previous_label_list = previous_label_list.reshape(-1)
previous_label_list = previous_label_list + 1
previous_label_list = label_onehot(previous_label_list, 8) #[N*pre_label_num*K, 8]
previous_label_list = previous_label_list.reshape(N, -1, 8) #[N, pre_label_num*K, 8]
previous_label_list = previous_label_list.sum(dim=1) #[N, 8]
previous_label_list = previous_label_list.argmax(dim=-1) #[N]
previous_label_list = previous_label_list - 1
previous_label = previous_label_list
mask = (pseudo0 == -1)
pseudo0[mask] = previous_label[mask]
if (pseudo0 != -1).sum() > 0:
# we assume that data the loader gives frames in pairs
stensor0 = ME.SparseTensor(coordinates=batch["coordinates0"].int().to(self.device),
features=batch["features0"].to(self.device),
quantization_mode=ME.SparseTensorQuantizationMode.UNWEIGHTED_AVERAGE)
stensor1 = ME.SparseTensor(coordinates=batch["coordinates1"].int().to(self.device),
features=batch["features1"].to(self.device),
quantization_mode=ME.SparseTensorQuantizationMode.UNWEIGHTED_AVERAGE)
# Must clear cache at regular interval
if self.global_step % self.clear_cache_int == 0:
torch.cuda.empty_cache()
self.optimizer.zero_grad()
# forward in mink
out_seg0, out_en0, out_pred0, out_bck0, _, out_seg1, out_en1, out_pred1, out_bck1, _ = self.model((stensor0, stensor1))
# segmentation loss for t0
labels0 = batch['labels0'].long()
# prototype generation
if self.args.use_prototype:
global prototypes
Contrast_loss = Contrast_Loss()
rep_all = out_bck0
pseudo0_2 = pseudo0.clone()
pseudo0_2[pseudo0_2 == -1] = 0
label_all = label_onehot(pseudo0_2, 7)
mask_all = pseudo0 != -1
pred_all = out_seg0
if self.args.BMD_prototype:
source_label = source_label * score.unsqueeze(-1).repeat(1,1,7) # [1, N, 7]
BMD_prototype_update(prototypes.cuda(), source_label.squeeze(), out_bck0)
elif self.args.use_prototype:
prototype_update(rep_all, label_all, mask_all, prototypes.cuda())
else:
contrast_loss = Contrast_loss(rep_all.cuda(), label_all.cuda(), mask_all.cuda(), pred_all.cuda(), prototypes.cuda())
norm_rep_u = F.normalize(out_bck0, dim=-1) # [N, C]
norm_proto = F.normalize(prototypes, dim=-1).permute(1, 0) # [C, C]
sim_mat = torch.mm(norm_rep_u, norm_proto) # [N, C] * [C, C] = [N, C]
temp = 0.25
# temp = 1.0
num_classes = 7
pseudo_logits_rep, pseudo_labels_rep = torch.max(F.softmax(sim_mat / temp, dim=1), dim=1)
label_mask = pseudo0.eq(pseudo_labels_rep)
label_mask = (~label_mask).float()
pseudo_labels = pseudo0 - label_mask * num_classes
pseudo_labels[pseudo_labels < 0] = -1
pseudo_labels = pseudo_labels
if self.args.use_all_pseudo:
label_mask = pseudo_all.eq(pseudo_labels_rep)
label_mask = (~label_mask).float()
pseudo_labels = pseudo_all - label_mask * num_classes
pseudo_labels[pseudo_labels < 0] = -1
pseudo_labels = pseudo_labels
# pseudo_labels = pseudo_labels.long()
# pseudo_labels[pseudo_labels == -1] = pseudo_labels_rep[pseudo_labels == -1]
# labels0 = batch['labels0'].long().cuda()
# valid_idx_pseudo = torch.logical_and(pseudo_labels != -1, labels0 != -1)
# # valid_idx_pseudo = labels0 != -1
# pseudo_acc = (pseudo_labels[valid_idx_pseudo] == labels0[valid_idx_pseudo]).sum() / labels0[valid_idx_pseudo].shape[0]
# print((pseudo_labels[valid_idx_pseudo] == labels0[valid_idx_pseudo]).sum())
# print(labels0[valid_idx_pseudo].shape[0])
# print(pseudo_acc)
if self.args.only_use_prototype:
pseudo = pseudo_labels_rep
class_th = get_cbst_th(pseudo, pseudo_logits_rep)
present_classes = torch.unique(pseudo)
new_pseudo = -torch.ones(pseudo.shape[0]).long().cuda()
main_idx = torch.arange(pseudo.shape[0])
valid_pseudo = []
for c in present_classes:
c_idx = main_idx[pseudo == c]
pseudo_logits_rep_c = pseudo_logits_rep[c_idx]
valid_unc = pseudo_logits_rep_c > class_th[c]
# valid_unc = pseudo_logits_rep_c < class_th[c]
c_idx = c_idx[valid_unc]
new_pseudo[c_idx] = c
valid_pseudo.append(c_idx)
pseudo_labels = -torch.ones(pseudo_labels_rep.shape[0]).long().cuda()
valid_pseudo = torch.cat(valid_pseudo)
pseudo_labels = new_pseudo.detach()
if self.args.only_use_BMD_prototype:
pseudo = pseudo_labels_rep
pseudo_labels = new_pseudo.detach()
if self.args.use_prototype:
pseudo0 = pseudo_labels.long()
if self.args.save_predictions:
save_path = os.path.join(self.weights_save_path, 'pcd')
phase = 'Sem_pseudo'
save_path_tmp = os.path.join(save_path, phase)
preds = pseudo0
labels = batch['labels0'].long().cuda()
self.save_pcd_wogt_2(batch, preds.cpu().numpy(),
labels.cpu().numpy(), save_path_tmp, frame,
is_global=False)
if self.args.loss_use_score_weight:
loss_seg_head = self.criterion(out_seg0, pseudo0, score=score, loss_method_num=self.args.loss_method_num)
else:
loss_seg_head = self.criterion(out_seg0, pseudo0)
pseudo0 = pseudo0
labels0 = labels0
# get matches in t0 and t1 (used for selection)
matches0 = batch['matches0'].to(self.device)
matches1 = batch['matches1'].to(self.device)
# 2FUTURE CONTRASTIVE
# forward preds (t0 -> t1)
future_preds = torch.index_select(out_pred0, 0, matches0)
# forward gt feats and stop grad
future_gt = torch.index_select(out_en1.detach(), 0, matches1)
future_neg_cos_sim = -self.ssl_criterion(future_preds, future_gt)
if self.args.sample_pos or self.args.coord_weight or self.args.score_weight:
if self.topk_matches > 0:
# select top-k worst performing matches
future_neg_cos_sim = future_neg_cos_sim.topk(self.topk_matches, dim=0).values.mean()
else:
if self.args.sample_pos:
future_seg = torch.index_select(out_seg1, 0, matches1)
future_seg = F.softmax(future_seg, dim=1)
future_seg, _ = torch.max(future_seg, dim=1)
future_neg_cos_sim = (future_neg_cos_sim * future_seg)
if self.args.coord_weight:
global_pts0 = batch["global_pts0"].unsqueeze(0).float().cuda()
global_pts1 = batch["global_pts1"].unsqueeze(0).float().cuda()
K = 1
dists, idx, _ = knn_points(global_pts1, global_pts0, K=K, return_nn=True) # [1, N, K], [1, N, K], [1, N, K, 3]
dists = dists.squeeze(0)
dists_weight = torch.index_select(dists, 0, matches1)
dists_weight = (dists_weight.sigmoid() - 0.5) * 2
dists_weight = (1 - dists_weight).squeeze()
future_neg_cos_sim = (future_neg_cos_sim * dists_weight)
if self.args.score_weight:
if frame >= 2 * self.max_time_wdw:
if self.args.score_weight_new:
score1 = out_seg1.detach().clone().softmax(dim=-1)
score1 = torch.max(score1, dim=-1)[0]
score_weight = torch.index_select(score1.cuda().squeeze(0).unsqueeze(-1), 0, matches1).squeeze()
else:
score_weight = score_list[-1-self.max_time_wdw].cuda()
score_weight = torch.index_select(score_weight.squeeze(0).unsqueeze(-1), 0, matches1).squeeze()
else:
score_weight = torch.ones(future_neg_cos_sim.shape[0]).cuda()
future_neg_cos_sim = (future_neg_cos_sim * score_weight)
future_neg_cos_sim = future_neg_cos_sim.mean(dim=0)
else:
if self.topk_matches > 0:
# select top-k worst performing matches
future_neg_cos_sim = future_neg_cos_sim.topk(self.topk_matches, dim=0).values.mean()
else:
future_neg_cos_sim = future_neg_cos_sim.mean(dim=0)
# 2PAST CONTRASTIVE
# backward preds (t1 -> t0)
past_preds = torch.index_select(out_pred1, 0, matches1)
# backward gt feats and stop grad
past_gt = torch.index_select(out_en0.detach(), 0, matches0)
past_neg_cos_sim = -self.ssl_criterion(past_preds, past_gt)
if self.args.sample_pos or self.args.coord_weight or self.args.score_weight:
if self.topk_matches > 0:
# select top-k worst performing matches
past_neg_cos_sim = past_neg_cos_sim.topk(self.topk_matches, dim=0).values.mean()
else:
if self.args.sample_pos:
past_seg = torch.index_select(out_seg0, 0, matches0)
past_seg = F.softmax(past_seg, dim=1)
past_seg, _ = torch.max(past_seg, dim=1)
past_neg_cos_sim = (past_neg_cos_sim * past_seg)
if self.args.coord_weight:
global_pts0 = batch["global_pts0"].unsqueeze(0).float().cuda()
global_pts1 = batch["global_pts1"].unsqueeze(0).float().cuda()
K = 1
dists, idx, _ = knn_points(global_pts0, global_pts1, K=K, return_nn=True) # [1, N, K], [1, N, K], [1, N, K, 3]
dists = dists.squeeze(0)
dists_weight = torch.index_select(dists, 0, matches0)
dists_weight = (dists_weight.sigmoid() - 0.5) * 2
dists_weight = (1 - dists_weight).squeeze()
past_neg_cos_sim = (past_neg_cos_sim * dists_weight)
if self.args.score_weight:
if frame >= 2 * self.max_time_wdw:
if self.args.score_weight_new:
score0 = out_seg0.detach().clone().softmax(dim=-1)
score0 = torch.max(score0, dim=-1)[0]
score_weight = torch.index_select(score0.cuda().squeeze(0).unsqueeze(-1), 0, matches0).squeeze()
else:
score_weight = score_list[-1].cuda()
score_weight = torch.index_select(score_weight.squeeze(0).unsqueeze(-1), 0, matches0).squeeze()
else:
score_weight = torch.ones(past_neg_cos_sim.shape[0]).cuda()
past_neg_cos_sim = (past_neg_cos_sim * score_weight)
past_neg_cos_sim = past_neg_cos_sim.mean(dim=0)
else:
if self.topk_matches > 0:
# select top-k worst performing matches
past_neg_cos_sim = past_neg_cos_sim.topk(self.topk_matches, dim=0).values.mean()
else:
past_neg_cos_sim = past_neg_cos_sim.mean(dim=0)
# sum up to total
ssl_loss = (future_neg_cos_sim + past_neg_cos_sim) * self.ssl_beta
total_loss = self.args.segmentation_beta * loss_seg_head + self.args.ssl_beta * ssl_loss
if self.args.without_ssl_loss:
total_loss = self.args.segmentation_beta * loss_seg_head
# backward and optimize
total_loss.backward()
self.optimizer.step()
if self.args.use_ema:
self.ema.update(self.model)
else:
# if no pseudo we skip the frame (happens never basically)
# we assume that data the loader gives frames in pairs
stensor0 = ME.SparseTensor(coordinates=batch["coordinates0"].int().to(self.device),
features=batch["features0"].to(self.device),
quantization_mode=ME.SparseTensorQuantizationMode.UNWEIGHTED_AVERAGE)
stensor1 = ME.SparseTensor(coordinates=batch["coordinates1"].int().to(self.device),
features=batch["features1"].to(self.device),
quantization_mode=ME.SparseTensorQuantizationMode.UNWEIGHTED_AVERAGE)
# Must clear cache at regular interval
if self.global_step % self.clear_cache_int == 0:
torch.cuda.empty_cache()
self.model.eval()
with torch.no_grad():
# forward in mink
out_seg0, out_en0, out_pred0, out_bck0, _, out_seg1, out_en1, out_pred1, out_bck1, _ = self.model((stensor0, stensor1))
# segmentation loss for t0
labels0 = batch['labels0'].long()
loss_seg_head = self.criterion(out_seg0, pseudo0)
pseudo0 = pseudo0
labels0 = labels0
# get matches in t0 and t1 (used for selection)
matches0 = batch['matches0'].to(self.device)
matches1 = batch['matches1'].to(self.device)
# 2FUTURE CONTRASTIVE
# forward preds (t0 -> t1)
future_preds = torch.index_select(out_pred0, 0, matches0)
# forward gt feats and stop grad
future_gt = torch.index_select(out_en1.detach(), 0, matches1)
future_neg_cos_sim = -self.ssl_criterion(future_preds, future_gt)
if self.topk_matches > 0:
# select top-k worst performing matches
future_neg_cos_sim = future_neg_cos_sim.topk(self.topk_matches, dim=0).values.mean()
else:
future_neg_cos_sim = future_neg_cos_sim.mean(dim=0)
# 2PAST CONTRASTIVE
# backward preds (t1 -> t0)
past_preds = torch.index_select(out_pred1, 0, matches1)
# backward gt feats and stop grad
past_gt = torch.index_select(out_en0.detach(), 0, matches0)
past_neg_cos_sim = -self.ssl_criterion(past_preds, past_gt)
if self.topk_matches > 0:
# select top-k worst performing matches
past_neg_cos_sim = past_neg_cos_sim.topk(self.topk_matches, dim=0).values.mean()
else:
past_neg_cos_sim = past_neg_cos_sim.mean(dim=0)
# sum up to total
ssl_loss = (future_neg_cos_sim + past_neg_cos_sim) * self.ssl_beta
# print((pseudo0 != -1).sum())
# print((pseudo0 != -1).sum())
# increase step
self.global_step += self.stream_batch_size
labels0 = batch['labels0'].long()
pseudo0 = pseudo0.cpu()
labels0 = labels0.cpu()
# additional metrics
_, pred_seg0 = out_seg0.detach().max(1)
# iou
iou_tmp = jaccard_score(pred_seg0.cpu().numpy(), labels0.cpu().numpy(), average=None,
labels=np.arange(0, self.num_classes),
zero_division=0.)
# forward preds (t0 -> t1)
future_preds = torch.index_select(out_bck0.detach(), 0, matches0)
# forward gt feats and stop grad