-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathISNetLayersZe.py
1667 lines (1384 loc) · 65.6 KB
/
ISNetLayersZe.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 ISNetFunctionsZe as f
import LRPDenseNetZe as LRPDenseNet
import globalsZe as globals
import re
#Transform function in ISNetFunctions in DNN layers:
class LRPDenseReLU (nn.Module):
def __init__(self, layer,e,rule,alpha=2,beta=-1):
super().__init__()
self.e=e
self.layer=layer
self.rule=rule
self.alpha=alpha
self.beta=beta
def forward(self, rK, aJ, aK):
y=f.LRPDenseReLU(layer=self.layer,rK=rK,aJ=aJ,aK=aK,e=self.e,rule=self.rule,
alpha=self.alpha,beta=self.beta)
return y
class LRPConvReLU (nn.Module):
def __init__(self, layer,e,rule,alpha=2,beta=-1):
super().__init__()
self.e=e
self.layer=layer
self.rule=rule
self.alpha=alpha
self.beta=beta
def forward(self, rK, aJ, aK):
y=f.LRPConvReLU(layer=self.layer,rK=rK,aJ=aJ,aK=aK,e=self.e,rule=self.rule,
alpha=self.alpha,beta=self.beta)
return y
class LRPOutput (nn.Module):
def __init__(self,layer,multiple,positive=False,rule='e',ignore=None,amplify=1,highest=False,
randomLogit=False):
super().__init__()
self.layer=layer
self.multiple=multiple
self.positive=positive
self.rule=rule
self.ignore=ignore
self.amplify=amplify
self.highest=highest
self.randomLogit=randomLogit
def forward(self, aJ,y,label=None):
return f.LRPOutput(layer=self.layer, aJ=aJ,
y=y,multiple=self.multiple,positive=self.positive,rule=self.rule,
ignore=self.ignore,amplify=self.amplify,highest=self.highest,label=label,
randomLogit=self.randomLogit)
class LRPSelectiveOutput (nn.Module):
def __init__(self,layer,e,rule,highest,amplify=1):
super().__init__()
self.e=e
self.layer=layer
self.rule=rule
self.highest=highest#single heatmap, for highest logit
self.amplify=amplify
def forward(self, aJ, aK, label=None):
return f.LRPClassSelectiveOutputLayer(layer=self.layer, aJ=aJ, aK=aK, e=self.e,
highest=self.highest,amplify=self.amplify,
label=label)
class LRPPool2d (nn.Module):
def __init__(self,layer,e,rule,alpha=2,beta=-1):
super().__init__()
self.e=e
self.layer=layer
self.rule=rule
self.alpha=alpha
self.beta=beta
def forward(self, rK, aJ, aK):
y= f.LRPPool2d(layer=self.layer,rK=rK,aJ=aJ,aK=aK,e=self.e,rule=self.rule,
alpha=self.alpha,beta=self.beta)
return y
class LRPAdaptativePool2d (nn.Module):
def __init__(self,layer,e,rule,alpha=2,beta=-1):
super().__init__()
self.e=e
self.layer=layer
self.rule=rule
self.alpha=alpha
self.beta=beta
def forward(self, rK, aJ,aK):
y= f.LRPPool2d(layer=self.layer,rK=rK,aJ=aJ,aK=aK,e=self.e,
adaptative=True,rule=self.rule,
alpha=self.alpha,beta=self.beta)
return y
class LRPSum (nn.Module):
def __init__(self,e,rule,alpha=2,beta=-1):
super().__init__()
self.e=e
self.rule=rule
self.alpha=alpha
self.beta=beta
def forward(self,rK,aJ,aK):
y= f.LRPSum(rK=rK,aJ=aJ,aK=aK,e=self.e,rule=self.rule,
alpha=self.alpha,beta=self.beta)
return y
class LRPElementWiseSum (nn.Module):
def __init__(self,e,rule):
super().__init__()
self.e=e
self.rule=rule
#if self.rule!='e':
# raise ValueError('LRPElementWiseSum can only be implemented for e rule')
def forward(self,rK,a,b):
y= f.LRPElementWiseSUM(rK,a,b,self.e,self.rule)
return y
class LRPLogSumExpPool(nn.Module):
def __init__(self,e,lse_r=6):
super().__init__()
self.e=e
self.lse_r=lse_r
def forward(self, rK, aJ):
y=f.LRPLogSumExpPool(rK, aJ, self.lse_r , self.e)
return y
class LRPPool2dBNReLU (nn.Module):
def __init__(self,layer,BN,e,rule,Ch0=0,Ch1=None,alpha=2,beta=-1):
super().__init__()
self.e=e
self.layer=layer
self.BN=BN
self.Ch=[Ch0,Ch1]
self.rule=rule
self.alpha=alpha
self.beta=beta
def forward (self,rK, aJ, aKConv):
y= f.LRPPool2dBNReLU(layer=self.layer,BN=self.BN,rK=rK,aJ=aJ,e=self.e,
aKConv=aKConv,
Ch0=self.Ch[0],Ch1=self.Ch[1],rule=self.rule,
alpha=self.alpha,beta=self.beta)
return y
class MultiBlockPoolBNReLU (nn.Module):
def __init__(self,layer,BN,e,rule,Ch0=0,Ch1=None,alpha=2,beta=-1):
super().__init__()
self.e=e
self.layer=layer
self.BN=BN
self.Ch=[Ch0,Ch1]
self.rule=rule
self.alpha=alpha
self.beta=beta
def forward (self, rK, aJ, aK, aKPool):
y= f.MultiBlockPoolBNReLU(layer=self.layer,BN=self.BN,rK=rK,aJ=aJ,aK=aK,e=self.e,
aKPool=aKPool,
Ch0=self.Ch[0],Ch1=self.Ch[1],rule=self.rule,
alpha=self.alpha,beta=self.beta)
return y
class MultiBlockMaxPoolBNReLU (nn.Module):
def __init__(self,layer,BN,e,rule,Ch0=0,Ch1=None,alpha=2,beta=-1):
super().__init__()
self.e=e
self.layer=layer
self.BN=BN
self.Ch=[Ch0,Ch1]
self.rule=rule
self.alpha=alpha
self.beta=beta
def forward (self, rK, aJ, aK, aKPool):
y= f.MultiBlockMaxPoolBNReLU(layer=self.layer,BN=self.BN,rK=rK,aJ=aJ,aK=aK,e=self.e,
aKPool=aKPool,
Ch0=self.Ch[0],Ch1=self.Ch[1],rule=self.rule,
alpha=self.alpha,beta=self.beta)
return y
class MultiLayerConvBNReLU (nn.Module):
def __init__(self,layer,BN,e,rule,Ch0=0,Ch1=None,alpha=2,beta=-1):
super().__init__()
self.e=e
self.layer=layer
self.BN=BN
self.Ch=[Ch0,Ch1]
self.rule=rule
self.alpha=alpha
self.beta=beta
def forward (self,rK,aJ,aKConv,aK):
y= f.MultiLayerConvBNReLU(layer=self.layer,BN=self.BN,rK=rK,aK=aK,aJ=aJ,e=self.e,
aKConv=aKConv,
Ch0=self.Ch[0],Ch1=self.Ch[1],rule=self.rule,
alpha=self.alpha,beta=self.beta)
return y
class LRPConvBNReLU (nn.Module):
def __init__(self,layer,BN,e,rule,Ch0=0,Ch1=None,alpha=2,beta=-1):
super().__init__()
self.e=e
self.layer=layer
self.BN=BN
self.Ch=[Ch0,Ch1]
self.rule=rule
self.alpha=alpha
self.beta=beta
def forward (self,rK,aJ,aKConv,aK):
y= f.LRPConvBNReLU(layer=self.layer,BN=self.BN,rK=rK,aK=aK,aJ=aJ,e=self.e,
aKConv=aKConv,
Ch0=self.Ch[0],Ch1=self.Ch[1],rule=self.rule,
alpha=self.alpha,beta=self.beta)
return y
class LRPBNReLU (nn.Module):
def __init__(self,BN,e,rule,alpha=2,beta=-1):
super().__init__()
self.e=e
self.BN=BN
self.rule=rule
self.alpha=alpha
self.beta=beta
def forward (self,rK,aJ,aK):
y= f.LRPBNReLU(BN=self.BN,rK=rK,aK=aK,aJ=aJ,e=self.e,
rule=self.rule,
alpha=self.alpha,beta=self.beta)
return y
class w2RuleInput (nn.Module):
def __init__(self,layer,e):
super().__init__()
self.e=e
self.layer=layer
def forward (self,rK,aJ,aK):
y= f.w2RuleInput(layer=self.layer,rK=rK,aJ=aJ,aK=aK,e=self.e)
return y
class w2BNRuleInput (nn.Module):
def __init__(self,layer,BN,e):
super().__init__()
self.e=e
self.BN=BN
def forward (self,rK,aJ,aKConv,aK):
y= f.w2BNRuleInput(layer=self.layer,BN=self.BN,rK=rK,aJ=aJ,aK=aK,
e=self.e,aKConv=aKConv)
return y
class ZbRuleConvBNInput (nn.Module):
def __init__(self,layer,BN,e,l=0,h=1,op=None):
super().__init__()
self.e=e
self.layer=layer
self.BN=BN
self.l=l
self.h=h
def forward (self,rK,aJ,aKConv,aK):
try:
y= f.ZbRuleConvBNInput(layer=self.layer,BN=self.BN,rK=rK,aJ=aJ,aK=aK,
aKConv=aKConv,e=self.e,
l=self.l,h=self.h)
except:#legacy, if self.op is missing
y= f.ZbRuleConvBNInput(layer=self.layer,BN=self.BN,rK=rK,aJ=aJ,aK=aK,
aKConv=aKConv,e=self.e,
l=self.l,h=self.h)
return y
class ZbRuleConvInput (nn.Module):
def __init__(self,layer,e,l=0,h=1,op=None):
super().__init__()
self.e=e
self.layer=layer
self.l=l
self.h=h
def forward (self,rK,aJ,aK):
try:
y= f.ZbRuleConvInput(layer=self.layer,rK=rK,aJ=aJ,aK=aK,
e=self.e,l=self.l,h=self.h,op=self.op)
except:#legacy, if self.op is missing
y= f.ZbRuleConvInput(layer=self.layer,rK=rK,aJ=aJ,aK=aK,
e=self.e,l=self.l,h=self.h)
return y
class ZbRuleDenseInput (nn.Module):
def __init__(self,layer,e,l=0,h=1,op=None):
super().__init__()
self.e=e
self.layer=layer
self.l=l
self.h=h
def forward (self,rK,aJ,aK):
y= f.ZbRuleDenseInput(layer=self.layer,rK=rK,aJ=aJ,aK=aK,
e=self.e,l=self.l,h=self.h)
return y
class LRPMaxPool (nn.Module):
def __init__(self,layer,e,rule,alpha=2,beta=-1):
super().__init__()
self.e=e
self.layer=layer
self.rule=rule
self.alpha=alpha
self.beta=beta
def forward (self,rK,aJ,aK):
y= f.LRPMaxPool2d(layer=self.layer,rK=rK,aJ=aJ,aK=aK,e=self.e,rule=self.rule,
alpha=self.alpha,beta=self.beta)
return y
#DenseNet specific modules:
class LRPDenseLayer (nn.Module):
def __init__(self,DenseLayerIdx,DenseBlockIdx,model,e,rule):
#propagates relevance through a dense layer inside dense block
#DenseLayerIdx: index of dense layer in block
#DenseBlockIdx: Dense block index
#model: dictionary with all layers and fdw indexes (net.layers)
#e: LRP-e term
super(LRPDenseLayer,self).__init__()
#Ch0 and Ch1: channels of the dense layer output in the BNs
DenseBlock=model['features']['denseblock'+str(DenseBlockIdx)]
self.DenseLayer=DenseBlock['denselayer'+str(DenseLayerIdx)]
Ch0=self.DenseLayer['norm1'][0].num_features
Ch1=Ch0+self.DenseLayer['conv2'][0].weight.shape[0]
#BNs: all batch normalizations that take the DenseLayer output
BNs=[]
#indexes of batchnorm outputs in the global fdw:
self.BNOut=[]
#indexes (negative) of relevances from posterior layers in block, starting from last:
self.Rs=[]
#transition layer:
if ('transition'+str(DenseBlockIdx) in model['features']):
#not last denseblock
BNs.append(model['features']['transition'+str(DenseBlockIdx)]['norm'][0])
self.BNOut.append(model['features']['transition'+str(DenseBlockIdx)]['norm'][1])
else:
#last denseblock
BNs.append(model['features']['norm5'][0])
self.BNOut.append(model['features']['norm5'][1])
#iterate from last layer in the DenseBlock (BN order will match self.R order):
j=(len(DenseBlock)-DenseLayerIdx)*(-1)
self.Rs.append(j-1)#transition layer
for key,layer in reversed(list(DenseBlock.items())):
if(int(key[-1])>DenseLayerIdx):
BNs.append(layer['norm1'][0])
self.BNOut.append(layer['norm1'][1])
self.Rs.append(j)
j=j+1
#initialize layers:
#through batchnorms and ReLUs in posterior layers and conv2 in this layer
self.L2=MultiLayerConvBNReLU(layer=self.DenseLayer['conv2'][0],
BN=BNs,e=e,Ch0=Ch0,Ch1=Ch1,rule=rule)
#through conv1, norm2 and relu2:
self.L1=LRPConvBNReLU(layer=self.DenseLayer['conv1'][0],BN=self.DenseLayer['norm2'][0],
e=e,rule=rule)
def forward (self,X,R):
#X:list of all layer activations
#R:list of relevances after dense layers, starting from last DNN layer
#through batchnorms and ReLUs in posterior layers and conv2 in this layer:
#get relevances from posterior layers
rK=[]
for i in self.Rs:
rK.append(R[i])
#get activations from posterior layers:
aK=[]
for i in self.BNOut:
aK.append(X[i])
#get activations for current layer:
aKConv=X[self.DenseLayer['conv2'][1]]
aJ=X[self.DenseLayer['relu2'][1]]
#propagate relevance:
r=self.L2(rK=rK,aJ=aJ,aKConv=aKConv,aK=aK)
#through conv1, norm2 and relu2:
aJ=X[self.DenseLayer['relu1'][1]]
aKConv=X[self.DenseLayer['conv1'][1]]
aK=X[self.DenseLayer['norm2'][1]]
r=self.L1(rK=r,aJ=aJ,aKConv=aKConv,aK=aK)
return r
class LRPDenseBlock (nn.ModuleDict):
def __init__(self,DenseBlockIdx,model,e,rule):
#propagates relevance through a dense block
#DenseBlockIdx: index of dense block in the DenseNet
#model: dictionary with all layers and fdw indexes (net.layers)
#e: LRP-e term
super(LRPDenseBlock,self).__init__()
DenseBlock=model['features']['denseblock'+str(DenseBlockIdx)]
if ('transition'+str(DenseBlockIdx) in model['features']):
Transition=model['features']['transition'+str(DenseBlockIdx)]
#initialize all dense layers:
for i in reversed(list(range(len(DenseBlock)))):
layer=LRPDenseLayer(DenseLayerIdx=i+1,DenseBlockIdx=DenseBlockIdx,
model=model,e=e,rule=rule)
self.add_module('LRPlayer%d' % (i + 1), layer)
def forward(self,X,r):
#X:list of all layer activations
#r:relevance before next block/transition first convolution
R=[r]
#propagate relevance through layer, from last in block
for name,layer in self.items():
R.append(layer(X=X,R=R))
#return all dense layers relevances+transition
return R
class LRPDenseNetClassifier(nn.Module):
def __init__(self,model,e,rule,multiple,positive,ignore,selective=False,highest=False,
amplify=1,randomLogit=False):
#propagates relevance through the DenseNet last layers (after dense blocks)
#model: dictionary with all layers and fdw indexes (net.layers)
#e: LRP-e term
#ignore: lsit with classes which will not suffer attention control
#selective: uses class selective propagation.
super(LRPDenseNetClassifier,self).__init__()
#dense layer:
try:
classifier=model['classifier'][0]
except:
#model with dropout
classifier=model['classifier']['1'][0]
#num_features: number of channels after adaptative pool
self.num_features=classifier.in_features
if selective:
self.SelectiveOut=LRPSelectiveOutput(classifier,e,rule,highest,amplify=amplify)
else:
#initialize output LRP layer:
self.Out=LRPOutput(layer=classifier,multiple=multiple,positive=positive,
rule=rule,ignore=ignore,highest=highest,
amplify=amplify,randomLogit=randomLogit)
#initialize LRP layer for classifier:
self.Dense=LRPDenseReLU(classifier,e,rule)
#pooling layer:
pool=model['features']['AdaptPool'][0]
self.PoolInput=model['features']['fReLU'][1]
self.PoolOutput=model['features']['AdaptPool'][1]
#initialize LRP layer for pooling:
self.AdpPool=LRPAdaptativePool2d(pool,e=e,rule=rule)
self.multiple=multiple
self.rule=rule
self.selective=selective
self.highest=highest
def forward(self,X,XI,y,label=None):
#X:list of all layer activations
#XI: inputs of last layer
#y: classifier outputs
B=y.shape[0]#batch size
if self.rule=='z+e':
C=2
elif self.multiple:
C=y.shape[-1]
elif not self.multiple:
C=1
else:
raise ValueError('Invalid argument selection')
if self.selective:
R=self.SelectiveOut(aJ=XI[0],aK=y,label=label)
R=R.view(B,C,self.num_features,1,1)
else:
#y:DNN output
R=self.Out(aJ=XI[0],y=y,label=label)
R=self.Dense(rK=R,aJ=XI[0],aK=y)
R=R.view(B,C,self.num_features,1,1)
R=self.AdpPool(rK=R,aJ=X[self.PoolInput],aK=X[self.PoolOutput])
return R
class LRPDenseNetInitial(nn.Module):
def __init__(self,model,e,rule,Zb=True):
#propagates relevance through the DenseNet first layers (before dense blocks)
#model: dictionary with all layers and fdw indexes (net.layers)
#e: LRP-e term
#Zb: allows Zb rule. If false, will use traditional LRP-e.
super(LRPDenseNetInitial,self).__init__()
#all layers in the first dense block:
BNs=[]
self.BNOut=[]
if ('transition1' in model['features']):
BNs.append(model['features']['transition1']['norm'][0])
self.BNOut.append(model['features']['transition1']['norm'][1])
else:
BNs.append(model['features']['norm5'][0])
self.BNOut.append(model['features']['norm5'][1])
self.Rs=[]
DenseBlock=model['features']['denseblock1']
self.features=model['features']
#from last dense layer:
j=len(DenseBlock)*(-1)
self.Rs.append(j-1)#transition layer
for key,layer in reversed(list(DenseBlock.items())):
BNs.append(layer['norm1'][0])
self.BNOut.append(layer['norm1'][1])
self.Rs.append(j)
j=j+1
#init pool:
self.pool=MultiBlockMaxPoolBNReLU(layer=model['features']['pool0'][0],BN=BNs,
Ch1=model['features']['norm0'][0].num_features,
e=e,rule=rule)
if(Zb):
self.conv=ZbRuleConvBNInput(layer=model['features']['conv0'][0],
BN=model['features']['norm0'][0],
e=e,l=0,h=1)
else:
self.conv=LRPConvBNReLU(layer=model['features']['conv0'][0],
BN=model['features']['norm0'][0],
e=e,rule=rule)
def forward(self,X,x,r):
#X:list of all layer activations
#x: model input images
#r:relevances from first dense block
rK=[]
for i in self.Rs:
rK.append(r[i])
aK=[]
for i in self.BNOut:
aK.append(X[i])
#get activations for current layer:
aKPool=X[self.features['pool0'][1]]
aJ=X[self.features['relu0'][1]]
R=self.pool(rK=rK, aJ=aJ, aKPool=aKPool, aK=aK)
R=self.conv(rK=R,aJ=x,aKConv=X[self.features['conv0'][1]],
aK=X[self.features['norm0'][1]])
return R
class LRPDenseNetTransition(nn.Module):
def __init__(self,TransitionIdx,model,e,rule):
#propagates relevance through transition layer
#TransitionIdx: index of transiton layer
#model: dictionary with all layers and fdw indexes (net.layers)
#e: LRP-e term
super(LRPDenseNetTransition,self).__init__()
#all layers in the first dense block:
BNs=[]
self.BNOut=[]
nextT='transition'+str(TransitionIdx+1)
self.current='transition'+str(TransitionIdx)
if (nextT in model['features']):
BNs.append(model['features'][nextT]['norm'][0])
self.BNOut.append(model['features'][nextT]['norm'][1])
else:
BNs.append(model['features']['norm5'][0])
self.BNOut.append(model['features']['norm5'][1])
self.Rs=[]
#next dense block:
DenseBlock=model['features']['denseblock'+str(TransitionIdx+1)]
self.features=model['features']
#from last dense layer:
j=len(DenseBlock)*(-1)
self.Rs.append(j-1)#next transition layer
for key,layer in reversed(list(DenseBlock.items())):
BNs.append(layer['norm1'][0])
self.BNOut.append(layer['norm1'][1])
self.Rs.append(j)
j=j+1
#init pool:
self.pool=MultiBlockPoolBNReLU(layer=model['features'][self.current]['pool'][0],BN=BNs,
Ch1=model['features'][self.current]['conv'][0].out_channels,
e=e,rule=rule)
self.conv=LRPConvReLU(layer=model['features'][self.current]['conv'][0],
e=e,rule=rule)
def forward(self,X,r):
#X:list of all layer activations
#r:relevances from next dense block
rK=[]
for i in self.Rs:
rK.append(r[i])
aK=[]
for i in self.BNOut:
aK.append(X[i])
#get activations for current layer:
aKPool=X[self.features[self.current]['pool'][1]]
aJ=X[self.features[self.current]['relu2'][1]]
R=self.pool(rK=rK, aJ=aJ, aKPool=aKPool, aK=aK)
R=self.conv(rK=R,aJ=X[self.features[self.current]['relu'][1]],
aK=X[self.features[self.current]['conv'][1]])
return R
class _LRPDenseNet(nn.ModuleDict):
def __init__(self,DenseNet,e,rule,multiple,positive,ignore=None,Zb=True,selective=False,
highest=False,amplify=1,detach=True,features='fReLU',
storeRelevance=False,FSP=False,randomLogit=False):
#LRP Block: Propagates relevance through DenseNet
#network: classifier
#e: LRP-e term
#Zb: allows Zb rule. If false, will use traditional LRP-e.
#rule: LRP rule, e or z+e
#ignore: lsit with classes which will not suffer attention control
#selective: uses class selective propagation. Only for explanation, not for ISNet training.
#highest: set to true for selective ISNet
#amplify: multiplier to LRP heatmap
#multiple: multiple heatmaps per sample, use for Original ISNet
#detach: detach biases from graph when propagating relevances
#FSP: full signal penalization in LDS
#storeRelevance: stores intermediate heatmaps for LDS
#randomLogit: Stochastic ISNet
#features: deprecated
super(_LRPDenseNet,self).__init__()
#check for inconsistent parameters:
if (randomLogit and selective):
raise ValueError('Set randomLogit or selective, not both')
if(not torch.backends.cudnn.deterministic):
raise ValueError('Please set torch.backends.cudnn.deterministic=True')
if(rule=='AB' or rule=='z+' or rule=='composite'):
print('ATTENTION: Using '+rule+' rule.')
print('AB and z+ rule should not be used for background relevance minimization. Use them for vizualization only.')
if(multiple and rule=='z+e'):
raise ValueError('Please set multiple=False with z+e rule')
if(selective and rule=='z+e'):
raise ValueError('Selective should not be used with z+e rules')
if (not multiple and not selective and rule=='e'):
print('ATTENTION: multiple and selective set to false with e rule. For ISNet training, please use multiple=True selective=False rule=e (original ISNet), or multiple=False selective=True rule=e (selective isnet), or multiple=False selective=False rule=z+e (isnet z+e)')
#register hooks:
f.resetGlobals()
model=f.InsertHooks(DenseNet)
try:
classifier=model['classifier'][0]
except:
#model with dropout
classifier=model['classifier']['1'][0]
classifier.register_forward_hook(f.AppendInput)
#classifier and last layers:
composite=False
last_e=e
if rule=='composite':
composite=True
rule='e'
last_e=1e-6#LRP-0 like
self.add_module('LRPFinalLayers',
LRPDenseNetClassifier(model=model,e=last_e,rule=rule,multiple=multiple,
positive=positive,ignore=ignore,selective=selective,
highest=highest,amplify=amplify,
randomLogit=randomLogit))
changeRule=0
if composite:
for key in reversed(list(model['features'])):
if ('denseblock' in key):
maximum=int(key[-1])
break
changeRule=int(maximum/2)
#DenseBlocks and transitions:
for key in reversed(list(model['features'])):
if ('denseblock' in key):
block=int(key[-1])
self.add_module('LRPDenseBlock%d' % (block),
LRPDenseBlock(block,model=model,e=e,rule=rule))
if ('transition' in key):
trans=int(key[-1])
if (composite and trans==changeRule):
rule='AB'
self.add_module('LRPTransition%d' % (trans),
LRPDenseNetTransition(trans,model=model,e=e,rule=rule))
#initial layers:
self.add_module('LRPInitialLayers',
LRPDenseNetInitial(model=model,e=e,Zb=Zb,rule=rule))
globals.detach=detach
self.features=model['features'][features][1]
#register hooks to store relevance
if not FSP and storeRelevance:
self.storedRelevance={}
self.storedRelevance['LRPFinalLayers']=f.HookRelevance(self.LRPFinalLayers)
for name, module in self.named_modules():
if 'LRPTransition' in name and '.' not in name:
self.storedRelevance[name]=f.HookRelevance(module)
elif FSP:
self.storedRelevance=f.InsertFSPHooksDense(self,'LRPBlock')
self.storedRelevance['LRPFinalLayers']=f.HookRelevance(self.LRPFinalLayers)
self.storedRelevance['LRPInitialLayers']=f.HookRelevance(self.LRPInitialLayers.pool)
def forward(self,x,y,returnFeatures=False,LRPFeatures=False,label=None):
#x: model input
#y: classifier output
R=self.LRPFinalLayers(X=globals.X,XI=globals.XI,y=y,label=label)
featuresLRP=R.clone()
for name,layer in self.items():
if ((name != 'LRPFinalLayers') and (name != 'LRPInitialLayers')
and (name != 'features')):
R=layer(X=globals.X,r=R)
R=self.LRPInitialLayers(X=globals.X,x=x,r=R)
featureMaps=globals.X[self.features]
#clean global variables:
globals.X=[]
globals.XI=[]
if returnFeatures and LRPFeatures:
return R,featureMaps,featuresLRP
elif LRPFeatures:
return R,featuresLRP
elif returnFeatures:
return R,featureMaps
else:
return R
class IsDense(nn.Module):
def __init__(self,DenseNet,e=1e-2,heat=True,ignore=None,
Zb=True,rule='e',multiple=True,positive=False,
selective=False,highest=False,amplify=1,detach=True,
randomLogit=False):
#Creates ISNet based on DenseNet
#DenseNet: classifier
#e: LRP-e term
#Zb: allows Zb rule. If false, will use traditional LRP-e.
#heat: allows relevance propagation and heatmap creation. If False,
#no signal is propagated through LRP block.
#rule: LRP rule, choose e, z+, AB or z+e. For background relevance
#minimization use either e or z+e.
#multiple: whether to produce a single heatmap or one per class
#positive: whether to make output relevance positive or not
#selective: uses class selective propagation. Only for explanation, not for ISNet training.
#highest: makes selective rule with a single heatmap
super (IsDense,self).__init__()
self.DenseNet=DenseNet
self.LRPBlock=_LRPDenseNet(self.DenseNet,e=e,Zb=Zb,rule=rule,
multiple=multiple,positive=positive,
selective=selective,
ignore=ignore,highest=highest,
amplify=amplify,detach=detach,
randomLogit=randomLogit)
self.heat=heat
def forward(self,x):
#x:input
y=self.DenseNet(x)
if(self.heat):
R=self.LRPBlock(x=x,y=y)
return y,R
else:
globals.X=[]
globals.XI=[]
return y
#Resnet specific modules:
from collections import OrderedDict
class IgnoreIndexes(nn.Module):
#special layer to ignore indexes of previous max pooling layer
def __init__(self):
super(IgnoreIndexes, self).__init__()
def forward(self, x):
return(x[0])
class LRPResNetBottleneck (nn.Module):
def __init__(self,model,e,rule):
#model: bottleneck
super(LRPResNetBottleneck ,self).__init__()
self.bottleneck=model
self.LRPSum=LRPElementWiseSum(e,rule=rule)
#check for downsampling:
if 'downsample' in self.bottleneck:
self.LRPDownsample=LRPConvBNReLU(layer=self.bottleneck['downsample']['0'][0],
BN=self.bottleneck['downsample']['1'][0],
e=e,
rule=rule)
self.LRPc3=LRPConvBNReLU(layer=self.bottleneck['conv3'][0],
BN=self.bottleneck['bn3'][0],
e=e,
rule=rule)
self.LRPc2=LRPConvBNReLU(layer=self.bottleneck['conv2'][0],
BN=self.bottleneck['bn2'][0],
e=e,
rule=rule)
self.LRPc1=LRPConvBNReLU(layer=self.bottleneck['conv1'][0],
BN=self.bottleneck['bn1'][0],
e=e,
rule=rule)
def forward(self,rK):
if 'downsample' not in self.bottleneck:#identity shotcut
RShortcut,R=self.LRPSum(rK,self.bottleneck['conv1'][1].input,
self.bottleneck['bn3'][1].output)
else:
RShortcut,R=self.LRPSum(rK,self.bottleneck['downsample']['1'][1].output,
self.bottleneck['bn3'][1].output)
RShortcut=self.LRPDownsample(RShortcut,
aJ=self.bottleneck['downsample']['0'][1].input,
aKConv=self.bottleneck['downsample']['0'][1].output,
aK=self.bottleneck['downsample']['1'][1].output)
R=self.LRPc3 (R,aJ=self.bottleneck['conv3'][1].input,
aKConv=self.bottleneck['conv3'][1].output,
aK=self.bottleneck['bn3'][1].output)
R=self.LRPc2 (R,aJ=self.bottleneck['conv2'][1].input,
aKConv=self.bottleneck['conv2'][1].output,
aK=self.bottleneck['bn2'][1].output)
R=self.LRPc1 (R,aJ=self.bottleneck['conv1'][1].input,
aKConv=self.bottleneck['conv1'][1].output,
aK=self.bottleneck['bn1'][1].output)
R=R+RShortcut
#print(torch.sum(R[:,0]))
return R
class LRPResNetBasicBlock (nn.Module):
def __init__(self,model,e,rule):
#model: bottleneck
super(LRPResNetBasicBlock ,self).__init__()
self.block=model
self.LRPSum=LRPElementWiseSum(e,rule=rule)
#check for downsampling:
if (list(self.block.keys())[0]=='conv1'):#conv bn relu
if 'downsample' in self.block:
self.LRPDownsample=LRPConvBNReLU(layer=self.block['downsample']['0'][0],
BN=self.block['downsample']['1'][0],
e=e,
rule=rule)
self.LRPc2=LRPConvBNReLU(layer=self.block['conv2'][0],
BN=self.block['bn2'][0],
e=e,
rule=rule)
self.LRPc1=LRPConvBNReLU(layer=self.block['conv1'][0],
BN=self.block['bn1'][0],
e=e,
rule=rule)
elif (list(self.block.keys())[0]=='bn1'):#bn relu conv
if 'downsample' in self.block:
self.LRPDownsample=LRPConvReLU(layer=self.block['downsample']['0'][0],
e=e,rule=rule)
self.LRPc2=LRPConvReLU(layer=self.block['conv2'][0],
e=e,rule=rule)
self.LRPc1=LRPConvBNReLU(layer=self.block['conv1'][0],
BN=self.block['bn2'][0],
e=e,rule=rule)
self.LRPbn=LRPBNReLU(BN=self.block['bn1'][0],
e=e,rule=rule)
else:
raise ValueError('Unrecognized block configuration')
def forward(self,rK):
if (list(self.block.keys())[0]=='conv1'):
if 'downsample' not in self.block:#identity shotcut
RShortcut,R=self.LRPSum(rK,self.block['conv1'][1].input,
self.block['bn2'][1].output)
else:
RShortcut,R=self.LRPSum(rK,self.block['downsample']['1'][1].output,
self.block['bn2'][1].output)
RShortcut=self.LRPDownsample(RShortcut,
aJ=self.block['downsample']['0'][1].input,
aKConv=self.block['downsample']['0'][1].output,
aK=self.block['downsample']['1'][1].output)
R=self.LRPc2 (R,aJ=self.block['conv2'][1].input,
aKConv=self.block['conv2'][1].output,
aK=self.block['bn2'][1].output)
R=self.LRPc1 (R,aJ=self.block['conv1'][1].input,
aKConv=self.block['conv1'][1].output,
aK=self.block['bn1'][1].output)
else:
if 'downsample' not in self.block:#identity shotcut
RShortcut,R=self.LRPSum(rK,self.block['bn1'][1].input,
self.block['conv2'][1].output)
else:
RShortcut,R=self.LRPSum(rK,self.block['downsample']['0'][1].output,
self.block['conv2'][1].output)
#print('shortcut')
RShortcut=self.LRPDownsample(RShortcut,
aJ=self.block['downsample']['0'][1].input,
aK=self.block['downsample']['0'][1].output)
if torch.isnan(R).any():
print('nan LRPshortcut')
#print(self.block)
#print('LRPc2')
R=self.LRPc2 (R,aJ=self.block['conv2'][1].input,
aK=self.block['conv2'][1].output)
if torch.isnan(R).any():
print('nan LRPc2')
#print('LRPc1')
R=self.LRPc1 (R,aJ=self.block['conv1'][1].input,
aKConv=self.block['conv1'][1].output,
aK=self.block['bn2'][1].output)
if torch.isnan(R).any():
print('nan LRPc1')
#print('LRPbn')
R=self.LRPbn (R,aJ=self.block['bn1'][1].input,
aK=self.block['bn1'][1].output)
if torch.isnan(R).any():
print('nan LRPbn')
#print(torch.sum(R[:,1]))
R=R+RShortcut
return R
class _LRPResNetLayer (nn.ModuleDict):
def __init__(self,model,idx,e,rule):
#idx: index of the resnet layer
super(_LRPResNetLayer ,self).__init__()
layer=model['layer'+str(idx)]
bottle=False
if 'conv3' in list(layer['0'].keys()):
bottle=True