-
Notifications
You must be signed in to change notification settings - Fork 0
/
losses.py
1883 lines (1602 loc) · 84.6 KB
/
losses.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 torch
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
from torch.autograd import Variable
import time
import pdb
import math
torch.set_default_tensor_type('torch.cuda.FloatTensor')
def investigate_pairs(x,labels,n_similar):
pairs=[]
for i in range(0,n_similar*2,2):
# [C]
shared_label = (labels[i, :] * labels[i + 1, :])
neg_candidates=[]
for j in range(0,x.shape[0]):
if (shared_label*labels[j]).sum()==0:
neg_candidates.append(j)
if len(neg_candidates)!=0:
pairs.append(i,i+1,np.random.choice(neg_candidates))
return pairs
def Cycle_Pseudo_Loss(x,proj_x,element_logits,n_similar,labels,device,lambd,is_back=False,k=8):
cycle_loss=0
if is_back:
labels = torch.cat(
(labels, torch.ones_like(labels[:, [0]])), dim=-1)
else:
labels = torch.cat(
(labels, torch.zeros_like(labels[:, [0]])), dim=-1)
_, n, c = element_logits.shape
x = x / torch.norm(x, p=2, dim=-1, keepdim=True)
proj_x = proj_x / torch.norm(x, p=2, dim=-1, keepdim=True)
for i in range(0, n_similar * 2, 2):
# [c]->[c,t] as mask
shared_label = (labels[i, :] * labels[i + 1, :]).unsqueeze(0).repeat(n, 1).bool().to(device)
atn1 = torch.masked_select(torch.softmax(element_logits[i], dim=-1), shared_label)[:n]
atn2 = torch.masked_select(torch.softmax(element_logits[i + 1], dim=-1), shared_label)[:n]
_,topk_idx1=torch.topk(atn1,n//int(k),dim=-1)
_,topk_idx2=torch.topk(atn2,n//int(k),dim=-1)
pseudo_labels_1=torch.zeros_like(atn1).to(device).int()
pseudo_labels_2=torch.zeros_like(atn2).to(device).int()
pseudo_labels_1[topk_idx1]=1
pseudo_labels_2[topk_idx2]=1
proj_topk1=x[i][topk_idx1]
proj_topk2=x[i+1][topk_idx2]
# calculate the similar matrix, [K,T]
sim_mat1=torch.softmax(torch.mm(proj_topk1,x[i+1].t())*lambd,dim=-1)
sim_mat2=torch.softmax(torch.mm(proj_topk2,x[i].t())*lambd,dim=-1)
_,sim_topk2=torch.topk(sim_mat1.mean(dim=0),n//int(k),dim=-1)
_,sim_topk1=torch.topk(sim_mat2.mean(dim=0),n//int(k),dim=-1)
pseudo_labels_k1=torch.zeros_like(atn1).to(device).int()
pseudo_labels_k2=torch.zeros_like(atn2).to(device).int()
pseudo_labels_k1[sim_topk1]=1
pseudo_labels_k2[sim_topk2]=1
pseudo_labels_1=pseudo_labels_1*pseudo_labels_k1
pseudo_labels_2=pseudo_labels_2*pseudo_labels_k2
select_pred1=torch.masked_select(atn1,pseudo_labels_1.bool())
select_pred2=torch.masked_select(atn2,pseudo_labels_2.bool())
select_pred=torch.cat([select_pred1,select_pred2],dim=-1)
if select_pred.shape[0]==0:
continue
else:
cycle_loss+=(-torch.log(select_pred+1e-8)).mean()
return cycle_loss/n_similar
def Co_Attention_Loss(x,affine_mat,element_logits,n_similar,labels,device,lambd,is_back=False):
ca_loss=0
b,n,c=element_logits.shape
for i in range(0,n_similar*2,2):
shared_label = (labels[i, :] * labels[i + 1, :]).unsqueeze(0).repeat(n, 1).bool().to(device)
atn1 = torch.masked_select(torch.softmax(element_logits[i], dim=1), shared_label)[:n]#.detach()
atn2 = torch.masked_select(torch.softmax(element_logits[i + 1], dim=1), shared_label)[:n]#.detach()
# x with shape [T,C]*[C,C]*[C,T] => [T,T]
P=torch.mm(torch.mm(x[i],affine_mat),x[i+1].t())
def Cross_Localize_Loss(x,proj_x,element_logits,n_similar,labels,device,lambd,is_back=False,**args):
cycle_loss = 0
if is_back:
labels = torch.cat(
(labels, torch.ones_like(labels[:, [0]])), dim=-1)
else:
labels = torch.cat(
(labels, torch.zeros_like(labels[:, [0]])), dim=-1)
n_tmp = 0.
# pairs=investigate_pairs(x,labels,n_similar)
_, n, c = element_logits.shape
x=x/torch.norm(x,p=2,dim=-1,keepdim=True)
proj_x=proj_x/torch.norm(x,p=2,dim=-1,keepdim=True)
for i in range(0, n_similar * 2, 2):
# [c]->[c,t] as mask
shared_label = (labels[i, :] * labels[i + 1, :]).unsqueeze(0).repeat(n, 1).bool().to(device)
atn1 = torch.masked_select(torch.softmax(element_logits[i], dim=1), shared_label)[:n]#.detach()
atn2 = torch.masked_select(torch.softmax(element_logits[i + 1], dim=1), shared_label)[:n]#.detach()
# to select the proj_x by topk
_,topk_idx1=torch.topk(atn1,n//8)
_,topk_idx2=torch.topk(atn2,n//8)
# _,bottom_idx1=torch.topk(atn1,7*n//8,largest=False)
# _,bottom_idx2=torch.topk(atn2,7*n//8,largest=False)
#
proj_topk1=proj_x[i][topk_idx1]
proj_topk2=proj_x[i+1][topk_idx2]
# calculate the similar matrix, [K,T]
sim_mat1=torch.softmax(torch.mm(proj_topk1,x[i+1].t().detach()),dim=-1)
sim_mat2=torch.softmax(torch.mm(proj_topk2,x[i].t().detach()),dim=-1)
# calculate the similarity
# select_k1 = ((atn2.squeeze() - sim_mat1.mean(dim=0))**2).mean()
# select_k2 = ((atn1.squeeze() - sim_mat2.mean(dim=0))**2).mean()
select_k1=torch.abs(atn2.squeeze()-sim_mat1.mean(dim=0)).mean()
select_k2=torch.abs(atn1.squeeze()-sim_mat2.mean(dim=0)).mean()
cycle_loss+=0.5*select_k1+0.5*select_k2
# to calculate the similar matrix, but let them more similar to each other than others
# sim_mat2=torch.mm(proj_topk1,x[i+1].t())
# sim_mat1=torch.mm(proj_topk2,x[i].t())
#
# dis1=torch.mean(1-sim_mat2[:,topk_idx2])
# dis2=torch.mean(1-sim_mat1[:,topk_idx1])
# dis3=torch.mean(1-sim_mat2[:,bottom_idx2])
# dis4=torch.mean(1-sim_mat1[:,bottom_idx1])
#
# cycle_loss=0.5*(torch.relu(dis3-dis1+0.5)+torch.relu(dis4-dis2+0.5))
return cycle_loss/n_similar
def Cycle_Feat_Loss(x,proj_x, element_logits, n_similar, labels, device, lambd, is_back=False,k=8):
cycle_loss = 0
k=int(k)
if is_back:
labels = torch.cat(
(labels, torch.ones_like(labels[:, [0]])), dim=-1)
else:
labels = torch.cat(
(labels, torch.zeros_like(labels[:, [0]])), dim=-1)
n_tmp = 0.
# pairs=investigate_pairs(x,labels,n_similar)
_, n, c = element_logits.shape
x=x/torch.norm(x,p=2,dim=-1,keepdim=True)
proj_x=proj_x/torch.norm(x,p=2,dim=-1,keepdim=True).detach()
for i in range(0, n_similar * 2, 2):
# [c]->[c,t] as mask
shared_label = (labels[i, :] * labels[i + 1, :]).unsqueeze(0).repeat(n, 1).bool().to(device)
atn1 = torch.masked_select(torch.softmax(element_logits[i], dim=1), shared_label)[:n]#.detach()
atn2 = torch.masked_select(torch.softmax(element_logits[i + 1], dim=1), shared_label)[:n]#.detach()
# to select the proj_x by topk
_,topk_idx1=torch.topk(atn1,n//k)
_,topk_idx2=torch.topk(atn2,n//k)
#
proj_topk1=x[i][topk_idx1]
proj_topk2=x[i+1][topk_idx2]
# calculate the similar matrix, [K,T]
sim_mat1=torch.softmax(torch.mm(proj_topk1,x[i+1].t()).view(-1),dim=-1).view(n//k,n)
sim_mat2=torch.softmax(torch.mm(proj_topk2,x[i].t()).view(-1),dim=-1).view(n//k,n)
recon_feat2=torch.mm(sim_mat1,x[i+1]).sum(dim=0,keepdim=True)
recon_feat1=torch.mm(sim_mat2,x[i]).sum(dim=0,keepdim=True)
recon_feat2=recon_feat2//torch.norm(recon_feat2,2,dim=-1)
recon_feat1=recon_feat1//torch.norm(recon_feat1,2,dim=-1)
resim_1=torch.softmax(torch.mm(recon_feat1,x[i].t()).view(-1)*lambd,dim=-1)
resim_2=torch.softmax(torch.mm(recon_feat2,x[i+1].t()).view(-1)*lambd,dim=-1)
cycle_loss+=-0.5*(torch.log(resim_1[topk_idx1].sum()+1e-8)+torch.log(resim_2[topk_idx2].sum()+1e-8))
#cycle_loss += 0.5 * (torch.mean((gfeat1 - recon_gfeat1) ** 2) + torch.mean((gfeat2 - recon_gfeat2) ** 2))
#cycle_loss+=0.5*(1-dis_1+1-dis_2)
return cycle_loss / n_similar
def Cycle_Feat_Loss_2(x,proj_x, element_logits, n_similar, labels, device, lambd, is_back=False,k=8):
cycle_loss = 0
k=int(k)
if is_back:
labels = torch.cat(
(labels, torch.ones_like(labels[:, [0]])), dim=-1)
else:
labels = torch.cat(
(labels, torch.zeros_like(labels[:, [0]])), dim=-1)
n_tmp = 0.
# pairs=investigate_pairs(x,labels,n_similar)
_, n, c = element_logits.shape
x=x/torch.norm(x,p=2,dim=-1,keepdim=True)
proj_x=proj_x/torch.norm(x,p=2,dim=-1,keepdim=True)
for i in range(0, n_similar * 2, 2):
# [c]->[c,t] as mask
shared_label = (labels[i, :] * labels[i + 1, :]).unsqueeze(0).repeat(n, 1).bool().to(device)
atn1 = torch.masked_select(torch.softmax(element_logits[i], dim=1), shared_label)[:n]#.detach()
atn2 = torch.masked_select(torch.softmax(element_logits[i + 1], dim=1), shared_label)[:n]#.detach()
# to select the proj_x by topk
_,topk_idx1=torch.topk(atn1,n//k)
_,topk_idx2=torch.topk(atn2,n//k)
_,bottom_idx1=torch.topk(atn1,(k-1)*n//k,largest=False)
_,bottom_idx2=torch.topk(atn2,(k-1)*n//k,largest=False)
#
proj_topk1=x[i][topk_idx1]
proj_topk2=x[i+1][topk_idx2]
# calculate the similar matrix, [K,T]
sim_mat1=torch.softmax(torch.mm(proj_topk1,x[i+1].t()).view(-1),dim=-1).view(n//k,n)
sim_mat2=torch.softmax(torch.mm(proj_topk2,x[i].t()).view(-1),dim=-1).view(n//k,n)
recon_feat2=torch.mm(sim_mat1,x[i+1]).sum(dim=0,keepdim=True)
recon_feat1=torch.mm(sim_mat2,x[i]).sum(dim=0,keepdim=True)
recon_feat2=recon_feat2//torch.norm(recon_feat2,2,dim=-1)
recon_feat1=recon_feat1//torch.norm(recon_feat1,2,dim=-1)
# [1,T-K]
bottom_sim1=torch.mm(recon_feat1,x[i][bottom_idx1].t())
bottom_sim2=torch.mm(recon_feat2,x[i+1][bottom_idx2].t())
# [1,K]
top_sim1=torch.mm(recon_feat1,x[i][topk_idx1].t())
top_sim2=torch.mm(recon_feat2,x[i+1][topk_idx2].t())
# [K,T-K+1]
resim_1=torch.softmax(torch.cat([bottom_sim1.repeat(n//k,1),top_sim1.t()],dim=-1)*lambd,dim=-1)
resim_2=torch.softmax(torch.cat([bottom_sim2.repeat(n//k,1),top_sim2.t()],dim=-1)*lambd,dim=-1)
# cycle_loss+=-0.5*(torch.log(resim_1[:,-1]+1e-8).mean()+torch.log(resim_2[:,-1]+1e-8).mean())
cycle_loss+=0.5*(1-resim_1[:,-1]).mean()+0.5*(1-resim_2[:,-1]).mean()
#cycle_loss += 0.5 * (torch.mean((gfeat1 - recon_gfeat1) ** 2) + torch.mean((gfeat2 - recon_gfeat2) ** 2))
#cycle_loss+=0.5*(1-dis_1+1-dis_2)
return cycle_loss / n_similar
def Contrastive_Memory_Loss(x,element_logits,labels,memory,lambd,is_back=False):
if is_back:
labels = torch.cat(
(labels, torch.ones_like(labels[:, [0]])), dim=-1)
else:
labels = torch.cat(
(labels, torch.zeros_like(labels[:, [0]])), dim=-1)
sim_loss = 0.
n_tmp = 0.
b, n, c = element_logits.shape
for i in range(b):
atn=F.softmax(element_logits[i],dim=0)
# [Ch,Cl]
Hf=torch.mm(torch.transpose(x[i],1,0),atn)
Lf=torch.mm(torch.transpose(x[i],1,0),(1-atn)/(n-1))
Hf=Hf/torch.norm(Hf,2,dim=0,keepdim=True)
Lf=Lf/torch.norm(Lf,2,dim=0,keepdim=True)
# Memory [Ch,Cl]
norm_mem=memory/torch.norm(memory,2,dim=0,keepdim=True)
H_sim=torch.softmax(torch.mm(Hf.t(),norm_mem)*lambd,dim=-1)# [cl,cl]
L_sim=torch.softmax(torch.mm(Lf.t(),norm_mem)*lambd,dim=-1)
# we hope the Hf is similar to the memory of the gt_class
# Lf is far away from that
gt=labels[i]
# to get the cross corner line of the matrix
eye_mat=torch.eye(c).to(x.device).bool()
# [cl]
H_sim=torch.masked_select(H_sim,eye_mat)
L_sim=torch.masked_select(L_sim,eye_mat)
sim_loss+=-0.5*((gt*torch.log(H_sim+1e-8)).sum()+(gt*torch.log(1-L_sim+1e-8)).sum())
sim_loss=sim_loss/b
return sim_loss
def Cycle_Score_Loss(x,proj_x,element_logits,n_similar,labels,device,lambd,is_back=False):
cycle_loss = 0
if is_back:
labels = torch.cat(
(labels, torch.ones_like(labels[:, [0]])), dim=-1)
else:
labels = torch.cat(
(labels, torch.zeros_like(labels[:, [0]])), dim=-1)
n_tmp = 0.
# pairs=investigate_pairs(x,labels,n_similar)
_, n, c = element_logits.shape
x = x / torch.norm(x, p=2, dim=-1, keepdim=True)
proj_x = proj_x / torch.norm(x, p=2, dim=-1, keepdim=True)
for i in range(0, n_similar * 2, 2):
# [c]->[c,t] as mask
shared_label = (labels[i, :] * labels[i + 1, :]).unsqueeze(0).repeat(n, 1).bool().to(device)
atn1 = torch.masked_select(torch.softmax(element_logits[i], dim=1), shared_label)[:n]
atn2 = torch.masked_select(torch.softmax(element_logits[i + 1], dim=1), shared_label)[:n]
# to select the proj_x by topk
# topk_atn1, topk_idx1 = torch.topk(atn1, n // 8)
# topk_atn2, topk_idx2 = torch.topk(atn2, n // 8)
# _,bottom_idx1=torch.topk(atn1,7*n//8,largest=False)
# _,bottom_idx2=torch.topk(atn2,7*n//8,largest=False)
#
# proj_topk1 = x[i][topk_idx1]
# proj_topk2 = x[i + 1][topk_idx2]
# calculate the similar matrix, [K,T]
sim_mat = torch.mm(x[i], x[i + 1].t()).detach()
retrieval_score_2=torch.mm(atn1.unsqueeze(0),torch.softmax(sim_mat*lambd,dim=-1)).squeeze(0)
retrieval_score_1=torch.mm(atn2.unsqueeze(0),torch.softmax(sim_mat.t()*lambd,dim=-1)).squeeze(0)
# score transfer, [1,K]*[K,T]=[1,T] get the score
# retrieval_score_2=torch.mm(topk_atn1.unsqueeze(0),sim_mat1).squeeze()
# retrieval_score_1=torch.mm(topk_atn2.unsqueeze(0),sim_mat2).squeeze()
cycle_loss+=0.5*torch.abs(atn1-retrieval_score_1.detach()).mean()+0.5*torch.abs(atn2-retrieval_score_2.detach()).mean()
return cycle_loss/n_similar
def Cycle_Cosine_Loss(x, element_logits, n_similar, labels, device, args, is_back=False):
cycle_loss = 0
if is_back:
labels = torch.cat(
(labels, torch.ones_like(labels[:, [0]])), dim=-1)
else:
labels = torch.cat(
(labels, torch.zeros_like(labels[:, [0]])), dim=-1)
n_tmp = 0.
_, n, c = element_logits.shape
for i in range(0, n_similar * 2, 2):
# [c]->[c,t] as mask
shared_label = (labels[i, :] * labels[i + 1, :]).unsqueeze(0).repeat(n, 1).bool().to(device)
# [t]
# import pdb
# pdb.set_trace()
atn1 = torch.masked_select(F.softmax(element_logits[i], dim=0), shared_label)[:n].detach()
atn2 = torch.masked_select(F.softmax(element_logits[i + 1], dim=0), shared_label)[:n].detach()
topk_mask_1=(atn1>torch.argsort(atn1,dim=0,descending=False)[n//8]).float()
topk_mask_2=(atn2>torch.argsort(atn2,dim=0,descending=False)[n//8]).float()
# to calculate the similar matrix
# [C,T]
feat_1 = x[i] / torch.norm(x[i], 2, dim=-1, keepdim=True)
feat_2 = x[i + 1] / torch.norm(x[i + 1], 2, dim=-1, keepdim=True)
# [T,T]->[T,C]
sim_matrix = torch.mm(feat_1, feat_2.transpose(-1, -2))
recon_feat_1 = torch.mm(sim_matrix, feat_2)
recon_feat_2 = torch.mm(sim_matrix.t(), feat_1)
recon_feat_1=recon_feat_1/torch.norm(recon_feat_1,dim=-1,keepdim=True)
recon_feat_2=recon_feat_2/torch.norm(recon_feat_2,dim=-1,keepdim=True)
# to calculate the cosine distance
dis_1=torch.mean(atn1.unsqueeze(-1)*torch.sum(recon_feat_1*feat_1,dim=-1))
dis_2=torch.mean(atn2.unsqueeze(-1)*torch.sum(recon_feat_2*feat_2,dim=-1))
# dis_1=torch.mean(atn1.detach()*torch.mean((recon_feat_1-feat_1)**2,dim=-1))
# dis_2=torch.mean(atn2.detach()*torch.mean((recon_feat_2-feat_2)**2,dim=-1))
# gfeat1 = torch.mean(atn1.unsqueeze(-1) * feat_1,dim=0)
# recon_gfeat1 = torch.mean(atn1.unsqueeze(-1) * recon_feat_1,dim=0)
# gfeat2 = torch.mean(atn2.unsqueeze(-1) * feat_2,dim=0)
# recon_gfeat2 = torch.mean(atn2.unsqueeze(-1) * recon_feat_2,dim=0)
#cycle_loss += 0.5 * (torch.mean((gfeat1 - recon_gfeat1) ** 2) + torch.mean((gfeat2 - recon_gfeat2) ** 2))
cycle_loss+=0.5*(1-dis_1+1-dis_2)
return cycle_loss / n_similar
def Cycle_Loss(x, element_logits, n_similar, labels, device, args, is_back=False):
cycle_loss = 0
if is_back:
labels = torch.cat(
(labels, torch.ones_like(labels[:, [0]])), dim=-1)
else:
labels = torch.cat(
(labels, torch.zeros_like(labels[:, [0]])), dim=-1)
n_tmp = 0.
_, n, c = element_logits.shape
for i in range(0, n_similar * 2, 2):
# [c]->[c,t] as mask
shared_label = (labels[i, :] * labels[i + 1, :]).unsqueeze(0).repeat(n, 1).bool().to(device)
# [t]
# import pdb
# pdb.set_trace()
atn1 = torch.masked_select(F.softmax(element_logits[i], dim=0), shared_label)[:n]
atn2 = torch.masked_select(F.softmax(element_logits[i + 1], dim=0), shared_label)[:n]
# to calculate the similar matrix
# [C,T]
feat_1 = x[i] / torch.norm(x[i], 2, dim=-1, keepdim=True)
feat_2 = x[i + 1] / torch.norm(x[i + 1], 2, dim=-1, keepdim=True)
# [T,T]->[T,C]
sim_matrix = torch.mm(feat_1, feat_2.transpose(-1, -2))
recon_feat_1 = torch.mm(sim_matrix, feat_2)
recon_feat_2 = torch.mm(sim_matrix.t(), feat_1)
dis_1=torch.mean(atn1.detach()*torch.mean((recon_feat_1-feat_1)**2,dim=-1))
dis_2=torch.mean(atn2.detach()*torch.mean((recon_feat_2-feat_2)**2,dim=-1))
# gfeat1 = torch.mean(atn1.unsqueeze(-1) * feat_1,dim=0)
# recon_gfeat1 = torch.mean(atn1.unsqueeze(-1) * recon_feat_1,dim=0)
# gfeat2 = torch.mean(atn2.unsqueeze(-1) * feat_2,dim=0)
# recon_gfeat2 = torch.mean(atn2.unsqueeze(-1) * recon_feat_2,dim=0)
#
#
# cycle_loss += 0.5 * (torch.mean((gfeat1 - recon_gfeat1) ** 2) + torch.mean((gfeat2 - recon_gfeat2) ** 2))
cycle_loss+=0.5*(1-dis_1+1-dis_2)
return cycle_loss / n_similar
def distill_loss(pred_logits,target_logits,labels,device,args,is_back=False):
# select the groundtruth logits
if is_back:
labels = torch.cat(
(labels, torch.ones_like(labels[:, [0]])), dim=-1)
else:
labels = torch.cat(
(labels, torch.zeros_like(labels[:, [0]])), dim=-1)
labels_masks=labels.unsqueeze(1).repeat([1,pred_logits.shape[1],1]).bool()
target_output=torch.masked_select(torch.softmax(target_logits*args.lambd,dim=1).detach(),labels_masks)
pred_output=torch.masked_select(torch.softmax(pred_logits,dim=1),labels_masks)
log_mean_output = ((target_output + pred_output) / 2).log()
return (F.kl_div(log_mean_output, target_output) + F.kl_div(log_mean_output, pred_output)) / 2
def Contrastive_RandomSample(x, element_logits, seq_len, n_similar, labels, device,args):
''' x is the torch tensor of feature from the last layer of model of dimension (n_similar, n_element, n_feature),
element_logits should be torch tensor of dimension (n_similar, n_element, n_class)
seq_len should be numpy array of dimension (B,)
labels should be a numpy array of dimension (B, n_class) of 1 or 0 '''
sim_loss = 0.
n_tmp = 0.
_, n, c = element_logits.shape
for i in range(0, n_similar*2, 2):
atn1 = F.softmax(element_logits[i], dim=0)
atn2 = F.softmax(element_logits[i+1], dim=0)
n1 = torch.FloatTensor([np.maximum(n-1, 1)]).to(device)
n2 = torch.FloatTensor([np.maximum(n-1, 1)]).to(device)
Hf1 = torch.mm(torch.transpose(x[i], 1, 0), atn1) # (n_feature, n_class)
Hf2 = torch.mm(torch.transpose(x[i+1], 1, 0), atn2)
Lf1 = torch.mm(torch.transpose(x[i], 1, 0), (1 - atn1)/n1)
Lf2 = torch.mm(torch.transpose(x[i+1], 1, 0), (1 - atn2)/n2)
d1 = 1 - torch.sum(Hf1*Hf2, dim=0) / (torch.norm(Hf1, 2, dim=0) * torch.norm(Hf2, 2, dim=0)) # 1-similarity
d2 = 1 - torch.sum(Hf1*Lf2, dim=0) / (torch.norm(Hf1, 2, dim=0) * torch.norm(Lf2, 2, dim=0))
d3 = 1 - torch.sum(Hf2*Lf1, dim=0) / (torch.norm(Hf2, 2, dim=0) * torch.norm(Lf1, 2, dim=0))
sim_loss = sim_loss + 0.5*torch.sum(torch.max(d1-d2+0.5, torch.FloatTensor([0.]).to(device))*Variable(labels[i,:])*Variable(labels[i+1,:]))
sim_loss = sim_loss + 0.5*torch.sum(torch.max(d1-d3+0.5, torch.FloatTensor([0.]).to(device))*Variable(labels[i,:])*Variable(labels[i+1,:]))
# d1 = torch.sum(Hf1*Hf2, dim=0) / (torch.norm(Hf1, 2, dim=0) * torch.norm(Hf2, 2, dim=0)) # 1-similarity
# d2 = torch.sum(Hf1*Lf2, dim=0) / (torch.norm(Hf1, 2, dim=0) * torch.norm(Lf2, 2, dim=0))
# d3 = torch.sum(Hf2*Lf1, dim=0) / (torch.norm(Hf2, 2, dim=0) * torch.norm(Lf1, 2, dim=0))
# sim_loss = sim_loss + 0.5*torch.sum(torch.max(d2-d1+0.5, torch.FloatTensor([0.]).to(device))*Variable(labels[i,:])*Variable(labels[i+1,:]))
# sim_loss = sim_loss + 0.5*torch.sum(torch.max(d3-d1+0.5, torch.FloatTensor([0.]).to(device))*Variable(labels[i,:])*Variable(labels[i+1,:]))
n_tmp = n_tmp + torch.sum(labels[i,:]*labels[i+1,:])
sim_loss = sim_loss / n_tmp
return sim_loss
def Contrastive(x, element_logits, seq_len, n_similar, labels, device,args):
''' x is the torch tensor of feature from the last layer of model of dimension (n_similar, n_element, n_feature),
element_logits should be torch tensor of dimension (n_similar, n_element, n_class)
seq_len should be numpy array of dimension (B,)
labels should be a numpy array of dimension (B, n_class) of 1 or 0 '''
sim_loss = 0.
n_tmp = 0.
_, _, c = element_logits.shape
for i in range(0, n_similar*2, 2):
atn1 = F.softmax(element_logits[i][:seq_len[i]], dim=0)
atn2 = F.softmax(element_logits[i+1][:seq_len[i+1]], dim=0)
n1 = torch.FloatTensor([np.maximum(seq_len[i]-1, 1)]).to(device)
n2 = torch.FloatTensor([np.maximum(seq_len[i+1]-1, 1)]).to(device)
Hf1 = torch.mm(torch.transpose(x[i][:seq_len[i]], 1, 0), atn1) # (n_feature, n_class)
Hf2 = torch.mm(torch.transpose(x[i+1][:seq_len[i+1]], 1, 0), atn2)
Lf1 = torch.mm(torch.transpose(x[i][:seq_len[i]], 1, 0), (1 - atn1)/n1)
Lf2 = torch.mm(torch.transpose(x[i+1][:seq_len[i+1]], 1, 0), (1 - atn2)/n2)
d1 = 1 - torch.sum(Hf1*Hf2, dim=0) / (torch.norm(Hf1, 2, dim=0) * torch.norm(Hf2, 2, dim=0)) # 1-similarity
d2 = 1 - torch.sum(Hf1*Lf2, dim=0) / (torch.norm(Hf1, 2, dim=0) * torch.norm(Lf2, 2, dim=0))
d3 = 1 - torch.sum(Hf2*Lf1, dim=0) / (torch.norm(Hf2, 2, dim=0) * torch.norm(Lf1, 2, dim=0))
sim_loss = sim_loss + 0.5*torch.sum(torch.max(d1-d2+0.5, torch.FloatTensor([0.]).to(device))*Variable(labels[i,:])*Variable(labels[i+1,:]))
sim_loss = sim_loss + 0.5*torch.sum(torch.max(d1-d3+0.5, torch.FloatTensor([0.]).to(device))*Variable(labels[i,:])*Variable(labels[i+1,:]))
# d1 = torch.sum(Hf1*Hf2, dim=0) / (torch.norm(Hf1, 2, dim=0) * torch.norm(Hf2, 2, dim=0)) # 1-similarity
# d2 = torch.sum(Hf1*Lf2, dim=0) / (torch.norm(Hf1, 2, dim=0) * torch.norm(Lf2, 2, dim=0))
# d3 = torch.sum(Hf2*Lf1, dim=0) / (torch.norm(Hf2, 2, dim=0) * torch.norm(Lf1, 2, dim=0))
# sim_loss = sim_loss + 0.5*torch.sum(torch.max(d2-d1+0.5, torch.FloatTensor([0.]).to(device))*Variable(labels[i,:])*Variable(labels[i+1,:]))
# sim_loss = sim_loss + 0.5*torch.sum(torch.max(d3-d1+0.5, torch.FloatTensor([0.]).to(device))*Variable(labels[i,:])*Variable(labels[i+1,:]))
n_tmp = n_tmp + torch.sum(labels[i,:]*labels[i+1,:])
sim_loss = sim_loss / n_tmp
return sim_loss
def Contrastive_Sigmoid(x, element_logits, seq_len, n_similar, labels, device,args):
''' x is the torch tensor of feature from the last layer of model of dimension (n_similar, n_element, n_feature),
element_logits should be torch tensor of dimension (n_similar, n_element, n_class)
seq_len should be numpy array of dimension (B,)
labels should be a numpy array of dimension (B, n_class) of 1 or 0 '''
sim_loss = 0.
n_tmp = 0.
_, _, c = element_logits.shape
for i in range(0, n_similar*2, 2):
atn1 = F.sigmoid(element_logits[i][:seq_len[i]])
neg_atn1=(1-atn1)/torch.sum(1-atn1,dim=0,keepdim=True)
atn1=atn1/torch.sum(atn1,dim=0,keepdim=True)
atn2 = F.sigmoid(element_logits[i+1][:seq_len[i+1]])
neg_atn2=(1-atn2)/torch.sum(1-atn2,dim=0,keepdim=True)
atn2=atn2/torch.sum(atn2,dim=0,keepdim=True)
n1 = torch.FloatTensor([np.maximum(seq_len[i]-1, 1)]).to(device)
n2 = torch.FloatTensor([np.maximum(seq_len[i+1]-1, 1)]).to(device)
Hf1 = torch.mm(torch.transpose(x[i][:seq_len[i]], 1, 0), atn1) # (n_feature, n_class)
Hf2 = torch.mm(torch.transpose(x[i+1][:seq_len[i+1]], 1, 0), atn2)
Lf1 = torch.mm(torch.transpose(x[i][:seq_len[i]], 1, 0), neg_atn1)
Lf2 = torch.mm(torch.transpose(x[i+1][:seq_len[i+1]], 1, 0), neg_atn2)
d1 = 1 - torch.sum(Hf1*Hf2, dim=0) / (torch.norm(Hf1, 2, dim=0) * torch.norm(Hf2, 2, dim=0)) # 1-similarity
d2 = 1 - torch.sum(Hf1*Lf2, dim=0) / (torch.norm(Hf1, 2, dim=0) * torch.norm(Lf2, 2, dim=0))
d3 = 1 - torch.sum(Hf2*Lf1, dim=0) / (torch.norm(Hf2, 2, dim=0) * torch.norm(Lf1, 2, dim=0))
sim_loss = sim_loss + 0.5*torch.sum(torch.max(d1-d2+0.5, torch.FloatTensor([0.]).to(device))*Variable(labels[i,:])*Variable(labels[i+1,:]))
sim_loss = sim_loss + 0.5*torch.sum(torch.max(d1-d3+0.5, torch.FloatTensor([0.]).to(device))*Variable(labels[i,:])*Variable(labels[i+1,:]))
# d1 = torch.sum(Hf1*Hf2, dim=0) / (torch.norm(Hf1, 2, dim=0) * torch.norm(Hf2, 2, dim=0)) # 1-similarity
# d2 = torch.sum(Hf1*Lf2, dim=0) / (torch.norm(Hf1, 2, dim=0) * torch.norm(Lf2, 2, dim=0))
# d3 = torch.sum(Hf2*Lf1, dim=0) / (torch.norm(Hf2, 2, dim=0) * torch.norm(Lf1, 2, dim=0))
# sim_loss = sim_loss + 0.5*torch.sum(torch.max(d2-d1+0.5, torch.FloatTensor([0.]).to(device))*Variable(labels[i,:])*Variable(labels[i+1,:]))
# sim_loss = sim_loss + 0.5*torch.sum(torch.max(d3-d1+0.5, torch.FloatTensor([0.]).to(device))*Variable(labels[i,:])*Variable(labels[i+1,:]))
n_tmp = n_tmp + torch.sum(labels[i,:]*labels[i+1,:])
sim_loss = sim_loss / n_tmp
return sim_loss
def Contrastive_Batch(x, element_logits, seq_len, n_similar, labels, device,args):
sim_loss = 0.
n_tmp = 0.
_, _, c = element_logits.shape
positives=[]
negatives=[]
for i in range(n_similar*2):
atn=torch.softmax(element_logits[i][:seq_len[i]],dim=0)
n = torch.FloatTensor([np.maximum(seq_len[i] - 1, 1)]).to(device)
Hf = torch.mm(torch.transpose(x[i][:seq_len[i]], 1, 0), atn) # (n_feature, n_class)
Lf = torch.mm(torch.transpose(x[i][:seq_len[i]], 1, 0), (1 - atn) / n)
positives.append(Hf)
negatives.append(Lf)
positives=torch.stack(positives,dim=0)
negatives=torch.stack(negatives,dim=0)
# [B,C]
# to calculate the distance matrix between of each videos
PN_Dissim_Mat=1-torch.sum(positives.unsqueeze(1)*negatives.unsqueeze(0),dim=2)/(torch.norm(positives.unsqueeze(1),p=2,dim=2)*torch.norm(negatives.unsqueeze(0),p=2,dim=2))
PP_Dissim_Mat=1-torch.sum(positives.unsqueeze(1)*positives.unsqueeze(0),dim=2)/(torch.norm(positives.unsqueeze(1),p=2,dim=2)*torch.norm(positives.unsqueeze(0),p=2,dim=2))
for i in range(0,n_similar*2,2):
neg_dis_vec_1=PN_Dissim_Mat[i]
neg_dis_vec_2=PN_Dissim_Mat[i+1]
pos_dis_vec_1=PP_Dissim_Mat[i]
pos_dis_vec_2=PP_Dissim_Mat[i+1]
pos_dis=pos_dis_vec_1[i]
sim_loss=sim_loss + 0.25 * torch.sum(torch.relu(torch.max((-pos_dis_vec_1+pos_dis.unsqueeze(0)+0.5)* Variable(labels[i, :]) * Variable(
labels[i + 1, :]),dim=0)[0]))
sim_loss=sim_loss + 0.25 * torch.sum(torch.relu(torch.max((-pos_dis_vec_2+pos_dis.unsqueeze(0)+0.5)* Variable(labels[i, :]) * Variable(
labels[i + 1, :]),dim=0)[0]))
# Hf1=positives[i]
# Hf2=positives[i+1]
#
# pos_dis=1-torch.sum(Hf1*Hf2,dim=0)/(torch.norm(Hf1,2,dim=0)*torch.norm(Hf2,2,dim=0))
sim_loss = sim_loss + 0.25 * torch.sum(torch.relu(torch.max((-neg_dis_vec_1+pos_dis.unsqueeze(0)+0.5)* Variable(labels[i, :]) * Variable(
labels[i + 1, :]),dim=0)[0]))
sim_loss = sim_loss + 0.25 * torch.sum(torch.relu(torch.max((-neg_dis_vec_2+pos_dis.unsqueeze(0)+0.5)* Variable(labels[i, :]) * Variable(
labels[i + 1, :]),dim=0)[0]))
# sim_loss=sim_loss+0.5*torch.sum(torch.relu(pos_dis-torch.max(neg_dis_vec_1,dim=0)[0]+0.5) * Variable(labels[i, :]) * Variable(
# labels[i + 1, :]))
# sim_loss=sim_loss+0.5*torch.sum(torch.relu(pos_dis-torch.max(neg_dis_vec_2,dim=0)[0]+0.5)* Variable(labels[i, :]) * Variable(
# labels[i + 1, :]))
n_tmp = n_tmp + torch.sum(labels[i, :] * labels[i + 1, :])
sim_loss = sim_loss / n_tmp
return sim_loss
def Contrastive_HT(x, element_logits, seq_len, n_similar, labels, device,args):
''' x is the torch tensor of feature from the last layer of model of dimension (n_similar, n_element, n_feature),
element_logits should be torch tensor of dimension (n_similar, n_element, n_class)
seq_len should be numpy array of dimension (B,)
labels should be a numpy array of dimension (B, n_class) of 1 or 0 '''
'''Hard tanh is used in computing the attention'''
sim_loss = 0.
n_tmp = 0.
_, _, c = element_logits.shape
for i in range(0, n_similar*2, 2):
atn1 = F.softmax(F.hardtanh(element_logits[i][:seq_len[i]],-args.clip,args.clip), dim=0)
atn2 = F.softmax(F.hardtanh(element_logits[i+1][:seq_len[i+1]],-args.clip,args.clip), dim=0)
n1 = torch.FloatTensor([np.maximum(seq_len[i]-1, 1)]).to(device)
n2 = torch.FloatTensor([np.maximum(seq_len[i+1]-1, 1)]).to(device)
Hf1 = torch.mm(torch.transpose(x[i][:seq_len[i]], 1, 0), atn1) # (n_feature, n_class)
Hf2 = torch.mm(torch.transpose(x[i+1][:seq_len[i+1]], 1, 0), atn2)
Lf1 = torch.mm(torch.transpose(x[i][:seq_len[i]], 1, 0), (1 - atn1)/n1)
Lf2 = torch.mm(torch.transpose(x[i+1][:seq_len[i+1]], 1, 0), (1 - atn2)/n2)
d1 = 1 - torch.sum(Hf1*Hf2, dim=0) / (torch.norm(Hf1, 2, dim=0) * torch.norm(Hf2, 2, dim=0)) # 1-similarity
d2 = 1 - torch.sum(Hf1*Lf2, dim=0) / (torch.norm(Hf1, 2, dim=0) * torch.norm(Lf2, 2, dim=0))
d3 = 1 - torch.sum(Hf2*Lf1, dim=0) / (torch.norm(Hf2, 2, dim=0) * torch.norm(Lf1, 2, dim=0))
sim_loss = sim_loss + 0.5*torch.sum(torch.max(d1-d2+0.5, torch.FloatTensor([0.]).to(device))*Variable(labels[i,:])*Variable(labels[i+1,:]))
sim_loss = sim_loss + 0.5*torch.sum(torch.max(d1-d3+0.5, torch.FloatTensor([0.]).to(device))*Variable(labels[i,:])*Variable(labels[i+1,:]))
# d1 = torch.sum(Hf1*Hf2, dim=0) / (torch.norm(Hf1, 2, dim=0) * torch.norm(Hf2, 2, dim=0)) # 1-similarity
# d2 = torch.sum(Hf1*Lf2, dim=0) / (torch.norm(Hf1, 2, dim=0) * torch.norm(Lf2, 2, dim=0))
# d3 = torch.sum(Hf2*Lf1, dim=0) / (torch.norm(Hf2, 2, dim=0) * torch.norm(Lf1, 2, dim=0))
# sim_loss = sim_loss + 0.5*torch.sum(torch.max(d2-d1+0.5, torch.FloatTensor([0.]).to(device))*Variable(labels[i,:])*Variable(labels[i+1,:]))
# sim_loss = sim_loss + 0.5*torch.sum(torch.max(d3-d1+0.5, torch.FloatTensor([0.]).to(device))*Variable(labels[i,:])*Variable(labels[i+1,:]))
n_tmp = n_tmp + torch.sum(labels[i,:]*labels[i+1,:])
sim_loss = sim_loss / n_tmp
return sim_loss
def Contrastive_TopK(x, element_logits, seq_len, n_similar, labels, device,args):
''' x is the torch tensor of feature from the last layer of model of dimension (n_similar, n_element, n_feature),
element_logits should be torch tensor of dimension (n_similar, n_element, n_class)
seq_len should be numpy array of dimension (B,)
labels should be a numpy array of dimension (B, n_class) of 1 or 0 '''
'''Hard tanh is used in computing the attention'''
sim_loss = 0.
n_tmp = 0.
_, _, c = element_logits.shape
for i in range(0, n_similar*2, 2):
# atn1 = F.softmax(F.hardtanh(element_logits[i][:seq_len[i]],-args.clip,args.clip), dim=0)
# atn2 = F.softmax(F.hardtanh(element_logits[i+1][:seq_len[i+1]],-args.clip,args.clip), dim=0)
# select topk to construct a attention
atn1=torch.sigmoid(element_logits[i][:seq_len[i]])
atn2=torch.sigmoid(element_logits[i+1][:seq_len[i+1]])
n1 = torch.FloatTensor([np.maximum(seq_len[i]-1, 1)]).to(device)
n2 = torch.FloatTensor([np.maximum(seq_len[i+1]-1, 1)]).to(device)
Hf1 = torch.mm(torch.transpose(x[i][:seq_len[i]], 1, 0), atn1) # (n_feature, n_class)
Hf2 = torch.mm(torch.transpose(x[i+1][:seq_len[i+1]], 1, 0), atn2)
Lf1 = torch.mm(torch.transpose(x[i][:seq_len[i]], 1, 0), (1 - atn1)/n1)
Lf2 = torch.mm(torch.transpose(x[i+1][:seq_len[i+1]], 1, 0), (1 - atn2)/n2)
d1 = 1 - torch.sum(Hf1*Hf2, dim=0) / (torch.norm(Hf1, 2, dim=0) * torch.norm(Hf2, 2, dim=0)) # 1-similarity
d2 = 1 - torch.sum(Hf1*Lf2, dim=0) / (torch.norm(Hf1, 2, dim=0) * torch.norm(Lf2, 2, dim=0))
d3 = 1 - torch.sum(Hf2*Lf1, dim=0) / (torch.norm(Hf2, 2, dim=0) * torch.norm(Lf1, 2, dim=0))
sim_loss = sim_loss + 0.5*torch.sum(torch.max(d1-d2+0.5, torch.FloatTensor([0.]).to(device))*Variable(labels[i,:])*Variable(labels[i+1,:]))
sim_loss = sim_loss + 0.5*torch.sum(torch.max(d1-d3+0.5, torch.FloatTensor([0.]).to(device))*Variable(labels[i,:])*Variable(labels[i+1,:]))
# d1 = torch.sum(Hf1*Hf2, dim=0) / (torch.norm(Hf1, 2, dim=0) * torch.norm(Hf2, 2, dim=0)) # 1-similarity
# d2 = torch.sum(Hf1*Lf2, dim=0) / (torch.norm(Hf1, 2, dim=0) * torch.norm(Lf2, 2, dim=0))
# d3 = torch.sum(Hf2*Lf1, dim=0) / (torch.norm(Hf2, 2, dim=0) * torch.norm(Lf1, 2, dim=0))
# sim_loss = sim_loss + 0.5*torch.sum(torch.max(d2-d1+0.5, torch.FloatTensor([0.]).to(device))*Variable(labels[i,:])*Variable(labels[i+1,:]))
# sim_loss = sim_loss + 0.5*torch.sum(torch.max(d3-d1+0.5, torch.FloatTensor([0.]).to(device))*Variable(labels[i,:])*Variable(labels[i+1,:]))
n_tmp = n_tmp + torch.sum(labels[i,:]*labels[i+1,:])
sim_loss = sim_loss / n_tmp
return sim_loss
def Inner_Outer_Loss(element_logits,seq_len,batch_size,labels,device,args,threshold=0.5,):
# use as a regularization in training, inner similar, outer dissimilar
io_loss=0
for i in range(batch_size):
# [N,C]
scores=torch.softmax(element_logits[i][:seq_len[i]],dim=-1)
# to select the gt_class (inner and outer should be clear different
label=labels[i]
# [C]->[]
label_mask=label.unsqueeze(-1).repeat(1,seq_len[i]).bool().permute([1,0])
selected_scores=torch.masked_select(scores,label_mask)
vid_pred=[]
for scores in selected_scores:
# [N,X]
thre=torch.max(scores)[0]-(torch.max(scores)[0]-torch.min(scores)[0])*threshold
# to generate segments
vid_pred=torch.cat([np.zeros])
selected_scores=torch.ge(selected_scores,threshold)
def rankingloss1(element_logits, seq_len, batch_size, labels, device,args,pair_id):
b,n,c = element_logits.shape
element_prob = F.softmax(element_logits,-1)
# bg_prob = element_prob[:,:,-1].unsqueeze(-1)
loss = 0
k = np.ceil(seq_len/8).astype('int32')
for i in range(args.num_similar):
Pos = [torch.topk(element_logits[i*args.similar_size+k][:seq_len[i*args.similar_size+k],pair_id[i]],k=int(k[i*args.similar_size+k]))[0] for k in range(args.similar_size)]
Neg = [torch.max(element_logits[(i+args.num_similar)*args.similar_size+k][:seq_len[(i+args.num_similar)*args.similar_size+k],pair_id[i]]) for k in range(args.similar_size)]
pdb.set_trace()
min_pos = torch.min(Pos)
max_neg = torch.max(Neg)
s_loss = F.relu(max_neg-min_pos+1,0)
loss += s_loss
loss/=args.num_similar
return loss
def rankingloss(element_logits, seq_len, batch_size, labels, device,args,pair_id):
b,n,c = element_logits.shape
element_prob = F.softmax(element_logits,-1)
# bg_prob = element_prob[:,:,-1].unsqueeze(-1)
loss = 0
for i in range(args.num_similar):
Pos = torch.stack([torch.max(element_prob[i*args.similar_size+k][:seq_len[i*args.similar_size+k],pair_id[i]]) for k in range(args.similar_size)])
Neg = torch.stack([torch.max(element_prob[(i+args.num_similar)*args.similar_size+k][:seq_len[(i+args.num_similar)*args.similar_size+k],pair_id[i]]) for k in range(args.similar_size)])
min_pos = torch.min(Pos)
max_neg = torch.max(Neg)
s_loss = F.relu(max_neg-min_pos+0.5,0)
loss += s_loss
loss/=args.num_similar
return loss
def bg_contraint(element_logits, seq_len, batch_size, labels, device,args):
b,n,c = element_logits.shape
element_prob = F.softmax(element_logits,-1)
bg_prob = element_prob[:,:,-1].unsqueeze(-1)
loss = 0
for i in range(b):
bgs = bg_prob[i,:seq_len[i]].sum()
gt_nums = torch.tensor(args.bg_prob*seq_len[i],requires_grad=False).float()
loss += (torch.pow(bgs-gt_nums,2)/seq_len[i])
loss/=b
return loss
# entropy =
def self_bg_supervised(element_logits, seq_len, batch_size, labels, device):
b,n,c = element_logits.shape
element_prob = F.softmax(element_logits,-1)
act_prob = F.softmax(element_logits[:,:,:-1],-1)
entropy = -torch.sum(act_prob*torch.log(act_prob),dim=-1,keepdim=True)
Max_entropy = -np.log(1/20)
bg_weight = 1-entropy/Max_entropy
bg_prob = element_prob[:,:,-1].unsqueeze(-1)
loss = 0
for i in range(b):
loss+=torch.mean(torch.pow((bg_prob[:seq_len[i]]-bg_weight[:seq_len[i]]),2))
loss/=b
return loss
# entropy =
def NegLoss2(element_logits, seq_len, batch_size, labels, device):
b,n,c = element_logits.shape
nagetive_loss = 0
for i in range(b):
s_logits = element_logits[i][:seq_len[i]]
s_label = labels[i]
neg_label = (s_label==0).float()
s_prob = F.sigmoid(s_logits)
# selected_prob = s_prob[:,neg_idx]
inverse_prob = 1- s_prob
s_loss = -(neg_label*torch.log(inverse_prob)).sum(1).mean()
nagetive_loss+=s_loss
nagetive_loss/=b
return nagetive_loss
def NegLoss1(element_logits, seq_len, batch_size, labels, device):
b,n,c = element_logits.shape
nagetive_loss = 0
for i in range(b):
s_logits = element_logits[i][:seq_len[i]]
s_label = labels[i]
pdb.set_trace()
neg_label = 1-s_label
s_prob = F.softmax(s_logits,-1)
inverse_prob = 1- s_prob
s_loss = -(neg_label*torch.log(inverse_prob)).sum(1).mean()
nagetive_loss+=s_loss
nagetive_loss/=b
return nagetive_loss
def NegLoss_RandomSample(element_logits, seq_len, batch_size, labels, device):
b,n,c = element_logits.shape
negative_loss = 0
for i in range(b):
s_logits = element_logits[i]
s_label = labels[i]
neg_idx = s_label==0
s_prob = F.sigmoid(s_logits)
selected_prob = s_prob[:,neg_idx]
inverse_prob = 1 - selected_prob
s_loss = -torch.log(inverse_prob+1e-8).sum(1).mean()
negative_loss+=s_loss
negative_loss/=b
return negative_loss
def NegLoss(element_logits, seq_len, batch_size, labels, device):
b,n,c = element_logits.shape
negative_loss = 0
for i in range(b):
s_logits = element_logits[i][:seq_len[i]]
s_label = labels[i]
neg_idx = s_label==0
s_prob = F.sigmoid(s_logits)
selected_prob = s_prob[:,neg_idx]
inverse_prob = 1 - selected_prob
s_loss = -torch.log(inverse_prob+1e-8).sum(1).mean()
negative_loss+=s_loss
negative_loss/=b
return negative_loss
# =========================== Conv ATT Loss ================================
def NegLoss_Vid(element_logits,seq_len,batch_size,labels,device,args):
negloss=0
element_logits=element_logits[0]
b=element_logits.shape[0]
#[B,C]
for i in range(b):
s_label = labels[i]
neg_idx = s_label == 0
s_prob=torch.softmax(element_logits[i],dim=-1)
selected_prob = s_prob[neg_idx]
inverse_prob = 1 - selected_prob
s_loss = -torch.log(inverse_prob).sum()
negloss+=s_loss
negloss/=b
return negloss
def NegLoss_Clip(element_logits,seq_len,batch_size,labels,device,args):
element_logits=element_logits[-1]
return NegLoss(element_logits,seq_len,batch_size,labels,device)
def SpaLoss(element_logits,seq_len,batch_size,labels,devices,args):
element_logits=element_logits[1]
return torch.mean(element_logits)
def GapLoss(element_logits,seq_len,batch_size,labels,devices,args):
gaploss=0
element_logits=element_logits[1]
for i in range(seq_len.shape[0]):
att=element_logits[i][:,:seq_len[i]].squeeze(0)
l=max(1,int(seq_len[i]/args.s))
# selected_att=np.random.choice(att,l)
att=torch.sort(att,dim=0)[0]
gaploss+=torch.relu(att[:l].mean()-att[-l:].mean()+1)
gaploss=gaploss/seq_len.shape[0]
return gaploss
def MILL_Vid(element_logits,seq_len,batch_size,labels,device,args):
element_logits=element_logits[0]
# labels is with shape [B,C]
millloss=-torch.mean(torch.sum(labels*F.log_softmax(element_logits,dim=1),dim=1),dim=0)
return millloss
def MILL_Clip(element_logits,seq_len,batch_size,labels,device,args):
element_logits=element_logits[-1]
return MILL(element_logits,seq_len,batch_size,labels,device,args)
def Contractive_Att(x,att_scores,seq_len,n_similar,labels,device,args):
sim_loss=0
for i in range(0,n_similar*2,2):
# []
Hf1 = torch.sum((x[i]*att_scores[i])[:seq_len[i]],dim=0)/torch.sum(att_scores[i][:seq_len[i]])
Hf2 = torch.sum((x[i+1]*att_scores[i+1])[:seq_len[i+1]],dim=0)/torch.sum(att_scores[i+1][:seq_len[i+1]])
Lf1 = torch.sum((x[i]*(1-att_scores[i]))[:seq_len[i]],dim=0)/torch.sum((1-att_scores[i])[:seq_len[i]])
Lf2 = torch.sum((x[i+1]*(1-att_scores[i+1]))[:seq_len[i+1]],dim=0)/torch.sum((1-att_scores[i+1])[:seq_len[i+1]])
d1=torch.sum(Hf1*Hf2)/(torch.norm(Hf1,p=2,dim=0)*torch.norm(Hf2,p=2,dim=0))
d2=torch.sum(Hf1*Lf1)/(torch.norm(Hf1,p=2,dim=0)*torch.norm(Lf1,p=2,dim=0))
d3=torch.sum(Hf1*Lf2)/(torch.norm(Hf1,p=2,dim=0)*torch.norm(Lf2,p=2,dim=0))
sim_loss+=0.5*torch.relu(d1-d2+0.5)
sim_loss+=0.5*torch.relu(d1-d3+0.5)
return sim_loss/n_similar
def Contractive_Vid(x, element_logits, seq_len, n_similar, labels, device,args):
''' x is the torch tensor of feature from the last layer of model of dimension (n_similar, n_element, n_feature),
element_logits should be torch tensor of dimension (n_similar, n_element, n_class)
seq_len should be numpy array of dimension (B,)
labels should be a numpy array of dimension (B, n_class) of 1 or 0 '''
sim_loss = 0.
n_tmp = 0.
_,fa,fb=x
# _,att_logits=element_logits
# _, _, c = element_logits.shape
for i in range(0, n_similar*2, 2):
# [1,C]
Hf1=fa[i]
Hf2=fa[i+1]
Lf1=fb[i]
Lf2=fb[i+1]
d1 = 1 - torch.sum(Hf1*Hf2, dim=0) / (torch.norm(Hf1, 2, dim=0) * torch.norm(Hf2, 2, dim=0)) # 1-similarity
d2 = 1 - torch.sum(Hf1*Lf2, dim=0) / (torch.norm(Hf1, 2, dim=0) * torch.norm(Lf2, 2, dim=0))
d3 = 1 - torch.sum(Hf2*Lf1, dim=0) / (torch.norm(Hf2, 2, dim=0) * torch.norm(Lf1, 2, dim=0))
sim_loss = sim_loss + 0.5*torch.relu(d1-d2+0.5)*torch.sum(Variable(labels[i,:])*Variable(labels[i+1,:]))/(torch.sum(labels[i,:])*torch.sum(labels[i+1,:]))
sim_loss = sim_loss + 0.5*torch.relu(d1-d3+0.5)*torch.sum(Variable(labels[i,:])*Variable(labels[i+1,:]))/(torch.sum(labels[i,:])*torch.sum(labels[i+1,:]))
n_tmp = n_tmp + torch.sum(labels[i,:]*labels[i+1,:])
sim_loss = sim_loss / n_tmp
return sim_loss
def Contractive_Clip(x,element_logits, seq_len, n_similar, labels, device,args):
feat_embed,_,_=x
_,_,clip_cls_logits=element_logits
return Contrastive(feat_embed,clip_cls_logits,seq_len,n_similar,labels,device,args)
# =========================================================================
# for asymmetric fusion
def MSE_Loss(a_logits,b_logits,seq_len,batch_size,labels,device,args):
mse_loss=0
for i,sl in enumerate(seq_len):
mse_loss+=torch.mean((a_logits[i]-b_logits[i])**2[:,:sl])
return mse_loss/seq_len.shape[0]
# ========================================================================
def MILL2(element_logits, seq_len, batch_size, labels, device, args):
''' element_logits should be torch tensor of dimension (B, n_element, n_class),
k should be numpy array of dimension (B,) indicating the top k locations to average over,
labels should be a numpy array of dimension (B, n_class) of 1 or 0
return is a torch tensor of dimension (B, n_class) '''
k = np.ceil(seq_len/args.k).astype('int32')
b, n_class = labels.shape
# labels = labels / torch.sum(labels, dim=1, keepdim=True)
instance_logits = torch.zeros(0).to(device)
element_prob = F.sigmoid(element_logits)
for i in range(element_logits.shape[0]):
tmp, _ = torch.topk(element_prob[i][:seq_len[i]], k=int(k[i]), dim=0)
instance_logits = torch.cat([instance_logits, torch.mean(tmp, 0, keepdim=True)], dim=0)
milloss = torch.norm(instance_logits-labels)
# milloss = -torch.mean(torch.sum(labels * F.log_softmax(instance_logits, dim=1), dim=1), dim=0)
return milloss
def MILL1(element_logits, seq_len, batch_size, labels, device,args):
k = np.ceil(seq_len / args.topk).astype("int32")
eps = 1e-8
loss = 0
instance_logits = torch.zeros(0).to(device)
# element_logits = F.hardtanh(element_logits, -args.clip, args.clip)
for i in range(element_logits.shape[0]):
peaks = n_peak_find(
element_logits[i][: seq_len[i]], args, win_size=int(args.topk)
)
instance_logits = torch.cat([instance_logits, torch.mean(peaks, 0, keepdim=True)], dim=0)
milloss = -torch.mean(torch.sum(Variable(labels) * F.log_softmax(instance_logits, dim=1), dim=1), dim=0)
return milloss
def MILL(element_logits, seq_len, batch_size, labels, device, args):
''' element_logits should be torch tensor of dimension (B, n_element, n_class),
k should be numpy array of dimension (B,) indicating the top k locations to average over,
labels should be a numpy array of dimension (B, n_class) of 1 or 0
return is a torch tensor of dimension (B, n_class) '''
k = np.ceil(seq_len/args.k).astype('int32')
b, n_class = labels.shape
labels = labels / torch.sum(labels, dim=1, keepdim=True)
instance_logits = torch.zeros(0).to(device)
for i in range(element_logits.shape[0]):
tmp, _ = torch.topk(element_logits[i][:seq_len[i]], k=int(k[i]), dim=0)
instance_logits = torch.cat([instance_logits, torch.mean(tmp, 0, keepdim=True)], dim=0)
milloss = -torch.mean(torch.sum(labels * F.log_softmax(instance_logits, dim=1), dim=1), dim=0)
return milloss
# not work well
def MILL_Con(element_logits, seq_len, batch_size, labels, device, args):
''' element_logits should be torch tensor of dimension (B, n_element, n_class),
k should be numpy array of dimension (B,) indicating the top k locations to average over,
labels should be a numpy array of dimension (B, n_class) of 1 or 0
return is a torch tensor of dimension (B, n_class) '''