-
Notifications
You must be signed in to change notification settings - Fork 8
/
train.py
1372 lines (1142 loc) · 57.6 KB
/
train.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 collections
import math
import statistics
from functools import reduce
import torch
import torch.nn as nn
from apex import amp
from torch import distributed
from torch.nn import functional as F
import numpy as np
from PIL import Image
from torch.autograd import Variable
import torchvision
import matplotlib.pyplot as plt
from utils.utils import Label2Color, color_map #save prediction results
from utils import get_regularizer
from utils.loss import (NCA, BCESigmoid, BCEWithLogitsLossWithIgnoreIndex,
criterion_self_entropy,
BCEWithLogitsLossWithIgnoreIndexSoftLabel,
ExcludedKnowledgeDistillationLoss, FocalLoss,
FocalLossNew, IcarlLoss, KnowledgeDistillationLoss,
UnbiasedCrossEntropy,
UnbiasedKnowledgeDistillationLoss, UnbiasedNCA,
MyselfKnowledgeDistillationLoss,
soft_crossentropy)
class Trainer:
def __init__(self, model, model_old, device, rank, opts, trainer_state=None, classes=None, step=0):
self.model_old = model_old
self.model = model
self.device = device
self.rank = rank
self.step = step
self.mem_size = opts.mem_size
self.init_portion = opts.init_portion
self.max_portion = opts.max_portion
self.portion_step = opts.portion_step
self.classes = classes
self.soft_param = opts.soft_param
self.regular_param = opts.regular_param
self.batch_size = opts.batch_size
self.inital_nb_classes = opts.inital_nb_classes
self.method = opts.incremental_method
if classes is not None:
new_classes = classes[-1]
tot_classes = reduce(lambda a, b: a + b, classes)
self.old_classes = tot_classes - new_classes
self.nb_classes = opts.num_classes
self.nb_current_classes = tot_classes
self.nb_new_classes = new_classes
else:
self.old_classes = 0
self.nb_classes = None
# Select the Loss Type
reduction = 'none'
self.bce = opts.bce or opts.icarl
if self.bce:
self.criterion = BCEWithLogitsLossWithIgnoreIndex(reduction=reduction)
elif opts.unce and self.old_classes != 0:
self.criterion = UnbiasedCrossEntropy(
old_cl=self.old_classes, ignore_index=255, reduction=reduction
)
self.lossresult = nn.L1Loss(size_average=True, reduction=True)
elif opts.nca and self.old_classes != 0:
self.criterion = UnbiasedNCA(
old_cl=self.old_classes,
ignore_index=255,
reduction=reduction,
scale=model.module.scalar,
margin=opts.nca_margin
)
elif opts.nca:
self.criterion = NCA(
scale=model.module.scalar,
margin=opts.nca_margin,
ignore_index=255,
reduction=reduction
)
elif opts.focal_loss:
self.criterion = FocalLoss(ignore_index=255, reduction=reduction, alpha=opts.alpha, gamma=opts.focal_loss_gamma)
elif opts.focal_loss_new:
self.criterion = FocalLossNew(ignore_index=255, reduction=reduction, index=self.old_classes, alpha=opts.alpha, gamma=opts.focal_loss_gamma)
else:
# CE
self.criterion = nn.CrossEntropyLoss(ignore_index=255, reduction=reduction)
self.lossresult = nn.L1Loss(size_average=True, reduction=True)
if opts.out_dis and step > 0:
# soft label
self.criterion_soft_label = BCEWithLogitsLossWithIgnoreIndexSoftLabel(reduction=reduction, ignore_index=255)
# ILTSS
self.lde = opts.loss_de
self.lde_flag = self.lde > 0. and model_old is not None
self.lde_loss = nn.MSELoss()
self.lkd = opts.loss_kd
self.local_rank=opts.local_rank
self.lkd_mask = opts.kd_mask
self.kd_mask_adaptative_factor = opts.kd_mask_adaptative_factor
self.lkd_flag = self.lkd > 0. and model_old is not None
self.kd_need_labels = False
if opts.unkd:
self.lkd_loss = UnbiasedKnowledgeDistillationLoss(reduction="none", alpha=opts.alpha)
elif opts.myselfkd:
self.lkd_loss = MyselfKnowledgeDistillationLoss(reduction="none", alpha=opts.alpha)
elif opts.kd_bce_sig:
self.lkd_loss = BCESigmoid(reduction="none", alpha=opts.alpha, shape=opts.kd_bce_sig_shape)
elif opts.exkd_gt and self.old_classes > 0 and self.step > 0 and self.model_old is not None:
self.lkd_loss = ExcludedKnowledgeDistillationLoss(
reduction='none', index_new=self.old_classes, new_reduction="gt",
initial_nb_classes=opts.inital_nb_classes,
temperature_semiold=opts.temperature_semiold
)
self.kd_need_labels = True
elif opts.exkd_sum and self.old_classes > 0 and self.step > 0 and self.model_old is not None:
self.lkd_loss = ExcludedKnowledgeDistillationLoss(
reduction='none', index_new=self.old_classes, new_reduction="sum",
initial_nb_classes=opts.inital_nb_classes,
temperature_semiold=opts.temperature_semiold
)
self.kd_need_labels = True
else:
self.lkd_loss = KnowledgeDistillationLoss(alpha=opts.alpha)
# ICARL
self.icarl_combined = False
self.icarl_only_dist = False
if opts.icarl:
self.icarl_combined = not opts.icarl_disjoint and model_old is not None
self.icarl_only_dist = opts.icarl_disjoint and model_old is not None
if self.icarl_combined:
self.licarl = nn.BCEWithLogitsLoss(reduction='mean')
self.icarl = opts.icarl_importance
elif self.icarl_only_dist:
self.licarl = IcarlLoss(reduction='mean', bkg=opts.icarl_bkg)
self.icarl_dist_flag = self.icarl_only_dist or self.icarl_combined
# Regularization
regularizer_state = trainer_state['regularizer'] if trainer_state is not None else None
self.regularizer = get_regularizer(model, model_old, device, opts, regularizer_state)
self.regularizer_flag = self.regularizer is not None
self.reg_importance = opts.reg_importance
self.ret_intermediate = self.lde or (opts.pod is not None)
self.pseudo_labeling = opts.pseudo
self.threshold = opts.threshold
self.step_threshold = opts.step_threshold
self.ce_on_pseudo = opts.ce_on_pseudo
self.pseudo_nb_bins = opts.pseudo_nb_bins
self.pseudo_soft = opts.pseudo_soft
self.pseudo_soft_factor = opts.pseudo_soft_factor
self.pseudo_ablation = opts.pseudo_ablation
self.classif_adaptive_factor = opts.classif_adaptive_factor
self.classif_adaptive_min_factor = opts.classif_adaptive_min_factor
self.kd_new = opts.kd_new
self.pod = opts.pod
self.pod_options = opts.pod_options if opts.pod_options is not None else {}
self.pod_factor = opts.pod_factor
self.soft_factor = opts.soft_factor
self.pod_prepro = opts.pod_prepro
self.use_pod_schedule = not opts.no_pod_schedule
self.pod_deeplab_mask = opts.pod_deeplab_mask
self.pod_deeplab_mask_factor = opts.pod_deeplab_mask_factor
self.pod_apply = opts.pod_apply
self.pod_interpolate_last = opts.pod_interpolate_last
self.deeplab_mask_downscale = opts.deeplab_mask_downscale
self.spp_scales = opts.spp_scales
self.pod_logits = opts.pod_logits
self.pod_large_logits = opts.pod_large_logits
self.align_weight = opts.align_weight
self.align_weight_frequency = opts.align_weight_frequency
self.dataset = opts.dataset
self.entropy_min = opts.entropy_min
self.kd_scheduling = opts.kd_scheduling
self.sample_weights_new = opts.sample_weights_new
self.temperature_apply = opts.temperature_apply
self.temperature = opts.temperature
# CIL
self.ce_on_new = opts.ce_on_new
self.out_dis = opts.out_dis
self.pseudo_proto = opts.pseudo_proto
self.feat_dim = opts.feat_dim
self.no_mask = opts.no_mask
self.overlap = opts.overlap
self.proto_temperature = opts.proto_temperature
def before(self, cur_epoch, train_loader):
self.target_portion = min(self.init_portion + self.portion_step * cur_epoch, self.max_portion)
if self.pseudo_labeling is None:
return
if self.pseudo_labeling.split("_")[0] == "median" and self.step > 0:
self.thresholds, _ = self.find_median(train_loader, self.device)
elif self.pseudo_labeling.split("_")[0] == "entropy" and self.step > 0:
self.thresholds, self.max_entropy = self.find_median(
train_loader, self.target_portion, self.device, mode="entropy"
)
elif self.pseudo_labeling.split("_")[0] == "adapt" and self.step > 0:
self.thresholds, self.max_entropy = self.find_median(
train_loader, self.target_portion, self.device, mode="adapt"
)
def efficient_step_old_class_weight(self, output, label):
pred = torch.sigmoid(output)
labels_new = torch.where(label != 255, label, output.shape[1])
# replace ignore with numclasses + 1 (to enable one hot and then remove it)
target = F.one_hot(labels_new, output.shape[1] + 1).float().permute(0, 3, 1, 2)
target = target[:, :output.shape[1], :, :] # remove 255 from 1hot
class_mask = F.one_hot(labels_new, output.shape[1] + 1).float().permute(0, 3, 1, 2)
class_mask = class_mask[:, :output.shape[1], :, :] # remove 255 from 1hot
g = torch.abs(pred.detach() - target)
if self.step > 0:
z = torch.div(self.old_classes, self.nb_current_classes)
z = g.clone().fill_(z)
g = torch.pow(g, z)
g = (g * class_mask).sum(1) # torch.size([12, 1,h,w])
if self.old_classes != 0:
ids = torch.where(label >= self.inital_nb_classes, label, label.clone().fill_(-1))
index1 = torch.eq(ids, -1).float()
index2 = torch.ne(ids, -1).float()#new
if index1.sum() != 0:
w1 = torch.div(g * index1, (g * index1).sum() / index1.sum())
else:
w1 = g.clone().fill_(0.)
if index2.sum() != 0:
classes_sum = []
for c in range(len(self.classes)):
classes_sum.append(self.classes[c])
if c > 0:
classes_sum[c] = classes_sum[c-1]+self.classes[c]
#print(classes_sum)
w2 = g.clone().fill_(0.)
if self.step == 1:
w2 = index2
else:
for j in range(0, len(self.classes)-2):
a = g.clone().fill_(0.)
for i in range(classes_sum[0], classes_sum[j+1]):
#print(i)
b = torch.eq(ids, i).float()
a = a + b
if a.sum() != 0:
m = torch.div(g * a, (g * a).sum() / a.sum())
else:
m = g.clone().fill_(0.)
w2 = w2 + m
a = g.clone().fill_(0.)
for i in range(classes_sum[-2], classes_sum[-1]):
b = torch.eq(ids, i).float()
a = a + b
if a.sum() != 0:
m = a
else:
m = g.clone().fill_(0.)
w2 = w2 + m
else:
w2 = g.clone().fill_(0.)
w = w1 + w2
else:
w = g.clone().fill_(1.)
return w
def efficient_dis_old_class_weight(self, output, label):
pred = torch.sigmoid(output)
labels_new = torch.where(label != 255, label, output.shape[1])
# replace ignore with numclasses + 1 (to enable one hot and then remove it)
target = F.one_hot(labels_new, output.shape[1] + 1).float().permute(0, 3, 1, 2)
target = target[:, :output.shape[1], :, :] # remove 255 from 1hot
class_mask = F.one_hot(labels_new, output.shape[1] + 1).float().permute(0, 3, 1, 2)
class_mask = class_mask[:, :output.shape[1], :, :] # remove 255 from 1hot
g = torch.abs(pred.detach() - target)
if self.step > 0:
z = torch.div(self.old_classes, self.nb_current_classes)
z = g.clone().fill_(z)
g = torch.pow(g, z)
g = (g * class_mask).sum(1) # torch.size([12, 1,h,w])
if self.old_classes != 0:
ids = torch.where(label >= self.inital_nb_classes, label, label.clone().fill_(-1))
index1 = torch.eq(ids, -1).float()
index2 = torch.ne(ids, -1).float()#new
if index1.sum() != 0:
w1 = torch.div(g * index1, (g * index1).sum() / index1.sum())
else:
w1 = g.clone().fill_(0.)
if index2.sum() != 0:
classes_sum = []
for c in range(len(self.classes)):
classes_sum.append(self.classes[c])
if c > 0:
classes_sum[c] = classes_sum[c-1]+self.classes[c]
#print(classes_sum)
w2 = g.clone().fill_(0.)
if self.step == 1:
w2 = index2
else:
for j in range(0, len(self.classes)-2):
a = g.clone().fill_(0.)
for i in range(classes_sum[0], classes_sum[j+1]):
#print(i)
b = torch.eq(ids, i).float()
a = a + b
if a.sum() != 0:
m = torch.div(g * a, (g * a).sum() / a.sum())
else:
m = g.clone().fill_(0.)
w2 = w2 + m
a = g.clone().fill_(0.)
for i in range(classes_sum[-2], classes_sum[-1]):
b = torch.eq(ids, i).float()
a = a + b
if a.sum() != 0:
m = a
else:
m = g.clone().fill_(0.)
w2 = w2 + m
else:
w2 = g.clone().fill_(0.)
w = w1 + w2
else:
w = g.clone().fill_(1.)
weight_aver = torch.zeros(self.nb_current_classes, dtype=torch.float32).to(
self.device
)
weight_num = torch.zeros(self.nb_current_classes, dtype=torch.float32).to(
self.device
)
#labels_long = label.view(-1)
#w_long = w.view(-1)
# print(labels_long.size())#12,512,512
for i in range(0, self.nb_current_classes):
mask_weight = label ==i
weight_aver[i] = w[mask_weight].sum()
weight_num[i] = mask_weight.sum()
for i in range(0, self.nb_current_classes):
if weight_num[i]==0:
weight_aver[i] = 0
else:
weight_aver[i] = weight_aver[i] / weight_num[i]
return weight_aver
def reg_pesudo_label(self, output, label, num_classes):
output = torch.softmax(output, dim=1)
loss = -(output * torch.log(output)).mean(dim=1)
return loss
def train(self, cur_epoch, optim, train_loader, scheduler=None, print_int=10):
"""Train and return epoch loss"""
if self.rank==0:
print(f"Pseudo labeling is: {self.pseudo_labeling}")
print("Epoch %d, lr = %f" % (cur_epoch+1, optim.param_groups[0]['lr']))
device = self.device
model = self.model
criterion = self.criterion
lossresult = self.lossresult
model.module.in_eval = False
if self.model_old is not None:
self.model_old.in_eval = False
epoch_loss = 0.0
reg_loss = 0.0
interval_loss = 0.0
lkd = torch.tensor(0.)
lde = torch.tensor(0.)
l_icarl = torch.tensor(0.)
l_reg = torch.tensor(0.)
pod_loss = torch.tensor(0.)
loss_entmin = torch.tensor(0.)
loss_soft_label = torch.tensor(0.)
Regularizer_soft = torch.tensor(0.)
loss_dis = torch.tensor(0.)
sample_weights = None
train_loader.sampler.set_epoch(cur_epoch)
G=[]
model.train()
for cur_step, (images, labels) in enumerate(train_loader):
images = images.to(device, dtype=torch.float32)
labels = labels.to(device, dtype=torch.long)
original_labels = labels.clone()
old_cls_aver = torch.zeros(self.nb_current_classes, dtype=torch.float32).to(
self.device
)
old_cls_num = torch.zeros(self.nb_current_classes, dtype=torch.float32).to(
self.device
)
new_cls_num = torch.zeros(self.nb_current_classes, dtype=torch.float32).to(
self.device
)
new_cls_aver = torch.zeros(self.nb_current_classes, dtype=torch.float32).to(
self.device
)
if (
self.lde_flag or self.lkd_flag or self.icarl_dist_flag or self.pod is not None or
self.pseudo_labeling is not None
) and self.model_old is not None:
with torch.no_grad():
outputs_old, features_old = self.model_old(
images, ret_intermediate=self.ret_intermediate
)
classif_adaptive_factor = 1.0
if self.step > 0 and self.model_old is not None:
mask_background = labels < self.old_classes
if self.pseudo_labeling == "naive":
labels[mask_background] = outputs_old.argmax(dim=1)[mask_background]
elif self.pseudo_labeling is not None and self.pseudo_labeling.startswith(
"threshold_"
):
threshold = float(self.pseudo_labeling.split("_")[1])
probs = torch.softmax(outputs_old, dim=1)
pseudo_labels = probs.argmax(dim=1)
pseudo_labels[probs.max(dim=1)[0] < threshold] = 255
labels[mask_background] = pseudo_labels[mask_background]
elif self.pseudo_labeling == "confidence":
probs_old = torch.softmax(outputs_old, dim=1)
labels[mask_background] = probs_old.argmax(dim=1)[mask_background]
sample_weights = torch.ones_like(labels).to(device, dtype=torch.float32)
sample_weights[mask_background] = probs_old.max(dim=1)[0][mask_background]
elif self.pseudo_labeling == "median":
probs = torch.softmax(outputs_old, dim=1)
max_probs, pseudo_labels = probs.max(dim=1)
mask_valid_pseudo = max_probs > self.thresholds[pseudo_labels]
pseudo_labels[max_probs < self.thresholds[pseudo_labels]] = 255
labels[mask_background] = pseudo_labels[mask_background]
if self.classif_adaptive_factor:
# Number of old/bg pixels that are certain
num = (mask_valid_pseudo & mask_background).float().sum(dim=(1, 2))
# Number of old/bg pixels
den = mask_background.float().sum(dim=(1, 2))
# If all old/bg pixels are certain the factor is 1 (loss not changed)
# Else the factor is < 1, i.e. the loss is reduced to avoid
# giving too much importance to new pixels
classif_adaptive_factor = num / (den + 1e-6)
classif_adaptive_factor = classif_adaptive_factor[:, None, None]
if self.classif_adaptive_min_factor:
classif_adaptive_factor = classif_adaptive_factor.clamp(
min=self.classif_adaptive_min_factor)
elif self.pseudo_labeling == "entropy":
probs = torch.softmax(outputs_old, dim=1)
max_probs, pseudo_labels = probs.max(dim=1)
mask_valid_pseudo = (entropy(probs) /
self.max_entropy) < self.thresholds[pseudo_labels]
mask_unconfident_pseudo = (entropy(probs) /
self.max_entropy) >= self.thresholds[pseudo_labels]#(b, w, h)
if self.pseudo_soft is None:
# All old labels that are NOT confident enough to be used as pseudo labels:
labels[~mask_valid_pseudo & mask_background] = 255
if self.pseudo_ablation is None:
# All old labels that are confident enough to be used as pseudo labels:
labels[mask_valid_pseudo & mask_background] = pseudo_labels[mask_valid_pseudo &
mask_background]
#print('mask_valid', mask_valid_pseudo.size())
labels_pseudo = labels.clone().fill_(0)
labels_pseudo[mask_valid_pseudo & mask_background] = labels[mask_valid_pseudo & mask_background]
#print('labels_pseudo', labels_pseudo.size())
labels_unconfident = labels.clone().fill_(0)
labels_unconfident[mask_unconfident_pseudo & mask_background] = labels[
mask_unconfident_pseudo & mask_background]
elif self.pseudo_ablation == "corrected_errors":
pass # If used jointly with data_masking=current+old, the labels already
# contrain the GT, thus all potentials errors were corrected.
elif self.pseudo_ablation == "removed_errors":
pseudo_error_mask = labels != pseudo_labels
kept_pseudo_labels = mask_valid_pseudo & mask_background & ~pseudo_error_mask
removed_pseudo_labels = mask_valid_pseudo & mask_background & pseudo_error_mask
labels[kept_pseudo_labels] = pseudo_labels[kept_pseudo_labels]
labels[removed_pseudo_labels] = 255
else:
raise ValueError(f"Unknown type of pseudo_ablation={self.pseudo_ablation}")
elif self.pseudo_soft == "soft_uncertain":
labels[mask_valid_pseudo & mask_background] = pseudo_labels[mask_valid_pseudo &
mask_background]
for i in range(0, self.nb_current_classes):
mask_old = labels == i
old_cls_aver[i] = max_probs[mask_old].sum()
old_cls_num[i] = mask_old.sum()
for i in range(0, self.nb_current_classes):
if old_cls_num[i] == 0:
old_cls_aver[i] = 0
else:
old_cls_aver[i] = old_cls_aver[i] / old_cls_num[i]
if self.classif_adaptive_factor:
# Number of old/bg pixels that are certain
num = (mask_valid_pseudo & mask_background).float().sum(dim=(1,2))
# Number of old/bg pixels
den = mask_background.float().sum(dim=(1,2))
# If all old/bg pixels are certain the factor is 1 (loss not changed)
# Else the factor is < 1, i.e. the loss is reduced to avoid
# giving too much importance to new pixels
classif_adaptive_factor = num / (den + 1e-6)
classif_adaptive_factor = classif_adaptive_factor[:, None, None]
if self.classif_adaptive_min_factor:
classif_adaptive_factor = classif_adaptive_factor.clamp(min=self.classif_adaptive_min_factor)
optim.zero_grad()
outputs, features = model(images, ret_intermediate=self.ret_intermediate)
probs_new = torch.softmax(outputs, dim=1)
max_probs_new, pseudo_labels_new = probs_new.max(dim=1)
for i in range(0, self.nb_current_classes):
mask_new = pseudo_labels_new == i
new_cls_aver[i] = max_probs_new[mask_new].sum()
new_cls_num[i] = mask_new.sum()
for i in range(0,self.nb_current_classes):
if new_cls_num[i] == 0:
new_cls_aver[i] = 0
else:
new_cls_aver[i] = new_cls_aver[i] / new_cls_num[i]
# xxx BCE / Cross Entropy Loss
if self.pseudo_soft is not None:
loss = soft_crossentropy(
outputs,
labels,
outputs_old,
mask_valid_pseudo,
mask_background,
self.pseudo_soft,
pseudo_soft_factor=self.pseudo_soft_factor
)
elif not self.icarl_only_dist: # True
if self.ce_on_pseudo and self.step > 0 and self.model_old is not None:
assert self.pseudo_labeling is not None
assert self.pseudo_labeling == "entropy"
# Apply UNCE on:
# - all new classes (foreground)
# - old classes (background) that were not selected for pseudo
loss_not_pseudo = criterion(
outputs,
original_labels,
mask=mask_background & mask_valid_pseudo # what to ignore
)
# Apply CE on:
# - old classes that were selected for pseudo
_labels = original_labels.clone()
_labels[~(mask_background & mask_valid_pseudo)] = 255
_labels[mask_background & mask_valid_pseudo] = pseudo_labels[mask_background &
mask_valid_pseudo]
loss_pseudo = F.cross_entropy(
outputs, _labels, ignore_index=255, reduction="none"
)
# Each loss complete the others as they are pixel-exclusive
loss = loss_pseudo + loss_not_pseudo
elif self.ce_on_new:
_labels = labels.clone()
_labels[_labels == 0] = 255
loss = criterion(outputs, _labels) # B x H x W
else:
if self.out_dis and self.step > 0:
w = self.efficient_step_old_class_weight(outputs, labels)
w1 = self.efficient_dis_old_class_weight(outputs, labels)
loss_dis = lossresult(w1*new_cls_aver, w1*old_cls_aver) * 0.5
loss = criterion(outputs, labels)
loss = w*loss
else:
# B x H x W
loss = criterion(outputs, labels)
else:
loss = self.licarl(outputs, labels, torch.sigmoid(outputs_old))
if self.out_dis and self.step > 0:
old_outputs = torch.sigmoid(outputs_old)
old_classes = self.old_classes
loss_soft_label = self.criterion_soft_label(outputs, old_outputs, old_classes, labels)
Regularizer_soft = self.reg_pesudo_label(outputs, labels, self.old_classes)#
if self.sample_weights_new is not None:
sample_weights = torch.ones_like(original_labels).to(device, dtype=torch.float32)
sample_weights[original_labels >= 0] = self.sample_weights_new
if sample_weights is not None:
loss = loss * sample_weights
loss = classif_adaptive_factor * loss
loss = loss.mean() # scalar
loss_soft_label = loss_soft_label.mean()
Regularizer_soft = Regularizer_soft.mean()
if self.icarl_combined:
# tensor.narrow( dim, start, end) -> slice tensor from start to end in the specified dim
n_cl_old = outputs_old.shape[1]
# use n_cl_old to sum the contribution of each class, and not to average them (as done in our BCE).
l_icarl = self.icarl * n_cl_old * self.licarl(
outputs.narrow(1, 0, n_cl_old), torch.sigmoid(outputs_old)
)
# xxx ILTSS (distillation on features or logits)
if self.lde_flag:
lde = self.lde * self.lde_loss(features['body'], features_old['body'])
if self.lkd_flag:
# resize new output to remove new logits and keep only the old ones
if self.lkd_mask is not None and self.lkd_mask == "oldbackground":
kd_mask = labels < self.old_classes
elif self.lkd_mask is not None and self.lkd_mask == "new":
kd_mask = labels >= self.old_classes
else:
kd_mask = None
if self.temperature_apply is not None:
temp_mask = torch.ones_like(labels).to(outputs.device).to(outputs.dtype)
if self.temperature_apply == "all":
temp_mask = temp_mask / self.temperature
elif self.temperature_apply == "old":
mask_bg = labels < self.old_classes
temp_mask[mask_bg] = temp_mask[mask_bg] / self.temperature
elif self.temperature_apply == "new":
mask_fg = labels >= self.old_classes
temp_mask[mask_fg] = temp_mask[mask_fg] / self.temperature
temp_mask = temp_mask[:, None]
else:
temp_mask = 1.0
if self.kd_need_labels:
lkd = self.lkd * self.lkd_loss(
outputs * temp_mask, outputs_old * temp_mask, labels, mask=kd_mask
)
else:
lkd = self.lkd * self.lkd_loss(
outputs * temp_mask, outputs_old * temp_mask, mask=kd_mask
)
if self.kd_new: # WTF?
mask_bg = labels == 0
lkd = lkd[mask_bg]
if kd_mask is not None and self.kd_mask_adaptative_factor:
lkd = lkd.mean(dim=(1, 2)) * kd_mask.float().mean(dim=(1, 2))
lkd = torch.mean(lkd)
if self.pod is not None and self.step > 0 and self.model_old is not None:
attentions_old = features_old["attentions"]
attentions_new = features["attentions"]
if self.pod_logits:
attentions_old.append(features_old["sem_logits_small"])
attentions_new.append(features["sem_logits_small"])
elif self.pod_large_logits:
attentions_old.append(outputs_old)
attentions_new.append(outputs)
pod_loss = features_distillation(
attentions_old,
attentions_new,
collapse_channels=self.pod,
labels=labels,
index_new_class=self.old_classes,
pod_apply=self.pod_apply,
pod_deeplab_mask=self.pod_deeplab_mask,
pod_deeplab_mask_factor=self.pod_deeplab_mask_factor,
interpolate_last=self.pod_interpolate_last,
pod_factor=self.pod_factor,
prepro=self.pod_prepro,
deeplabmask_upscale=not self.deeplab_mask_downscale,
spp_scales=self.spp_scales,
pod_options=self.pod_options,
outputs_old=outputs_old,
use_pod_schedule=self.use_pod_schedule,
nb_current_classes=self.nb_current_classes,
nb_new_classes=self.nb_new_classes
)
if self.entropy_min > 0. and self.step > 0 and self.model_old is not None:
mask_new = labels > 0
entropies = entropy(torch.softmax(outputs, dim=1))
entropies[mask_new] = 0.
pixel_amount = (~mask_new).float().sum(dim=(1, 2))
loss_entmin = (entropies.sum(dim=(1, 2)) / pixel_amount).mean()
if self.kd_scheduling:
lkd = lkd * math.sqrt(self.nb_current_classes / self.nb_new_classes)
# xxx first backprop of previous loss (compute the gradients for regularization methods)
loss_tot = loss + lkd + lde + l_icarl + pod_loss + loss_entmin + self.soft_param * loss_soft_label + self.regular_param * Regularizer_soft + loss_dis
with amp.scale_loss(loss_tot, optim) as scaled_loss:
scaled_loss.backward()
# xxx Regularizer (EWC, RW, PI)
if self.regularizer_flag:
if distributed.get_rank() == 0:
self.regularizer.update()
l_reg = self.reg_importance * self.regularizer.penalty()
if l_reg != 0.:
with amp.scale_loss(l_reg, optim) as scaled_loss:
scaled_loss.backward()
optim.step()
if scheduler is not None:
scheduler.step()
epoch_loss += loss.item()
reg_loss += l_reg.item() if l_reg != 0. else 0.
reg_loss += lkd.item() + lde.item() + l_icarl.item()
interval_loss += loss.item() + lkd.item() + lde.item() + l_icarl.item() + pod_loss.item(
) + loss_entmin.item()
interval_loss += l_reg.item() if l_reg != 0. else 0.
if (cur_step + 1) % print_int == 0:
interval_loss = interval_loss / print_int
if self.rank==0:
print(
f"Epoch {cur_epoch+1}, Batch {cur_step + 1}/{len(train_loader)},"
f" Loss={interval_loss}"
)
print(
f"Loss made of: CE {loss}, LKD {lkd}, LDE {lde}, LReg {l_reg}, POD {pod_loss} EntMin {loss_entmin}"
)
# visualization
interval_loss = 0.0
# collect statistics from multiple processes
epoch_loss = torch.tensor(epoch_loss).to(self.device)
reg_loss = torch.tensor(reg_loss).to(self.device)
torch.distributed.reduce(epoch_loss, dst=0)
torch.distributed.reduce(reg_loss, dst=0)
if distributed.get_rank() == 0:
epoch_loss = epoch_loss / distributed.get_world_size() / len(train_loader)
reg_loss = reg_loss / distributed.get_world_size() / len(train_loader)
if self.rank==0:
print(f"Epoch {cur_epoch+1}, Class Loss={epoch_loss}, Reg Loss={reg_loss}")
return (epoch_loss, reg_loss)
def find_median(self, train_loader, target_portion, device, mode="probability"):
"""Find the median prediction score per class with the old model.
Computing the median naively uses a lot of memory, to allievate it, instead
we put the prediction scores into a histogram bins and approximate the median.
https://math.stackexchange.com/questions/2591946/how-to-find-median-from-a-histogram
"""
if mode == "entropy":
max_value = torch.log(torch.tensor(self.nb_current_classes).float().to(device))
nb_bins = 100
else:
max_value = 1.0
nb_bins = 20 # Bins of 0.05 on a range [0, 1]
if self.pseudo_nb_bins is not None:
nb_bins = self.pseudo_nb_bins
histograms = torch.zeros(self.nb_current_classes, nb_bins).long().to(self.device)
for cur_step, (images, labels) in enumerate(train_loader):
images = images.to(device, dtype=torch.float32)
labels = labels.to(device, dtype=torch.long)
outputs_old, features_old = self.model_old(images, ret_intermediate=True)
mask_bg = labels == 0
probas = torch.softmax(outputs_old, dim=1)
max_probas, pseudo_labels = probas.max(dim=1)
if mode == "entropy":
values_to_bins = entropy(probas)[mask_bg].view(-1) / max_value
else:
values_to_bins = max_probas[mask_bg].view(-1)
x_coords = pseudo_labels[mask_bg].view(-1)
y_coords = torch.clamp((values_to_bins * nb_bins).long(), max=nb_bins - 1)
histograms.index_put_(
(x_coords, y_coords),
torch.LongTensor([1]).expand_as(x_coords).to(histograms.device),
accumulate=True
)
thresholds = torch.zeros(self.nb_current_classes, dtype=torch.float32).to(
self.device
) # zeros or ones? If old_model never predict a class it may be important
for c in range(self.nb_current_classes):
total = histograms[c].sum()
if total <= 0.:
continue
if self.out_dis:
half = total * target_portion
else:
half = total / 2#
#half = total * 0.8
running_sum = 0.
for lower_border in range(nb_bins):
lower_border = lower_border / nb_bins
bin_index = int(lower_border * nb_bins)
if half >= running_sum and half <= (running_sum + histograms[c, bin_index]):
break
running_sum += lower_border * nb_bins
median = lower_border + ((half - running_sum) /
histograms[c, bin_index].sum()) * (1 / nb_bins)
thresholds[c] = median
base_threshold = self.threshold#0.8
if "_" in mode:
mode, base_threshold = mode.split("_")
base_threshold = float(base_threshold)
if self.step_threshold is not None:
self.threshold += self.step * self.step_threshold
if mode == "entropy":
for c in range(len(thresholds)):
thresholds[c] = max(thresholds[c], base_threshold)
else:
for c in range(len(thresholds)):
thresholds[c] = min(thresholds[c], base_threshold)
return thresholds.to(device), max_value
def validate(self, loader, metrics, ret_samples_ids=None, end_task=False):
"""Do validation and return specified samples"""
metrics.reset()
model = self.model
device = self.device
criterion = self.criterion
model.eval()
model.module.in_eval = True
if self.model_old is not None:
self.model_old.in_eval = True
class_loss = 0.0
reg_loss = 0.0
lkd = torch.tensor(0.)
lde = torch.tensor(0.)
l_icarl = torch.tensor(0.)
l_reg = torch.tensor(0.)
if self.step > 0 and self.model_old is not None and self.align_weight_frequency == "epoch":
model.module.align_weight(self.align_weight)
elif self.step > 0 and self.model_old is not None and self.align_weight_frequency == "task" and end_task:
model.module.align_weight(self.align_weight)
ret_samples = []
with torch.no_grad():
for i, (images, labels) in enumerate(loader):
images = images.to(device, dtype=torch.float32)
labels = labels.to(device, dtype=torch.long)
if (
self.lde_flag or self.lkd_flag or self.icarl_dist_flag
) and self.model_old is not None:
with torch.no_grad():
outputs_old, features_old = self.model_old(images, ret_intermediate=True)
outputs, features = model(images, ret_intermediate=True)
# xxx BCE / Cross Entropy Loss
if not self.icarl_only_dist:
loss = criterion(outputs, labels) # B x H x W
else:
loss = self.licarl(outputs, labels, torch.sigmoid(outputs_old))
loss = loss.mean() # scalar
if self.icarl_combined:
# tensor.narrow( dim, start, end) -> slice tensor from start to end in the specified dim
n_cl_old = outputs_old.shape[1]
# use n_cl_old to sum the contribution of each class, and not to average them (as done in our BCE).
l_icarl = self.icarl * n_cl_old * self.licarl(
outputs.narrow(1, 0, n_cl_old), torch.sigmoid(outputs_old)
)
# xxx ILTSS (distillation on features or logits)
if self.lde_flag:
lde = self.lde_loss(features['body'], features_old['body'])
if self.lkd_flag and not self.kd_need_labels:
lkd = self.lkd_loss(outputs, outputs_old).mean()
# xxx Regularizer (EWC, RW, PI)
if self.regularizer_flag:
l_reg = self.regularizer.penalty()
class_loss += loss.item()
reg_loss += l_reg.item() if l_reg != 0. else 0.
reg_loss += lkd.item() + lde.item() + l_icarl.item()
_, prediction = outputs.max(dim=1)
labels = labels.cpu().numpy()
prediction = prediction.cpu().numpy()
metrics.update(labels, prediction)
if ret_samples_ids is not None and i in ret_samples_ids: # get samples
ret_samples.append((images[0].detach().cpu().numpy(), labels[0], prediction[0]))
# collect statistics from multiple processes
metrics.synch(device)
score = metrics.get_results()
class_loss = torch.tensor(class_loss).to(self.device)
reg_loss = torch.tensor(reg_loss).to(self.device)
torch.distributed.reduce(class_loss, dst=0)
torch.distributed.reduce(reg_loss, dst=0)
if distributed.get_rank() == 0:
class_loss = class_loss / distributed.get_world_size() / len(loader)
reg_loss = reg_loss / distributed.get_world_size() / len(loader)
if self.rank==0:
print(
f"Validation, Class Loss={class_loss}, Reg Loss={reg_loss} (without scaling)"
)
return (class_loss, reg_loss), score, ret_samples
def state_dict(self):
state = {"regularizer": self.regularizer.state_dict() if self.regularizer_flag else None}
return state
def load_state_dict(self, state):
if state["regularizer"] is not None and self.regularizer is not None:
self.regularizer.load_state_dict(state["regularizer"])
def entropy(probabilities):
"""Computes the entropy per pixel.
# References:
* ESL: Entropy-guided Self-supervised Learning for Domain Adaptation in Semantic Segmentation
Saporta et al.