-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathengine.py
More file actions
1301 lines (1107 loc) · 60.4 KB
/
engine.py
File metadata and controls
1301 lines (1107 loc) · 60.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import time
import datetime
import json
import copy
import pandas as pd
import torch
import numpy as np
from torch.utils.data import DataLoader
from datasets.coco_style_dataset import DataPreFetcher
from datasets.coco_eval import CocoEvaluator
# from datasets.sfuod_eval import SFUODevaluator
from models.criterion import post_process, get_pseudo_labels, get_known_pseudo_labels, get_unknown_pseudo_labels, get_unknown_pseudo_labels_attn, get_topk_outputs, SetCriterion
from utils.distributed_utils import is_main_process
from utils.box_utils import box_cxcywh_to_xyxy, convert_to_xywh
from collections import defaultdict
from typing import List
from datasets.masking import Masking
from scipy.optimize import linear_sum_assignment
from utils.box_utils import box_cxcywh_to_xyxy, generalized_box_iou
from utils import selective_reinitialize
def train_one_epoch_standard(model: torch.nn.Module,
criterion: torch.nn.Module,
data_loader: DataLoader,
optimizer: torch.optim.Optimizer,
device: torch.device,
epoch: int,
clip_max_norm: float = 0.0,
print_freq: int = 20,
flush: bool = True):
"""
Train the standard detection model, using only labelled training set source.
"""
start_time = time.time()
model.train()
criterion.train()
fetcher = DataPreFetcher(data_loader, device=device)
images, masks, annotations = fetcher.next()
# Training statistics
epoch_loss = torch.zeros(1, dtype=torch.float, device=device, requires_grad=False)
epoch_loss_dict = defaultdict(float)
for i in range(len(data_loader)):
# Forward
out = model(images, masks)
# Loss
loss, loss_dict = criterion(out, annotations)
# Backward
optimizer.zero_grad()
loss.backward()
if clip_max_norm > 0:
torch.nn.utils.clip_grad_norm_(model.parameters(), clip_max_norm)
optimizer.step()
# Record loss
epoch_loss += loss.detach()
for k, v in loss_dict.items():
epoch_loss_dict[k] += v.detach().cpu().item()
# Data pre-fetch
images, masks, annotations = fetcher.next()
# Log
if is_main_process() and (i + 1) % print_freq == 0:
print('Training epoch ' + str(epoch) + ' : [ ' + str(i + 1) + '/' + str(len(data_loader)) + ' ] ' +
'total loss: ' + str(loss.detach().cpu().numpy()), flush=flush)
# Final process of training statistic
epoch_loss /= len(data_loader)
for k, v in epoch_loss_dict.items():
epoch_loss_dict[k] /= len(data_loader)
end_time = time.time()
total_time_str = str(datetime.timedelta(seconds=int(end_time - start_time)))
print('Training epoch ' + str(epoch) + ' finished. Time cost: ' + total_time_str +
' Epoch loss: ' + str(epoch_loss.detach().cpu().numpy()), flush=flush)
return epoch_loss, epoch_loss_dict
def train_one_epoch_teaching_standard(student_model: torch.nn.Module,
teacher_model: torch.nn.Module,
criterion_pseudo: torch.nn.Module,
target_loader: DataLoader,
optimizer: torch.optim.Optimizer,
thresholds: List[float],
alpha_ema: float,
device: torch.device,
epoch: int,
clip_max_norm: float = 0.0,
print_freq: int = 20,
flush: bool = True,
fix_update_iter: int = 1):
"""
Train the student model with the teacher model, using only unlabeled training set target .
"""
start_time = time.time()
student_model.train()
teacher_model.train()
criterion_pseudo.train()
target_fetcher = DataPreFetcher(target_loader, device=device)
target_images, target_masks, _ = target_fetcher.next()
target_teacher_images, target_student_images = target_images[0], target_images[1]
# Record epoch losses
epoch_loss = torch.zeros(1, dtype=torch.float, device=device, requires_grad=False)
# Training data statistics
epoch_target_loss_dict = defaultdict(float)
total_iters = len(target_loader)
for iter in range(total_iters):
# Target teacher forward
with torch.no_grad():
teacher_out = teacher_model(target_teacher_images, target_masks)
pseudo_labels = get_pseudo_labels(teacher_out['logit_all'][-1], teacher_out['boxes_all'][-1], thresholds)
#todo OW-DETR Pseudo Labeling for unknown
# pseudo_labels = get_ow_pseudo_labels(target_teacher_images, teacher_out['resnet_1024_feat'], teacher_out['logit_all'][-1], teacher_out['boxes_all'][-1], thresholds)
#todo Unknown Pseudo Label is needed
# ps_labels=torch.tensor([])
# for ps_dict in pseudo_labels:
# ps_labels = torch.cat([ps_labels, ps_dict['labels'].cpu()], dim=0)
# print('[Pseudo Labels]', ps_labels.unique(return_counts=True))
# Target student forward
target_student_out = student_model(target_student_images, target_masks)
target_loss, target_loss_dict = criterion_pseudo(target_student_out, pseudo_labels)
loss = target_loss
# Backward
optimizer.zero_grad()
loss.backward()
if clip_max_norm > 0:
torch.nn.utils.clip_grad_norm_(student_model.parameters(), clip_max_norm)
optimizer.step()
# Record epoch losses
epoch_loss += loss.detach()
# update loss_dict
for k, v in target_loss_dict.items():
epoch_target_loss_dict[k] += v.detach().cpu().item()
if iter % fix_update_iter == 0:
with torch.no_grad():
state_dict, student_state_dict = teacher_model.state_dict(), student_model.state_dict()
for key, value in state_dict.items():
state_dict[key] = alpha_ema * value + (1 - alpha_ema) * student_state_dict[key].detach()
teacher_model.load_state_dict(state_dict)
# Data pre-fetch
target_images, target_masks, _ = target_fetcher.next()
if target_images is not None:
target_teacher_images, target_student_images = target_images[0], target_images[1]
# Log
if is_main_process() and (iter + 1) % print_freq == 0:
print('Teaching epoch ' + str(epoch) + ' : [ ' + str(iter + 1) + '/' + str(total_iters) + ' ] ' +
'total loss: ' + str(loss.detach().cpu().numpy()), flush=flush)
# Final process of loss dict
epoch_loss /= total_iters
for k, v in epoch_target_loss_dict.items():
epoch_target_loss_dict[k] /= total_iters
end_time = time.time()
total_time_str = str(datetime.timedelta(seconds=int(end_time - start_time)))
print('Teaching epoch ' + str(epoch) + ' finished. Time cost: ' + total_time_str +
' Epoch loss: ' + str(epoch_loss.detach().cpu().numpy()), flush=flush)
return epoch_loss, epoch_target_loss_dict
# with torch.no_grad():
# teacher_out_k = teacher_model(target_teacher_images, target_masks)
# k_pseudo_labels, k_batch_indices = get_known_pseudo_labels(teacher_out_k['logit_all'][-1], teacher_out_k['boxes_all'][-1], thresholds)
# u_pseudo_labels = get_unknown_pseudo_labels(teacher_out_k['logit_all'][-1], teacher_out_k['boxes_all'][-1], teacher_out_k['hidden_states_last'], k_batch_indices)
# if len(u_pseudo_labels) > 0:
# pseudo_labels = []
# for k_anno, u_anno in zip(k_pseudo_labels, u_pseudo_labels):
# # print('k_anno:',k_anno['scores'].shape[0])
# # print('u_anno:',u_anno['scores'].shape[0])
# total_scores = torch.cat([k_anno['scores'], u_anno['scores']])
# # print('total_anno:',total_scores.shape[0])
# total_labels = torch.cat([k_anno['labels'], u_anno['labels']])
# total_boxes = torch.cat([k_anno['boxes'], u_anno['boxes']])
# pseudo_labels.append({'scores': total_scores, 'labels': total_labels, 'boxes': total_boxes})
# else:
# pseudo_labels = k_pseudo_labels
def train_one_epoch_teaching_unknown_specialist(student_model: torch.nn.Module,
teacher_model: torch.nn.Module,
init_student_model: torch.nn.Module,
criterion_pseudo: torch.nn.Module,
criterion_pseudo_weak: torch.nn.Module,
target_loader: DataLoader,
optimizer: torch.optim.Optimizer,
thresholds: List[float],
coef_masked_img: float,
alpha_ema: float,
device: torch.device,
epoch: int,
keep_modules: List[str],
clip_max_norm: float = 0.0,
print_freq: int = 20,
masking: Masking = None,
flush: bool = True,
fix_update_iter: int = 1,
max_update_iter: int = 5,
dynamic_update: bool = False,
stu_buffer_cost: List[float] = None,
stu_buffer_img: List[torch.Tensor] = None,
stu_buffer_mask: List[torch.Tensor] = None,
res_dict: dict = None,
use_pseudo_label_weights: bool = False,
use_loss_student: bool = False,
unk_thresh: float = 0.3):
"""
Train the student model with the teacher model, using only unlabeled training set target .
"""
start_time = time.time()
student_model.train()
teacher_model.train()
init_student_model.train()
criterion_pseudo.train()
criterion_pseudo_weak.train()
target_fetcher = DataPreFetcher(target_loader, device=device)
target_images, target_masks, _ = target_fetcher.next()
target_teacher_images, target_student_images = target_images[0], target_images[1]
# Record epoch losses
epoch_loss = torch.zeros(1, dtype=torch.float, device=device, requires_grad=False)
# Training data statistics
epoch_target_loss_dict = defaultdict(float)
total_iters = len(target_loader)
for iter in range(total_iters):
# Target teacher forward
with torch.no_grad():
teacher_out = teacher_model(target_teacher_images, target_masks, bi_attn=False)
# pseudo_labels = get_pseudo_labels(teacher_out['logit_all'][-1], teacher_out['boxes_all'][-1], thresholds)
#* Ours ..
teacher_out_k = teacher_model(target_teacher_images, target_masks, bi_attn=False)
k_pseudo_labels, k_batch_indices = get_known_pseudo_labels(teacher_out_k['logit_all'][-1], teacher_out_k['boxes_all'][-1], thresholds)
u_pseudo_labels = get_unknown_pseudo_labels(teacher_out_k['logit_all'][-1], teacher_out_k['boxes_all'][-1], teacher_out_k['hidden_states_last'], k_batch_indices, unk_threshold=unk_thresh)
#* u_pseudo_labels = get_unknown_pseudo_labels_attn(target_teacher_images, teacher_out_k['logit_all'][-1], teacher_out_k['boxes_all'][-1], teacher_out_k['resnet_1024_feat'], k_batch_indices, unk_threshold=unk_thresh)
if len(u_pseudo_labels) > 0:
pseudo_labels = []
for k_anno, u_anno in zip(k_pseudo_labels, u_pseudo_labels):
total_scores = torch.cat([k_anno['scores'], u_anno['scores']])
total_labels = torch.cat([k_anno['labels'], u_anno['labels']])
total_boxes = torch.cat([k_anno['boxes'], u_anno['boxes']])
pseudo_labels.append({'scores': total_scores, 'labels': total_labels, 'boxes': total_boxes})
else:
pseudo_labels = k_pseudo_labels
#* ============================================
target_student_out = student_model(target_student_images, target_masks)
# loss from pseudo labels of current teacher
target_loss, target_loss_dict = criterion_pseudo(target_student_out, pseudo_labels)
#? Masked target student forward
#* masked_target_images = masking(target_student_images)
#* masked_target_student_out = student_model(masked_target_images, target_masks)
#* masked_target_loss, masked_target_loss_dict = criterion_pseudo(masked_target_student_out, pseudo_labels)
# Final loss
#* loss = target_loss + coef_masked_img * masked_target_loss
loss = target_loss
# Dynamic update EMA teacher : Create buffer cost and buffer image in student model
if dynamic_update:
with torch.no_grad():
# print("[Engine] Student_Foward: Dunamic Update")
student_out = student_model(target_teacher_images, target_masks)
# variance logit
student_out_var = student_out['logit_all'].var(dim=0)
var_total = student_out_var.mean().item()
stu_buffer_cost.append(var_total)
# Store batch data to buffer
stu_buffer_img.append(target_teacher_images.clone().detach())
stu_buffer_mask.append(target_masks.clone().detach())
if len(stu_buffer_cost) == 1:
with torch.no_grad():
init_student_model.load_state_dict(student_model.state_dict())
if len(stu_buffer_cost) >= 1:
with torch.no_grad():
init_student_out = init_student_model(target_teacher_images, target_masks)
# init_pseudo_labels = get_pseudo_labels(init_student_out['logit_all'][-1], init_student_out['boxes_all'][-1],thresholds)
#* Ours..
pseudo_labels_init_student, init_k_batch_indices = get_known_pseudo_labels(init_student_out['logit_all'][-1], init_student_out['boxes_all'][-1],thresholds)
init_u_pseudo_labels = get_unknown_pseudo_labels(init_student_out['logit_all'][-1], init_student_out['boxes_all'][-1], init_student_out['hidden_states_last'], init_k_batch_indices, unk_threshold=unk_thresh)
if len(init_u_pseudo_labels) > 0:
init_pseudo_labels = []
for k_anno, u_anno in zip(pseudo_labels_init_student, init_u_pseudo_labels):
total_scores = torch.cat([k_anno['scores'], u_anno['scores']])
total_labels = torch.cat([k_anno['labels'], u_anno['labels']])
total_boxes = torch.cat([k_anno['boxes'], u_anno['boxes']])
init_pseudo_labels.append({'scores': total_scores, 'labels': total_labels, 'boxes': total_boxes})
else:
init_pseudo_labels = pseudo_labels_init_student
#* ==================================
# Loss from pseudo labels of init student
init_student_loss, init_student_loss_dict = criterion_pseudo_weak(target_student_out,
init_pseudo_labels, use_pseudo_label_weights)
#* masked_init_student_loss, masked_init_student_loss_dict = criterion_pseudo_weak(masked_target_student_out, init_pseudo_labels, use_pseudo_label_weights)
#* loss_init_student = init_student_loss + coef_masked_img * masked_init_student_loss
loss_init_student = init_student_loss
loss += loss_init_student
# Backward
optimizer.zero_grad()
loss.backward()
if clip_max_norm > 0:
torch.nn.utils.clip_grad_norm_(student_model.parameters(), clip_max_norm)
optimizer.step()
# Record epoch losses
epoch_loss += loss.detach()
# update loss_dict
for k, v in target_loss_dict.items():
epoch_target_loss_dict[k] += v.detach().cpu().item()
# Dynamic update EMA teacher : Update weight of teacher model
if dynamic_update:
if len(stu_buffer_cost) < max_update_iter:
all_score = eval_stu(student_model, stu_buffer_img, stu_buffer_mask)
compare_score = np.array(all_score) - np.array(stu_buffer_cost)
# print(len(stu_buffer_cost), len(all_score), np.mean(compare_score<0))
if np.mean(compare_score < 0) >= 0.5:
res_dict['stu_ori'].append(stu_buffer_cost)
res_dict['stu_now'].append(all_score)
res_dict['update_iter'].append(len(stu_buffer_cost))
df = pd.DataFrame(res_dict)
df.to_csv('dynamic_update.csv')
with torch.no_grad():
state_dict, student_state_dict = teacher_model.state_dict(), student_model.state_dict()
for key, value in state_dict.items():
state_dict[key] = alpha_ema * value + (1 - alpha_ema) * student_state_dict[key].detach()
teacher_model.load_state_dict(state_dict)
# Clear buffer
stu_buffer_cost = []
stu_buffer_img = []
stu_buffer_mask = []
else:
# print(len(stu_buffer_cost), 'Load previous student model weight')
with torch.no_grad():
student_model = selective_reinitialize(student_model, init_student_model.state_dict(), keep_modules)
# Clear buffer
stu_buffer_cost = []
stu_buffer_img = []
stu_buffer_mask = []
else:
# EMA update teacher after fix iteration
if iter % fix_update_iter == 0:
with torch.no_grad():
state_dict, student_state_dict = teacher_model.state_dict(), student_model.state_dict()
for key, value in state_dict.items():
state_dict[key] = alpha_ema * value + (1 - alpha_ema) * student_state_dict[key].detach()
teacher_model.load_state_dict(state_dict)
# Data pre-fetch
target_images, target_masks, _ = target_fetcher.next()
if target_images is not None:
target_teacher_images, target_student_images = target_images[0], target_images[1]
# Log
if is_main_process() and (iter + 1) % print_freq == 0:
print('Teaching epoch ' + str(epoch) + ' : [ ' + str(iter + 1) + '/' + str(total_iters) + ' ] ' +
'total loss: ' + str(loss.detach().cpu().numpy()), flush=flush)
# Final process of loss dict
epoch_loss /= total_iters
for k, v in epoch_target_loss_dict.items():
epoch_target_loss_dict[k] /= total_iters
end_time = time.time()
total_time_str = str(datetime.timedelta(seconds=int(end_time - start_time)))
print('Teaching epoch ' + str(epoch) + ' finished. Time cost: ' + total_time_str +
' Epoch loss: ' + str(epoch_loss.detach().cpu().numpy()), flush=flush)
return epoch_loss, epoch_target_loss_dict
# def train_one_epoch_teaching_unknown_specialist2(student_model: torch.nn.Module,
def train_one_epoch_teaching_unknown_specialist2(student_model: torch.nn.Module,
teacher_model: torch.nn.Module,
criterion_pseudo: torch.nn.Module,
target_loader: DataLoader,
optimizer: torch.optim.Optimizer,
thresholds: List[float],
alpha_ema: float,
device: torch.device,
epoch: int,
clip_max_norm: float = 0.0,
print_freq: int = 20,
flush: bool = True,
fix_update_iter: int = 1,
unk_thresh: float = 0.3):
"""
Train the student model with the teacher model, using only unlabeled training set target .
"""
start_time = time.time()
student_model.train()
teacher_model.train()
criterion_pseudo.train()
target_fetcher = DataPreFetcher(target_loader, device=device)
target_images, target_masks, _ = target_fetcher.next()
target_teacher_images, target_student_images = target_images[0], target_images[1]
# Record epoch losses
epoch_loss = torch.zeros(1, dtype=torch.float, device=device, requires_grad=False)
# Training data statistics
epoch_target_loss_dict = defaultdict(float)
total_iters = len(target_loader)
for iter in range(total_iters):
# Target teacher forward
with torch.no_grad():
#? Original
# teacher_out = teacher_model(target_teacher_images, target_masks)
# pseudo_labels = get_pseudo_labels(teacher_out['logit_all'][-1], teacher_out['boxes_all'][-1], thresholds)
teacher_out_k = teacher_model(target_teacher_images, target_masks, bi_attn=False)
k_pseudo_labels, k_batch_indices = get_known_pseudo_labels(teacher_out_k['logit_all'][-1], teacher_out_k['boxes_all'][-1], thresholds)
u_pseudo_labels = get_unknown_pseudo_labels(teacher_out_k['logit_all'][-1], teacher_out_k['boxes_all'][-1], teacher_out_k['hidden_states_last'], k_batch_indices, unk_threshold=unk_thresh)
if len(u_pseudo_labels) > 0:
pseudo_labels = []
for k_anno, u_anno in zip(k_pseudo_labels, u_pseudo_labels):
total_scores = torch.cat([k_anno['scores'], u_anno['scores']])
total_labels = torch.cat([k_anno['labels'], u_anno['labels']])
total_boxes = torch.cat([k_anno['boxes'], u_anno['boxes']])
pseudo_labels.append({'scores': total_scores, 'labels': total_labels, 'boxes': total_boxes})
else:
pseudo_labels = k_pseudo_labels
# Target student forward
target_student_out = student_model(target_student_images, target_masks)
target_loss, target_loss_dict = criterion_pseudo(target_student_out, pseudo_labels)
loss = target_loss
# Backward
optimizer.zero_grad()
loss.backward()
if clip_max_norm > 0:
torch.nn.utils.clip_grad_norm_(student_model.parameters(), clip_max_norm)
optimizer.step()
# Record epoch losses
epoch_loss += loss.detach()
# update loss_dict
for k, v in target_loss_dict.items():
epoch_target_loss_dict[k] += v.detach().cpu().item()
if iter % fix_update_iter == 0:
with torch.no_grad():
state_dict, student_state_dict = teacher_model.state_dict(), student_model.state_dict()
for key, value in state_dict.items():
state_dict[key] = alpha_ema * value + (1 - alpha_ema) * student_state_dict[key].detach()
teacher_model.load_state_dict(state_dict)
# Data pre-fetch
target_images, target_masks, _ = target_fetcher.next()
if target_images is not None:
target_teacher_images, target_student_images = target_images[0], target_images[1]
# Log
if is_main_process() and (iter + 1) % print_freq == 0:
print('Teaching epoch ' + str(epoch) + ' : [ ' + str(iter + 1) + '/' + str(total_iters) + ' ] ' +
'total loss: ' + str(loss.detach().cpu().numpy()), flush=flush)
# Final process of loss dict
epoch_loss /= total_iters
for k, v in epoch_target_loss_dict.items():
epoch_target_loss_dict[k] /= total_iters
end_time = time.time()
total_time_str = str(datetime.timedelta(seconds=int(end_time - start_time)))
print('Teaching epoch ' + str(epoch) + ' finished. Time cost: ' + total_time_str +
' Epoch loss: ' + str(epoch_loss.detach().cpu().numpy()), flush=flush)
return epoch_loss, epoch_target_loss_dict
def train_one_epoch_upuk(student_model: torch.nn.Module,
teacher_model: torch.nn.Module,
criterion_pseudo: torch.nn.Module,
target_loader: DataLoader,
optimizer: torch.optim.Optimizer,
thresholds: List[float],
alpha_ema: float,
device: torch.device,
epoch: int,
clip_max_norm: float = 0.0,
print_freq: int = 20,
flush: bool = True,
fix_update_iter: int = 1):
"""
teacher_model: NetB+NetC
"""
import torch.nn.functional as F
start_time = time.time()
student_model.train()
teacher_model.train()
criterion_pseudo.train()
target_fetcher = DataPreFetcher(target_loader, device=device)
target_images, target_masks, _ = target_fetcher.next()
target_teacher_images, target_student_images = target_images[0], target_images[1]
# Record epoch losses
epoch_loss = torch.zeros(1, dtype=torch.float, device=device, requires_grad=False)
# Training data statistics
epoch_target_loss_dict = defaultdict(float)
total_iters = len(target_loader)
num_sample = len(target_loader.dataset)
# fea_bank = torch.randn(num_sample, 256)
# score_bank = torch.randn(num_sample, 3).cuda()
fea_bank = []
score_bank = []
for iter in range(total_iters):
# fea_bank.append(output_norm.detach().clone().cpu())
# score_bank.append(outputs.detach().clone().cpu())
# fea_bank = torch.cat(fea_bank, dim=0)
# score_bank = torch.cat(score_bank, dim=0)
# Target teacher forward
with torch.no_grad():
teacher_out = teacher_model(target_teacher_images, target_masks)
pseudo_labels = get_pseudo_labels(teacher_out['logit_all'][-1], teacher_out['boxes_all'][-1], thresholds)
# out_dict = teacher_model(target_student_images, target_masks)
tea_outputs = teacher_out['logit_all'][-1]
# tea_output_f = out_dict['hidden_states_last']
# tea_f_norm = F.normalize(tea_output_f)
tea_prob = F.softmax(tea_outputs, dim=-1)
# Target student forward
target_student_out = student_model(target_student_images, target_masks)
# outputs = teacher_model(inputs, image_mask)['logit_all'][-1]
# output_f = teacher_model(inputs, image_mask)['hidden_states_last']
# tea_f_norm = F.normalize(output_f)
# tea_prob = F.softmax(dim=-1)(outputs)
stu_outputs = target_student_out['logit_all'][-1]
# stu_output_f = target_student_out['hidden_states_last'][-1]
# stu_f_norm = F.normalize(stu_output_f)
stu_prob = F.softmax(stu_outputs, dim=-1)
# fa = a.flatten(start_dim=0, end_dim=1)
upuk_loss_1 = torch.mean(F.kl_div(stu_prob, tea_prob, reduction='none'))
# (stu_f_norm.flatten(start_dim=0, end_dim=1) @ stu_f_norm.flatten(start_dim=0, end_dim=1).T).diag()
stu_scores = stu_prob.flatten(start_dim=0, end_dim=1)
mask = torch.ones((stu_scores.shape[0], stu_scores.shape[0]), device=device)
diag_num = torch.diag(mask)
mask_diag = torch.diag_embed(diag_num)
mask = mask - mask_diag
copy = stu_scores.T
dot_neg = stu_scores @ copy
dot_neg = (dot_neg * mask).sum(-1)
upuk_loss_2 = torch.mean(dot_neg)
target_loss, target_loss_dict = criterion_pseudo(target_student_out, pseudo_labels)
loss = target_loss + 0.2*(upuk_loss_1 + upuk_loss_2)
# Backward
optimizer.zero_grad()
loss.backward()
if clip_max_norm > 0:
torch.nn.utils.clip_grad_norm_(student_model.parameters(), clip_max_norm)
optimizer.step()
# Record epoch losses
epoch_loss += loss.detach()
# update loss_dict
for k, v in target_loss_dict.items():
epoch_target_loss_dict[k] += v.detach().cpu().item()
if iter % fix_update_iter == 0:
with torch.no_grad():
state_dict, student_state_dict = teacher_model.state_dict(), student_model.state_dict()
for key, value in state_dict.items():
state_dict[key] = alpha_ema * value + (1 - alpha_ema) * student_state_dict[key].detach()
teacher_model.load_state_dict(state_dict)
# Data pre-fetch
target_images, target_masks, _ = target_fetcher.next()
if target_images is not None:
target_teacher_images, target_student_images = target_images[0], target_images[1]
# Log
if is_main_process() and (iter + 1) % print_freq == 0:
print('Teaching epoch ' + str(epoch) + ' : [ ' + str(iter + 1) + '/' + str(total_iters) + ' ] ' +
'total loss: ' + str(loss.detach().cpu().numpy()), flush=flush)
# Final process of loss dict
epoch_loss /= total_iters
for k, v in epoch_target_loss_dict.items():
epoch_target_loss_dict[k] /= total_iters
end_time = time.time()
total_time_str = str(datetime.timedelta(seconds=int(end_time - start_time)))
print('Teaching epoch ' + str(epoch) + ' finished. Time cost: ' + total_time_str +
' Epoch loss: ' + str(epoch_loss.detach().cpu().numpy()), flush=flush)
return epoch_loss, epoch_target_loss_dict
def analysis_process(model: torch.nn.Module,
criterion: torch.nn.Module,
data_loader: DataLoader,
device: torch.device
):
"""
Train the standard detection model, using only labelled training set source.
"""
start_time = time.time()
model.eval()
criterion.eval()
fetcher = DataPreFetcher(data_loader, device=device)
target_images, masks, annotations = fetcher.next()
# target_fetcher = DataPreFetcher(target_loader, device=device)
# target_images, target_masks, _ = target_fetcher.next()
teacher_images, student_images = target_images[0], target_images[1]
teacher_dict={}
student_dict={}
# Training statistics
# epoch_loss = torch.zeros(1, dtype=torch.float, device=device, requires_grad=False)
# epoch_loss_dict = defaultdict(float)
def merging_dicts(agg_dict, iter_dict, domain):
for cid in iter_dict.keys():
if cid not in agg_dict.keys():
agg_dict[cid] = {}
for iter_key in iter_dict[cid].keys():
if iter_key not in agg_dict[cid].keys():
agg_dict[cid][iter_key]=[iter_dict[cid][iter_key].cpu()]
# try:
# agg_dict[cid][iter_key]=[iter_dict[cid][iter_key].cpu()]
# except:
# print('iter_key:',iter_key)
# print('Value:', iter_dict[cid][iter_key])
else:
agg_dict[cid][iter_key].append(iter_dict[cid][iter_key].cpu())
# print(f"Write Dict Info -{domain}-")
for i in range(len(data_loader)):
# if i>10:
# break
# Forward
with torch.no_grad():
out = model(teacher_images, masks)
# Loss
#* loss, loss_dict = criterion(out, annotations)
iter_tea_dict = criterion.analysis(teacher_images.cpu(), out, annotations)
del out
if iter_tea_dict is not None:
# print('='*50)
# print(f'[Iter: {i}]Image: Teacher Image')
merging_dicts(teacher_dict, iter_tea_dict, 'Teacher')
# print()
# print('='*50)
# print('Image: Student Image')
# # Forward
# out = model(student_images, masks)
# iter_stu_dict = criterion.analysis(student_images.cpu(), out, annotations)
# del out
# if iter_stu_dict is not None:
# merging_dicts(student_dict, iter_stu_dict, 'Student')
# print()
target_images, masks, annotations = fetcher.next()
if target_images is not None:
teacher_images, student_images = target_images[0], target_images[1]
text_detail = ['logit_candid_score', 'logit_gt_score', 'logit_candid_label_acc', 'hidden_state_intra_sim', 'hidden_state_bgd_sim', 'res_attn']
for a_key in teacher_dict.keys():
print(f'[Merge Result] [Categories: {a_key}]')
for k,v in teacher_dict[a_key].items():
# agg_value = torch.cat(v,dim=0)
try:
# 예외가 발생할 가능성이 있는 코드
agg_value = torch.cat(v,dim=0)
except:
# 예외가 발생했을 때 실행할 코드
# print('Potential Error: RuntimeError: zero-dimensional tensor (at position 0) cannot be concatenated')
# print('Key:', k)
agg_value = torch.tensor(v)
if k in text_detail:
if k == 'res_attn':
mask = torch.isnan(agg_value)
print(f'{k} (num: {len(v)}): {agg_value.shape} || Not nan: {(~mask).sum()} || AVG: {agg_value[~mask].mean()}')
else:
print(f'{k} (num: {len(v)}): {agg_value.shape} || AVG: {agg_value.mean()}')
else:
print(f'{k} (num: {len(v)}): {agg_value.shape}')
print()
end_time = time.time()
total_time_str = str(datetime.timedelta(seconds=int(end_time - start_time)))
print('Finished. Time cost: ', total_time_str)
torch.save(teacher_dict, '/data/pgh2874/SFOpen_suites/DRU/outputs/def-detr-base/SFUOD/city2foggy/teaching_standard_analysis/analysis_dict.pt')
print('save info dicts..')
def train_one_epoch_teaching_mask(student_model: torch.nn.Module,
teacher_model: torch.nn.Module,
init_student_model: torch.nn.Module,
criterion_pseudo: torch.nn.Module,
criterion_pseudo_weak: torch.nn.Module,
target_loader: DataLoader,
optimizer: torch.optim.Optimizer,
thresholds: List[float],
coef_masked_img: float,
alpha_ema: float,
device: torch.device,
epoch: int,
keep_modules: List[str],
clip_max_norm: float = 0.0,
print_freq: int = 20,
masking: Masking = None,
flush: bool = True,
fix_update_iter: int = 1,
max_update_iter: int = 5,
dynamic_update: bool = False,
stu_buffer_cost: List[float] = None,
stu_buffer_img: List[torch.Tensor] = None,
stu_buffer_mask: List[torch.Tensor] = None,
res_dict: dict = None,
use_pseudo_label_weights: bool = False,
use_loss_student: bool = False):
"""
Train the student model with the teacher model, using only unlabeled training set target (plus masked target image)
"""
start_time = time.time()
student_model.train()
teacher_model.train()
init_student_model.train()
criterion_pseudo.train()
criterion_pseudo_weak.train()
target_fetcher = DataPreFetcher(target_loader, device=device)
target_images, target_masks, _ = target_fetcher.next()
target_teacher_images, target_student_images = target_images[0], target_images[1]
# Record epoch losses
epoch_loss = torch.zeros(1, dtype=torch.float, device=device, requires_grad=False)
# Training data statistics
epoch_target_loss_dict = defaultdict(float)
total_iters = len(target_loader)
for iter in range(total_iters):
# Target teacher forward
with torch.no_grad():
teacher_out = teacher_model(target_teacher_images, target_masks)
pseudo_labels = get_pseudo_labels(teacher_out['logit_all'][-1], teacher_out['boxes_all'][-1], thresholds)
# Target student forward
target_student_out = student_model(target_student_images, target_masks)
# loss from pseudo labels of current teacher
target_loss, target_loss_dict = criterion_pseudo(target_student_out, pseudo_labels)
# Masked target student forward
masked_target_images = masking(target_student_images)
masked_target_student_out = student_model(masked_target_images, target_masks)
# loss from pseudo labels of current teacher
masked_target_loss, masked_target_loss_dict = criterion_pseudo(masked_target_student_out, pseudo_labels)
# Final loss
loss = target_loss + coef_masked_img * masked_target_loss
# Loss from pseudo labels of previous student (just testing, not used)
# if use_loss_student:
# # Loss from pseudo labels of previous student
# with torch.no_grad():
# student_out = student_model(target_teacher_images, target_masks)
# pseudo_labels_student = get_pseudo_labels(student_out['logit_all'][-1], student_out['boxes_all'][-1],
# thresholds)
# target_loss_student, target_loss_dict_student = criterion_pseudo_weak(target_student_out,
# pseudo_labels_student, use_pseudo_label_weights)
# masked_target_loss_student, masked_target_loss_dict_student = criterion_pseudo_weak(masked_target_student_out,
# pseudo_labels_student, use_pseudo_label_weights)
#
# # Final loss
# loss_student = target_loss_student + coef_masked_img * masked_target_loss_student
# loss += loss_student
# Dynamic update EMA teacher : Create buffer cost and buffer image in student model
if dynamic_update:
with torch.no_grad():
student_out = student_model(target_teacher_images, target_masks)
# variance logit
student_out_var = student_out['logit_all'].var(dim=0)
var_total = student_out_var.mean().item()
stu_buffer_cost.append(var_total)
# Store batch data to buffer
stu_buffer_img.append(target_teacher_images.clone().detach())
stu_buffer_mask.append(target_masks.clone().detach())
if len(stu_buffer_cost) == 1:
with torch.no_grad():
init_student_model.load_state_dict(student_model.state_dict())
if len(stu_buffer_cost) >= 1:
with torch.no_grad():
init_student_out = init_student_model(target_teacher_images, target_masks)
pseudo_labels_init_student = get_pseudo_labels(init_student_out['logit_all'][-1], init_student_out['boxes_all'][-1],
thresholds)
# Loss from pseudo labels of init student
init_student_loss, init_student_loss_dict = criterion_pseudo_weak(target_student_out,
pseudo_labels_init_student, use_pseudo_label_weights)
masked_init_student_loss, masked_init_student_loss_dict = criterion_pseudo_weak(masked_target_student_out,
pseudo_labels_init_student, use_pseudo_label_weights)
loss_init_student = init_student_loss + coef_masked_img * masked_init_student_loss
loss += loss_init_student
# Backward
optimizer.zero_grad()
loss.backward()
if clip_max_norm > 0:
torch.nn.utils.clip_grad_norm_(student_model.parameters(), clip_max_norm)
optimizer.step()
# Record epoch losses
epoch_loss += loss.detach()
# update loss_dict
for k, v in target_loss_dict.items():
epoch_target_loss_dict[k] += v.detach().cpu().item()
# Dynamic update EMA teacher : Update weight of teacher model
if dynamic_update:
if len(stu_buffer_cost) < max_update_iter:
all_score = eval_stu(student_model, stu_buffer_img, stu_buffer_mask)
compare_score = np.array(all_score) - np.array(stu_buffer_cost)
# print(len(stu_buffer_cost), len(all_score), np.mean(compare_score<0))
if np.mean(compare_score < 0) >= 0.5:
res_dict['stu_ori'].append(stu_buffer_cost)
res_dict['stu_now'].append(all_score)
res_dict['update_iter'].append(len(stu_buffer_cost))
df = pd.DataFrame(res_dict)
df.to_csv('dynamic_update.csv')
with torch.no_grad():
state_dict, student_state_dict = teacher_model.state_dict(), student_model.state_dict()
for key, value in state_dict.items():
state_dict[key] = alpha_ema * value + (1 - alpha_ema) * student_state_dict[key].detach()
teacher_model.load_state_dict(state_dict)
# Clear buffer
stu_buffer_cost = []
stu_buffer_img = []
stu_buffer_mask = []
else:
# print(len(stu_buffer_cost), 'Load previous student model weight')
with torch.no_grad():
student_model = selective_reinitialize(student_model, init_student_model.state_dict(), keep_modules)
# Clear buffer
stu_buffer_cost = []
stu_buffer_img = []
stu_buffer_mask = []
else:
# EMA update teacher after fix iteration
if iter % fix_update_iter == 0:
with torch.no_grad():
state_dict, student_state_dict = teacher_model.state_dict(), student_model.state_dict()
for key, value in state_dict.items():
state_dict[key] = alpha_ema * value + (1 - alpha_ema) * student_state_dict[key].detach()
teacher_model.load_state_dict(state_dict)
# Data pre-fetch
target_images, target_masks, _ = target_fetcher.next()
if target_images is not None:
target_teacher_images, target_student_images = target_images[0], target_images[1]
# Log
if is_main_process() and (iter + 1) % print_freq == 0:
print('Teaching epoch ' + str(epoch) + ' : [ ' + str(iter + 1) + '/' + str(total_iters) + ' ] ' +
'total loss: ' + str(loss.detach().cpu().numpy()), flush=flush)
# Final process of loss dict
epoch_loss /= total_iters
for k, v in epoch_target_loss_dict.items():
epoch_target_loss_dict[k] /= total_iters
end_time = time.time()
total_time_str = str(datetime.timedelta(seconds=int(end_time - start_time)))
print('Teaching epoch ' + str(epoch) + ' finished. Time cost: ' + total_time_str +
' Epoch loss: ' + str(epoch_loss.detach().cpu().numpy()), flush=flush)
return epoch_loss, epoch_target_loss_dict
@torch.no_grad()
def evaluate(model: torch.nn.Module,
criterion: torch.nn.Module,
data_loader_val: DataLoader,
device: torch.device,
print_freq: int,
output_result_labels: bool = False,
flush: bool = False,
bi_attn: bool = True):
start_time = time.time()
model.eval()
criterion.eval()
if hasattr(data_loader_val.dataset, 'coco') or hasattr(data_loader_val.dataset, 'anno_file'):
evaluator = CocoEvaluator(data_loader_val.dataset.coco)
coco_data = json.load(open(data_loader_val.dataset.anno_file, 'r'))
# dataset_annotations = [[] for _ in range(len(coco_data['images']))]
dataset_annotations = defaultdict(list)
else:
raise ValueError('Unsupported dataset type.')
epoch_loss = 0.0
for i, (images, masks, annotations) in enumerate(data_loader_val):
# To CUDA
images = images.to(device)
masks = masks.to(device)
annotations = [{k: v.to(device) for k, v in t.items()} for t in annotations]
# Forward
# out = model(images, masks, bi_attn=bi_attn)
out = model(images, masks)
logit_all, boxes_all = out['logit_all'], out['boxes_all']
# Get pseudo labels
if output_result_labels:
#? results = get_pseudo_labels(logit_all[-1], boxes_all[-1], [0.4 for _ in range(9)])
results = get_pseudo_labels(logit_all[-1], boxes_all[-1], [0.4 for _ in range(10)])
for anno, res in zip(annotations, results):
image_id = anno['image_id'].item()
orig_image_size = anno['orig_size']
img_h, img_w = orig_image_size.unbind(0)
scale_fct = torch.stack([img_w, img_h, img_w, img_h])
converted_boxes = convert_to_xywh(box_cxcywh_to_xyxy(res['boxes'] * scale_fct))
converted_boxes = converted_boxes.detach().cpu().numpy().tolist()
for label, box in zip(res['labels'].detach().cpu().numpy().tolist(), converted_boxes):
pseudo_anno = {
'id': 0,
'image_id': image_id,
'category_id': label,
'iscrowd': 0,
'area': box[-2] * box[-1],
'bbox': box
}
# dataset_annotations[image_id].append(pseudo_anno)
dataset_annotations[image_id].append(pseudo_anno)
# Loss
loss, loss_dict = criterion(out, annotations)
epoch_loss += loss
if is_main_process() and (i + 1) % print_freq == 0:
print('Evaluation : [ ' + str(i + 1) + '/' + str(len(data_loader_val)) + ' ] ' +
'total loss: ' + str(loss.detach().cpu().numpy()), flush=flush)
# mAP
orig_image_sizes = torch.stack([anno['orig_size'] for anno in annotations], dim=0)
results = post_process(logit_all[-1], boxes_all[-1], orig_image_sizes, 100)
results = {anno['image_id'].item(): res for anno, res in zip(annotations, results)}
evaluator.update(results)
evaluator.synchronize_between_processes()
evaluator.accumulate()
aps = evaluator.summarize()
epoch_loss /= len(data_loader_val)
end_time = time.time()
total_time_str = str(datetime.timedelta(seconds=int(end_time - start_time)))
print('Evaluation finished. Time cost: ' + total_time_str, flush=flush)
# Save results
if output_result_labels:
dataset_annotations_return = []
id_cnt = 0
# for image_anno in dataset_annotations: