-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathISNetFunctionsZe.py
3229 lines (2735 loc) · 131 KB
/
ISNetFunctionsZe.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 as nn
import globalsZe as globals
from collections import OrderedDict
from typing import Dict, Callable
import copy
import random
def GlobalWeightedRankPooling(x,d=0.9,descending=True,oneD=False,rank=True):
#GWRP, performs weighted average in spatial dimensions https://arxiv.org/abs/1809.08264
#x: input
#d: rate of weights' exponential decay
#descending: if true elements are ordered in descending order before weighting, if false, in ascending order
#oneD: set to True only for aggregating LDS loss, aggregates one-dimensional vectors instead of
#2D objects
#rank: allows ordering of elements. If False, elements are aggregated in the provided order
if len(x.shape)==5 and not oneD:#2D pool
x=x.view(x.shape[0],x.shape[1],x.shape[2],x.shape[3]*x.shape[4])
if rank:
x,_=torch.sort(x,dim=-1,descending=descending)
weights=torch.tensor([d ** i for i in range(x.shape[-1])]).type_as(x)
while len(weights.shape)<len(x.shape):
weights=weights.unsqueeze(0)
x=torch.mul(x,weights)
x=x.sum(-1)/weights.sum(-1)
return x
def LRPLossCEValleysGWRP (heatmap, mask, cut=1, cut2=25, reduction='mean',
norm='absRoIMean', A=1, B=3, E=1,d=0.9,
eps=1e-10,rule='e',tuneCut=False,
channelGWRP=1.0,
alternativeForeground='L2'):
#ISNet Loss Function
#heatmap: heatmaps to be optimized
#mask: foreground segmentation masks, should be 1 in foreground and 0 in background
#cut1 and cut2: C1 and C2 parameters, should define natural range of total absolute heatmap relevance
#reduction: how the loss is reduced
#norm: 'absRoIMean' uses standard ISNet loss, 'RoIMean' applies the background loss normalization step before the absolute value operation
#A and B: w1 and w2 parameters, weights for the background and foreground loss
#E: parameter of the background loss activation x/(x+E)
#d: GWRP exponential decay parameter
#channelGWRP: exponential decay of 1D GWRP to aggregate heatmap losses of each channel in LDS, set to 1 in paper (simple mean)
#alternativeForeground='hybrid' adds the loss modification in the paper Faster ISNet for Background Bias Mitigation on Deep Neural Networks, alternativeForeground='L2' uses the standard (original) loss
if len(heatmap.shape)!=5:
raise ValueError('Incorrect heatmap format, correct is: batch, classes, channels, wdith, lenth')
if isinstance(alternativeForeground, bool):#backward compat
if alternativeForeground:
alternativeForeground='L1'
else:
alternativeForeground='L2'
if isinstance(norm, bool):#backward compat
if norm:
norm='absRoIMean'
else:
norm='none'
batchSize=heatmap.shape[0]
classesSize=heatmap.shape[1]
channels=heatmap.shape[2]
length=heatmap.shape[-1]
width=heatmap.shape[-2]
#create copies to avoid changing argument variables
cut=copy.deepcopy(cut)
cut2=copy.deepcopy(cut2)
mask=mask.clone()
heatmap=heatmap.clone()
#resize masks to match heatmap shape if necessary
if (mask.shape[-2]!=width or mask.shape[-1]!=length):
mask=torch.nn.functional.adaptive_avg_pool2d(mask, [heatmap.shape[-2],heatmap.shape[-1]])
#ensure binary:
mask=torch.where(mask==0.0,0.0,1.0)#conservative approach, only minimize attention to regions we have no foreground
if not torch.equal((torch.where(mask==0.0,1.0,0.0)+torch.where(mask==1.0,1.0,0.0)),
torch.ones(mask.shape).type_as(mask)):
non_binary_elements = mask[(mask != 0) & (mask != 1)]
print("Non-binary elements:", non_binary_elements)
raise ValueError('Non binary mask')
if len(mask.shape)!=len(heatmap.shape):
mask=mask.unsqueeze(1).repeat(1,classesSize,1,1,1)
if mask.shape[2]!=channels:
mask=mask[:,:,0,:,:].unsqueeze(2).repeat(1,1,channels,1,1)
if mask.sum().item()==0:
print('Zero mask')
#inverse mask:
Imask=torch.ones(mask.shape).type_as(mask)-mask
with torch.cuda.amp.autocast(enabled=False):
heatmap=heatmap.float()
mask=mask.float()
Imask=Imask.float()
#substitute nans if necessary:
if torch.isnan(heatmap).any():
print('nan 0')
if torch.isinf(heatmap).any():
print('inf 0')
RoIMean=torch.sum(torch.nan_to_num(heatmap,posinf=0.0,neginf=0.0)*mask)/(torch.sum(mask)+eps)
#print(RoIMean)
heatmap=torch.nan_to_num(heatmap,nan=RoIMean.item(),
posinf=torch.max(torch.nan_to_num(heatmap,posinf=0,neginf=0)).item(),
neginf=torch.min(torch.nan_to_num(heatmap,posinf=0,neginf=0)).item())
#save non-normalized heatmap:
heatmapRaw=torch.abs(heatmap).clone()
if A!=0:
if torch.isnan(heatmap).any():
print('nan 1')
if torch.isinf(heatmap).any():
print('inf 1')
#normalize heatmap:
if norm=='absRoIMean':
#abs:
heatmap=torch.abs(heatmap)
#roi mean value:
denom=torch.sum(heatmap*mask, dim=(-1,-2,-3),
keepdim=True)/(torch.sum(mask,dim=(-1,-2,-3),keepdim=True)+eps)
if torch.isnan(denom).any():#nan in denom
print('nan 0.5')
if torch.isinf(denom).any():
print('inf 0.5')
heatmap=heatmap/(denom+eps)
#print('heatmap:',heatmap.shape, 'denom', denom.shape)
elif norm=='RoIMean':
#print('running new norm')
#roi mean value (no abs):
denom=torch.sum(heatmap*mask, dim=(-1,-2,-3),
keepdim=True)/(torch.sum(mask,dim=(-1,-2,-3),keepdim=True)+eps)
if torch.isnan(denom).any():#nan in denom
print('nan 0.5')
if torch.isinf(denom).any():
print('inf 0.5')
heatmap=heatmap/(denom+eps)
#abs:
heatmap=torch.abs(heatmap)
elif norm=='none':
#abs:
heatmap=torch.abs(heatmap)
heatmap=heatmap*(channels*length*width)
else:
raise ValueError('Unrcognized norm')
if torch.isnan(heatmap).any():
print('nan 2')
if torch.isinf(heatmap).any():
print('inf 2')
#Background:
heatmapBKG=torch.mul(heatmap,Imask)
heatmapBKG=GlobalWeightedRankPooling(heatmapBKG,d=d)
#activation:
heatmapBKG=heatmapBKG/(heatmapBKG+E)
#cross entropy (pixel-wise):
heatmapBKG=torch.clamp(heatmapBKG,max=1-1e-7)
loss=-torch.log(torch.ones(heatmapBKG.shape).type_as(heatmapBKG)-heatmapBKG)
if channelGWRP==1.0:
loss=torch.mean(loss,dim=(-1,-2))#channels and classes mean
else:#GWRP over channel loss, penalizing more channels with with background attention
loss=GlobalWeightedRankPooling(loss,d=channelGWRP,oneD=True)#reduce over channel dimension
loss=torch.mean(loss,dim=-1)#reduce over classes dimension
if torch.isnan(loss).any():
print('nan 3')
if torch.isinf(loss).any():#here
print('inf 3')
if (not torch.isinf(heatmapBKG).any()):
print('inf by log')
else:
loss=0
if tuneCut: #use for finding ideal cut values
if (reduction=='sum'):
loss=torch.sum(loss)
elif (reduction=='mean'):
loss=torch.mean(loss)
elif (reduction=='none'):
pass
else:
raise ValueError('reduction should be none, mean or sum')
#return loss,(heatmapRaw*mask).sum(dim=(-1,-2,-3))
return loss,(heatmapRaw).sum(dim=(-1,-2,-3))
if B!=0:
#avoid foreground values too low or too high:
heatmapF=torch.mul(heatmapRaw,mask).sum(dim=(-1,-2,-3))
#divide heatmapF by cut, same as dividing square losses by cut**2, but avoids underflow
if (rule=='e' and isinstance(cut, list)):
cut=cut[0]
cut2=cut2[0]
#Set targets
if rule=='z+e':
#for z+e, the z+ and the e heatmaps can be at different scales,
#provide cut0=[cut0 for LRP-z+,cut0 for LRP-e]
#and cut2=[cut2 for LRP-z+,cut2 for LRP-e]
shape=(heatmapF.shape[0],int(heatmapF.shape[1]/2))
target=torch.cat((cut[0]*torch.ones(shape).type_as(heatmapF),
cut[1]*torch.ones(shape).type_as(heatmapF)),dim=1)
target2=torch.cat((cut2[0]*torch.ones(shape).type_as(heatmapF),
cut2[1]*torch.ones(shape).type_as(heatmapF)),dim=1)
else:
target=cut*torch.ones(heatmapF.shape).type_as(heatmapF)
target2=cut2*torch.ones(heatmapF.shape).type_as(heatmapF)
#print(heatmapF)
#left side: lossF
#target/target=1
lossF=nn.functional.mse_loss(torch.clamp(heatmapF/target,min=None,
max=torch.ones(target.shape).type_as(target)),
torch.ones(target.shape).type_as(target),reduction='none')
lossF=torch.mean(lossF,dim=-1)#classes mean
#right side: lossF2
if alternativeForeground=='L2':
lossF2=nn.functional.mse_loss(torch.clamp(heatmapF/target,
min=target2/target,max=None),
target2/target,reduction='none')
elif alternativeForeground=='L1':
#uses not scaled L1 loss in the right side of the foreground loss
lossF2=nn.functional.l1_loss(torch.clamp(heatmapF,min=target2,max=None),
target2,reduction='none')
elif alternativeForeground=='hybrid':
#symetric L2 loss around [C1,C2] range, then L1 loss
#mask:what elements are higher than C1+C2?
high=torch.where(heatmapF.detach()>(target+target2),1.0,0.0).type_as(heatmapF)#use L1
low=1.0-high#use L2
L2=nn.functional.mse_loss(torch.clamp(low*(heatmapF/target),
min=target2/target,max=None),
target2/target,reduction='none')
L1=nn.functional.l1_loss(torch.clamp(high*heatmapF,min=(target2+target),max=None),
(target2+target),reduction='none')
L1=L1+torch.ones(target.shape).type_as(target)
lossF2=L2*low+L1*high
else:
raise ValueError('Unrecognized alternativeForeground')
lossF2=torch.mean(lossF2,dim=-1)#classes mean
lossF=lossF+lossF2
loss=A*loss+B*lossF
if torch.isnan(loss).any():
print('nan 4')
if torch.isinf(loss).any():
print('inf 4')
#reduction of batch dimension
if (reduction=='sum'):
loss=torch.sum(loss)
elif (reduction=='mean'):
loss=torch.mean(loss)
elif (reduction=='none'):
pass
else:
raise ValueError('reduction should be none, mean or sum')
return loss
def stabilizer(aK,e,sign=None):
#Used for LRP-e, returns terms sign(ak)*e
#ak: values to stabilize
#e: LRP-e term
#sign: 1, -1 or None
if(sign is None):
signs=torch.sign(aK)
#zeros as positives
signs[signs==0]=1
signs=signs*e
else:
signs=sign*torch.ones(aK.shape).type_as(aK)*e
return signs
def PosNeg(x):
#splits positive and negative parts of a signal x
xp=torch.max(x,torch.zeros(x.shape).type_as(x))
xn=torch.min(x,torch.zeros(x.shape).type_as(x))
return xp,xn
def LRPOutput(layer,aJ,y,positive,multiple,rule,ignore=None,amplify=1,highest=False,label=None,
randomLogit=False):
#returns output relevance, create a new batch dimenison for classes,
#of size C, the number of DNN outputs/classes. Returns diagonal matrix.
#y:classifier output
#positive: deprecated
#multiple: creates one map per class if True
#ignore: lsit with classes which will not suffer attention control
#check parameters:
tmp=0
for i in [(label is not None),randomLogit, multiple, highest]:
if i:
tmp+=1
if tmp>1:
raise ValueError('Choose label, randomLogit, multiple or highest')
if(rule=='z+e'):
if multiple:
raise ValueError('Not implemented')
ROp=LRPOutput(layer,aJ,y,positive=False,multiple=False,rule='z+',
ignore=ignore,amplify=amplify)
ROe=LRPOutput(layer,aJ,y,positive=False,multiple=False,rule='e',
ignore=ignore,amplify=amplify)
RO=torch.cat((ROp,ROe),dim=1)#one map for each rule, in the classes dim
return RO
#recreate y with detached bias
weights=layer.weight
if (layer.bias is not None):
bias=layer.bias.detach()
else:
bias=None
if (rule=='z+'):
if(torch.min(aJ)<0):
raise ValueError('negative aJ elements input and z+ rule, not implemented for this case')
weights=torch.max(weights,torch.zeros(weights.shape).type_as(weights))
if (bias is not None):
bias=torch.max(bias,torch.zeros(bias.shape).type_as(bias))
else:
bias=None
if ((bias is not None and globals.detach) or rule=='z+'):
aK=nn.functional.linear(aJ,weights,bias)
else:
aK=y.clone()
numOutputs=aK.shape[-1]
ones=torch.ones((numOutputs)).type_as(aK)
if (ignore is not None):
for i,_ in enumerate(ones,0):
if(i in ignore):
ones[i]=ones[i]*0
if rule=='z+' or rule=='e':
if(multiple):
#define identity matrix:
I=torch.diag(ones)
#repeat the outputs and element-wise multiply with identity
RO=torch.mul(aK.unsqueeze(-1).repeat(1,1,numOutputs),I)
else:
if label is not None:
print('Label logit being used, do not use for training ISNet')
#propagate highest logit
I=torch.diag(ones)
#repeat the outputs and element-wise multiply with identity
RO=torch.mul(aK.unsqueeze(-1).repeat(1,1,numOutputs),I)
idx=label
tmp=[]
for i,val in enumerate(idx,0):
tmp.append(RO[i,val,:])
RO=torch.stack(tmp,dim=0)#batch dimension
RO=RO.unsqueeze(1)#add classes dimension back
elif randomLogit:
I=torch.diag(ones)
#repeat the outputs and element-wise multiply with identity
RO=torch.mul(aK.unsqueeze(-1).repeat(1,1,numOutputs),I)
if random.randint(1,10)>5:#propagate logit for highest class, 50% chance
#propagate highest logit
idx=torch.argmax(y,dim=-1)
tmp=[]
for i,val in enumerate(idx,0):
tmp.append(RO[i,val,:])
RO=torch.stack(tmp,dim=0)#batch dimension
RO=RO.unsqueeze(1)#add classes dimension back
else:#select logit randomly in other classes
idx=torch.argmax(y,dim=-1)
tmp=[]
for i,val in enumerate(idx,0):
rand=random.randint(0,RO.shape[1]-1)
while (rand==val):
rand=random.randint(0,(RO.shape[1]-1))#select random class
tmp.append(RO[i,rand,:])
RO=torch.stack(tmp,dim=0)#batch dimension
RO=RO.unsqueeze(1)#add classes dimension back
elif highest:
#propagate highest logit
I=torch.diag(ones)
#repeat the outputs and element-wise multiply with identity
RO=torch.mul(aK.unsqueeze(-1).repeat(1,1,numOutputs),I)
idx=torch.argmax(y,dim=-1)
tmp=[]
for i,val in enumerate(idx,0):
tmp.append(RO[i,val,:])
RO=torch.stack(tmp,dim=0)#batch dimension
RO=RO.unsqueeze(1)#add classes dimension back
else:
#propagate every logit simultaneously
RO=torch.mul(aK,ones).unsqueeze(1)
if amplify!=1:
RO=RO*amplify
if rule!='z+' and rule!='e' and rule!='z+e':
raise ValueError('Not implemented')
#print(RO.shape)
return RO
def LRPDenseReLU(layer,rK,aJ,aK,e,weights=None,bias=None,rule='e',alpha=2,beta=-1):
#Propagates relevance through fully-connected layer
#layer: layer L throgh which we propagate relevance, fully-connected
#e: LRP-e term. Use e=0 for LRP0
#RK: relevance at layer L output
#aJ: values at layer L input
#aK: activations before ReLU
#rule: 'e': epsilon; 'AB': alpha beta
#alpha and beta: weights for LRP-AlphaBeta rule
#size of batch dimension (0):
batchSize=rK.shape[0]
#size of classes dimension (1):
numOutputs=rK.shape[1]
if layer is not None:
weights=layer.weight
if (layer.bias is not None):
bias=layer.bias.detach()
else:
bias=None
if (rule=='e' or rule=='z+'):
if (rule=='z+'):
if(torch.min(aJ)<0):
raise ValueError('negative aJ elements in MaxPool input and z+ rule')
weights=torch.max(weights,torch.zeros(weights.shape).type_as(weights))
if (bias is not None):
bias=torch.max(bias,torch.zeros(bias.shape).type_as(bias))
else:
bias=None
if ((bias is not None and globals.detach) or rule=='z+'):
aK=nn.functional.linear(aJ,weights,bias)
aK=aK.unsqueeze(1).repeat(1,numOutputs,1)
z=aK+stabilizer(aK=aK,e=e)
#element-wise inversion:s
s=torch.div(rK,z)
#shape: batch,o,k
W=torch.transpose(weights,0,1)
#mix batch and class dimensions
s=s.view(batchSize*numOutputs,s.shape[-1])
#back relevance with transposed weigths
c=nn.functional.linear(s,W)
#unmix:
c=c.view(batchSize,numOutputs,c.shape[-1])
#add classes dimension:
AJ=aJ.unsqueeze(1)
if numOutputs>1:
AJ=AJ.repeat(1,numOutputs,1)
#print(AJ.shape,c.shape)
RJ=torch.mul(AJ,c)
elif (rule=='z+e'):
#numOutputs should be 2, considering one map per rule. set it to half:
numOutputs=int(numOutputs/2)
if(torch.min(aJ)>=0):
#raise ValueError('negative aJ elements in MaxPool input and z+ rule')
weights_p=torch.max(weights,torch.zeros(weights.shape).type_as(weights))
if (bias is not None and globals.detach):
biases_p=torch.max(bias,torch.zeros(bias.shape).type_as(bias))
aKe=nn.functional.linear(aJ,weights,bias)
else:
biases_p=None
aKe=aK
aKp=nn.functional.linear(aJ,weights_p,biases_p)
aKp=aKp.unsqueeze(1).repeat(1,numOutputs,1)
aKe=aKe.unsqueeze(1).repeat(1,numOutputs,1)
zp=aKp+stabilizer(aK=aKp,e=e)
ze=aKe+stabilizer(aK=aKe,e=e)
#element-wise inversion:s
sp=torch.div(rK[:,:numOutputs,:],zp)
se=torch.div(rK[:,numOutputs:,:],ze)
#shape: batch,o,k
W=torch.transpose(weights,0,1)
Wp=torch.transpose(weights_p,0,1)
#mix batch and class dimensions
sp=sp.view(batchSize*numOutputs,sp.shape[-1])
se=se.view(batchSize*numOutputs,se.shape[-1])
#back relevance with transposed weigths
cp=nn.functional.linear(sp,Wp)
ce=nn.functional.linear(se,W)
#unmix:
ce=ce.view(batchSize,numOutputs,ce.shape[-1])
cp=cp.view(batchSize,numOutputs,cp.shape[-1])
#add 2 rules to classes dimension
c=torch.cat((cp,ce), dim=1)
#add classes dimension:
AJ=aJ.unsqueeze(1).repeat(1,numOutputs*2,1)
RJ=torch.mul(AJ,c)
else:
RJp=LRPDenseReLU(layer,rK[:,:numOutputs,:],aJ,aK,e,rule='AB',alpha=1,beta=0,
weights=weights,bias=bias)
RJe=LRPDenseReLU(layer,rK[:,numOutputs:,:],aJ,aK,e,rule='e',
weights=weights,bias=bias)
RJ=torch.cat((RJp,RJe),dim=1)
elif (rule=='AB'):
if((alpha+beta)!=1):
raise ValueError('Ensure alpha+beta=1')
#positive and negative parts
Wp,Wn=PosNeg(weights)
if bias is not None:
Bp,Bn=PosNeg(bias)
else:
Bp,Bn=None,None
aJp,aJn=PosNeg(aJ)
#step 1- Forward pass
aKp=nn.functional.linear(aJp,Wp,Bp)+nn.functional.linear(aJn,Wn)
aKn=nn.functional.linear(aJn,Wp,Bn)+nn.functional.linear(aJp,Wn)
aKp=aKp.unsqueeze(1).repeat(1,numOutputs,1)
aKn=aKn.unsqueeze(1).repeat(1,numOutputs,1)
#step 2- Division and stabilizer
zp=aKp+stabilizer(aK=aKp,e=e,sign=1)
sp=torch.div(rK,zp)
zn=aKn+stabilizer(aK=aKn,e=e,sign=-1)
sn=torch.div(rK,zn)
#step 3- Transpose pass
Wp=torch.transpose(Wp,0,1)
Wn=torch.transpose(Wn,0,1)
sp=sp.view(batchSize*numOutputs,sp.shape[-1])
sn=sn.view(batchSize*numOutputs,sn.shape[-1])
cp_a=nn.functional.linear(sp,Wp)
cp_b=nn.functional.linear(sp,Wn)
cn_a=nn.functional.linear(sn,Wp)
cn_b=nn.functional.linear(sn,Wn)
cp_a=cp_a.view(batchSize,numOutputs,cp_a.shape[-1])
cp_b=cp_b.view(batchSize,numOutputs,cp_b.shape[-1])
cn_a=cn_a.view(batchSize,numOutputs,cn_a.shape[-1])
cn_b=cn_b.view(batchSize,numOutputs,cn_b.shape[-1])
#step 4- Multiplication with input
aJp=aJp.unsqueeze(1).repeat(1,numOutputs,1)
aJn=aJn.unsqueeze(1).repeat(1,numOutputs,1)
RJ=alpha*(torch.mul(aJp.squeeze(1),cp_a.squeeze(1))+\
torch.mul(aJn.squeeze(1),cp_b.squeeze(1)))
RJ=RJ+beta*(torch.mul(aJn.squeeze(1),cn_a.squeeze(1))+\
torch.mul(aJp.squeeze(1),cn_b.squeeze(1)))
if(len(RJ.shape)<5):
RJ=RJ.unsqueeze(1)
else:
raise ValueError('only Epsilon (e), Alpha Beta (AB), and z+ rules implemented')
return RJ
def ZbRuleDenseInput(layer,rK,aJ,aK,e,l=0,h=1):
#used to propagate relevance through the sequence: Convolution, ReLU using Zb rule
#l and h: minimum and maximum allowed pixel values
#layer: convolutional layer throgh which we propagate relevance
#e: LRP-e term. Use e=0 for LRP0
#rK: relevance at layer L ReLU output
#aJ: values at layer L convolution input
#aK: activations after BN
#print(rK.shape,aJ.shape,aK.shape,layer)
batchSize=rK.shape[0]
#size of classes dimension (1):
numOutputs=rK.shape[1]
weights=layer.weight
if(layer.bias is not None):
biases=layer.bias.detach()
else:
biases=torch.zeros(layer.out_features).type_as(rK)
#positive and negative weights:
Wpos,Wneg=PosNeg(weights)
#positive and negative bias:
BPos,BNeg=PosNeg(layer.bias.detach())
#propagation:
aKPos=nn.functional.linear(torch.ones(aJ.shape).type_as(rK)*l,weight=Wpos,
bias=BPos*l)
aKNeg=nn.functional.linear(torch.ones(aJ.shape).type_as(rK)*h,weight=Wneg,
bias=BNeg*h)
if (layer.bias is not None and globals.detach):
aK=nn.functional.linear(aJ,weights,biases)
z=aK-aKPos-aKNeg
z=z.unsqueeze(1).repeat(1,numOutputs,1)
#print('z',z.shape)
z=z+stabilizer(z,e=e)
s=torch.div(rK,z)
#print(s.shape)
#print(numOutputs)
W=torch.transpose(weights,0,1)
Wpos=torch.transpose(Wpos,0,1)
Wneg=torch.transpose(Wneg,0,1)
#mix batch and class dimensions
s=s.view(batchSize*numOutputs,s.shape[-1])
#back relevance with transposed weigths
c=nn.functional.linear(s,W)
cPos=l*nn.functional.linear(s,Wpos)
cNeg=h*nn.functional.linear(s,Wneg)
#unmix:
c=c.view(batchSize,numOutputs,c.shape[-1])
cPos=cPos.view(batchSize,numOutputs,c.shape[-1])
cNeg=cNeg.view(batchSize,numOutputs,c.shape[-1])
AJ=aJ.unsqueeze(1).repeat(1,numOutputs,1)
R0=torch.mul(AJ,c)-cPos-cNeg
return R0
def LRPClassSelectiveOutputLayerOld(layer, aJ, aK, e, highest=False,amplify=1,label=None):
#non lse
#Explains a more class selective quantity, instead of the logits
#e: LRP-e term. Use e=0 for LRP0
#RK: relevance at layer L output
#aJ: values at layer L input
#print(aJ.shape,aK.shape)
#size of batch dimension (0):
batchSize=aJ.shape[0]
numOutputs=layer.weight.shape[0]
Zcc=[]
for c in list(range(numOutputs)):
#Zcc=Zc-Zc'
#forward pass:
weight=layer.weight[c].unsqueeze(0).repeat(numOutputs,1)-layer.weight
if layer.bias is not None:
bias=layer.bias[c].repeat(numOutputs)-layer.bias
if globals.detach:
bias=bias.detach()
else:
bias=None
Zcc.append(nn.functional.linear(aJ,weight,bias))
#stack in the new classes dimension
Zcc=torch.stack(Zcc,dim=1)
#backward pass to Zcc:
eZcc=torch.exp(-Zcc)
Rcc=Zcc*eZcc
#print('eZcc:',eZcc)
#Pc=eZcc/eZcc.sum(dim=-1,keepdim=True)
#print('Pc:',Pc)
#Nc=(-1)*torch.log(eZcc.sum(dim=-1,keepdim=True)-1)
#print('Nc:',Nc)
#print('Zc:',nn.functional.linear(aJ,layer.weight,layer.bias))
#-1 removes the element for c''=c, as it is e^0, as Zcc=0
denom=eZcc.sum(dim=-1,keepdim=True).repeat(1,1,numOutputs)-1
denom=denom+stabilizer(denom,e=1e-5)
Rcc=Rcc/denom
#print('Rcc:',Rcc)
#print('Rcc sum:',Rcc.sum(-1))
#akOl=aK.clone()
#backward pass to aJ, Zcc'=Sumj(aj*(wjc-wjc'))
RJ=[]
for c in list(range(numOutputs)):
weight=layer.weight[c].unsqueeze(0).repeat(numOutputs,1)-layer.weight
if layer.bias is not None:
bias=layer.bias[c].repeat(numOutputs)-layer.bias
if globals.detach:
bias=bias.detach()
else:
bias=None
aK=Zcc[:,c,:]
rK=Rcc[:,c,:].unsqueeze(1)
RJ.append(LRPDenseReLU(layer=None,rK=rK,aJ=aJ,aK=aK,e=e,
weights=weight, bias=bias).squeeze(1))
RJ=torch.stack(RJ,dim=1)
if highest or (label is not None):
#propagates only heatmap for highest logit
if highest:
idx=torch.argmax(aK,dim=-1)
elif (label is not None):
print('Label logit being used, do not use for ISNet training')
idx=label
print(idx, torch.argmax(aK,dim=-1))
#print(torch.equal(idx,torch.argmin(akOl,dim=-1)))
tmp=[]
for i,val in enumerate(idx,0):
tmp.append(RJ[i,val,:])
RJ=torch.stack(tmp,dim=0)
RJ=RJ.unsqueeze(1)#add classes dimension back
if amplify!=1:
RJ=RJ*amplify
return RJ
def LRPClassSelectiveOutputLayerMultiple(layer, aJ, aK, e, highest=False,amplify=1):
#used only for explanation, not for ISNet training
#Explains a more class selective quantity, instead of the logits
#e: LRP-e term. Use e=0 for LRP0
#RK: relevance at layer L output
#aJ: values at layer L input
#print(aJ.shape,aK.shape)
#size of batch dimension (0):
batchSize=aJ.shape[0]
numOutputs=layer.weight.shape[0]
Zcc=[]
for c in list(range(numOutputs)):
#Zcc=Zc-Zc'
#forward pass:
weight=layer.weight[c].unsqueeze(0).repeat(numOutputs,1)-layer.weight
if layer.bias is not None:
bias=layer.bias[c].repeat(numOutputs)-layer.bias
if globals.detach:
bias=bias.detach()
else:
bias=None
Zcc.append(nn.functional.linear(aJ,weight,bias))
#stack in the new classes dimension
Zcc=torch.stack(Zcc,dim=1)
#backward pass to Zcc:
eZcc=torch.exp(-Zcc)
#if (torch.isinf(eZcc).any()):
# eZcc=torch.exp(torch.minimum(-Zcc,11*torch.ones(Zcc.shape).type_as(Zcc)))
#this maximum was added after isnetZ+E experiments for paper!!!
Rcc=Zcc*eZcc
#print('eZcc:',eZcc)
#Pc=eZcc/eZcc.sum(dim=-1,keepdim=True)
#print('Pc:',Pc)
#Nc=(-1)*torch.log(eZcc.sum(dim=-1,keepdim=True)-1)
#print('Nc:',Nc)
#print('Zc:',nn.functional.linear(aJ,layer.weight,layer.bias))
#-1 removes the element for c''=c, as it is e^0, as Zcc=0
denom=eZcc.sum(dim=-1,keepdim=True).repeat(1,1,numOutputs)-1
denom=denom+stabilizer(denom,e=1e-5)
Rcc=Rcc/denom
#print('Rcc:',Rcc)
#print('Rcc sum:',Rcc.sum(-1))
#backward pass to aJ, Zcc'=Sumj(aj*(wjc-wjc'))
RJ=[]
for c in list(range(numOutputs)):
weight=layer.weight[c].unsqueeze(0).repeat(numOutputs,1)-layer.weight
if layer.bias is not None:
bias=layer.bias[c].repeat(numOutputs)-layer.bias
if globals.detach:
bias=bias.detach()
else:
bias=None
#aK=Zcc[:,c,:]
rK=Rcc[:,c,:].unsqueeze(1)
RJ.append(LRPDenseReLU(layer=None,rK=rK,aJ=aJ,aK=Zcc[:,c,:],e=e,
weights=weight, bias=bias).squeeze(1))
RJ=torch.stack(RJ,dim=1)
#print('RJ:',RJ)
#print('RJ sum:',RJ.sum(-1))
if highest:
#propagates only heatmap for highest logit
idx=torch.argmax(aK,dim=-1)
tmp=[]
#zalt=[]
for i,val in enumerate(idx,0):
tmp.append(RJ[i,val,:])
#zalt.append(Zcc[i,val,:])
#zalt=torch.stack(zalt,dim=0)
RJ=torch.stack(tmp,dim=0)
RJ=RJ.unsqueeze(1)#add classes dimension back
if amplify!=1:
RJ=RJ*amplify
return RJ#,zalt
def LRPClassSelectiveOutputLayer(layer, aJ, aK, e, highest=False,amplify=1,mode='lowest',label=None):
#used only for explanation, not for ISNet training
#Explains a more class selective quantity, instead of the logits
#e: LRP-e term. Use e=0 for LRP0
#RK: relevance at layer L output
#aJ: values at layer L input
if not highest and label is None:
return LRPClassSelectiveOutputLayerMultiple(layer,aJ,aK,e,highest,amplify)
if label is not None:
return LRPClassSelectiveOutputLayerOld(layer,aJ,aK,e,highest,amplify,label=label)
print('Using label logit')
#size of batch dimension (0):
batchSize=aJ.shape[0]
numOutputs=layer.weight.shape[0]
#highest:
#idx=torch.argmax(aK,dim=-1)
if mode=='random':
idx=torch.randint(low=0,high=numOutputs,size=(aK.shape[0],))
if mode=='random2':
mx=torch.argmax(aK,dim=-1)
mi=torch.argmin(aK,dim=-1)
idx=[]
for i,_ in enumerate(mx,0):
if numOutputs>2:
r=random.randint(1,3)
else:
r=random.randint(1,2)
if r==1:
idx.append(mx[i])
elif r==2:
idx.append(mi[i])
elif r==3:
tmp=random.randint(0,numOutputs-1)
while (tmp==mi[i] or tmp==mx[i]):
tmp=random.randint(0,numOutputs-1)
idx.append(tmp)
if mode=='lowest':
idx=torch.argmin(aK,dim=-1)
if mode=='highest':
sft=torch.softmax(aK,dim=-1)
n=torch.log(sft/(1-sft))
idx=torch.argmax(torch.abs(n),dim=-1)
Zcc=[]
for i,c in enumerate(idx,0):
#for c in list(range(numOutputs)):
#Zcc=Zc-Zc'
#forward pass:
weight=layer.weight[c].unsqueeze(0).repeat(numOutputs,1)-layer.weight
if layer.bias is not None:
bias=layer.bias[c].repeat(numOutputs)-layer.bias
if globals.detach:
bias=bias.detach()
else:
bias=None
Zcc.append(nn.functional.linear(aJ[i].unsqueeze(0),weight,bias))
#stack in the new classes dimension
Zcc=torch.cat(Zcc,dim=0)
if torch.isnan(Zcc).any():
print('nan 1')
#backward pass to Zcc:
eZcc=torch.exp(-Zcc)
#if (torch.isinf(eZcc).any()):
# eZcc=torch.exp(torch.minimum(-Zcc,11*torch.ones(Zcc.shape).type_as(Zcc)))
#this maximum was added after isnetZ+E experiments for paper!!!
Rcc=Zcc*eZcc
if torch.isnan(eZcc).any():
print('nan 2')
#-1 removes the element for c''=c, as it is e^0, as Zcc=0
denom=eZcc.sum(dim=-1,keepdim=True).repeat(1,numOutputs)-1
if torch.isnan(denom).any():
print('nan denom')
if torch.isinf(denom).any():
print('inf denom')
denom=denom+stabilizer(denom,e=1e-5)
Rcc=Rcc/denom
if torch.isnan(Rcc).any():
print('nan 3')
RJ=[]
for i,c in enumerate(idx,0):
#for c in list(range(numOutputs)):
weight=layer.weight[c].unsqueeze(0).repeat(numOutputs,1)-layer.weight
if layer.bias is not None:
bias=layer.bias[c].repeat(numOutputs)-layer.bias
if globals.detach:
bias=bias.detach()
else:
bias=None
aK=Zcc[i,:].unsqueeze(0)
rK=Rcc[i,:].unsqueeze(0).unsqueeze(1)
#print('aj',aJ[i].unsqueeze(0).shape)
#print('rK',rK.shape)
RJ.append(LRPDenseReLU(layer=None,rK=rK,aJ=aJ[i].unsqueeze(0),aK=aK,e=e,
weights=weight, bias=bias).squeeze(1))
RJ=torch.cat(RJ,dim=0).unsqueeze(1)
if torch.isnan(RJ).any():
print('nan 4')
if amplify!=1:
RJ=RJ*amplify
return RJ
def LRPLogSumExpPool(rK, aJ, lse_r , e):
#mix spatial dimensions and exponential:
exp_aJ=torch.exp(lse_r*aJ)
denom=exp_aJ.sum(dim=(-1,-2),keepdim=True)
denom=denom+stabilizer(denom,e)
R=torch.div(exp_aJ,denom)
#add classes dimension
R=R.unsqueeze(1).repeat(1,rK.shape[1],1,1,1)
R=torch.mul(R,rK.repeat(1,1,1,R.shape[-2],R.shape[-1]))
return R
def LRPConvReLUParallel(layer,rK,aJ,aK,e,rule='e',alpha=2,beta=-1,
weights=None,bias=None,stride=None,padding=None,dilation=1):
#returns: RJ, relevance at input of layer L
#layer: layer L throgh which we propagate relevance, convolutional
#e: LRP-e term. Use e=0 for LRP0
#RK: relevance at layer L output
#aJ: values at layer L input
#aK: activations before ReLU
#rule: 'e': epsilon; 'AB': alpha beta
#alpha and beta: weights for LRP-AlphaBeta rule
#weights, bias, stride and padding: layer parameters, overwritten if layer is not None
#size of batch dimension (0):
batchSize=rK.shape[0]
#size of classes dimension (1):
numOutputs=rK.shape[1]
if (layer is not None):
weights=layer.weight
stride=layer.stride
padding=layer.padding
dilation=layer.dilation
if(layer.bias is not None):
bias=layer.bias.detach()
else:
bias=None
if (rule=='e' or rule=='z+'):
if (rule=='z+'):
if(torch.min(aJ)<0):
return LRPConvReLU(layer,rK,aJ,aK,e,rule='AB',alpha=1,beta=0,
weights=weights,bias=bias,stride=stride,
padding=padding,dilation=dilation)
#raise ValueError('negative aJ elements in MaxPool input and z+ rule')
weights=torch.max(weights,torch.zeros(weights.shape).type_as(weights))
if(bias is not None):
bias=torch.max(bias,torch.zeros(bias.shape).type_as(bias))
if ((bias is not None and globals.detach) or rule=='z+'):
aK=nn.functional.conv2d(aJ,weight=weights,bias=bias,
stride=stride,padding=padding,
dilation=dilation)
aK=aK.unsqueeze(1).repeat(1,numOutputs,1,1,1)
z=aK+stabilizer(aK=aK,e=e)
#element-wise inversion:s
s=torch.div(rK,z)
#shape: batch,o,k