-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathlrp_general6.py
2005 lines (1556 loc) · 77.6 KB
/
lrp_general6.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 copy
#######################################################
#######################################################
# wrappers for autograd type modules
#######################################################
#######################################################
class zeroparam_wrapper_class(nn.Module):
def __init__(self, module, autogradfunction):
super(zeroparam_wrapper_class, self).__init__()
self.module=module
self.wrapper=autogradfunction
def forward(self,x):
y=self.wrapper.apply( x, self.module)
return y
class oneparam_wrapper_class(nn.Module):
def __init__(self, module, autogradfunction, parameter1):
super(oneparam_wrapper_class, self).__init__()
self.module=module
self.wrapper=autogradfunction
self.parameter1=parameter1
def forward(self,x):
y=self.wrapper.apply( x, self.module,self.parameter1)
return y
class twoparam_wrapper_class(nn.Module):
def __init__(self, module, autogradfunction, parameter1, parameter2):
super(twoparam_wrapper_class, self).__init__()
self.module=module
self.wrapper=autogradfunction
self.parameter1=parameter1
self.parameter2 = parameter2
def forward(self,x):
y=self.wrapper.apply( x, self.module,self.parameter1, self.parameter2)
return y
class conv2d_zbeta_wrapper_class(nn.Module):
def __init__(self, module, lrpignorebias,lowest = None, highest = None ):
super(conv2d_zbeta_wrapper_class, self).__init__()
if lowest is None:
lowest=torch.min(torch.tensor([-0.485/0.229, -0.456/0.224, -0.406/0.225]))
if highest is None:
highest=torch.max (torch.tensor([(1-0.485)/0.229, (1-0.456)/0.224, (1-0.406)/0.225]))
assert( isinstance( module, nn.Conv2d ))
self.module=module
self.wrapper=conv2d_zbeta_wrapper_fct()
self.lrpignorebias=lrpignorebias
self.lowest=lowest
self.highest=highest
def forward(self,x):
y=self.wrapper.apply( x, self.module, self.lrpignorebias, self.lowest, self.highest)
return y
class lrplookupnotfounderror(Exception):
pass
def get_lrpwrapperformodule(module, lrp_params, lrp_layer2method, thisis_inputconv_andiwant_zbeta=False):
if isinstance(module, nn.ReLU):
#return zeroparam_wrapper_class( module , relu_wrapper_fct() )
key='nn.ReLU'
if key not in lrp_layer2method:
print("found no dictionary entry in lrp_layer2method for this module name:", key)
raise lrplookupnotfounderror( "found no dictionary entry in lrp_layer2method for this module name:", key)
#default relu_wrapper_fct()
autogradfunction = lrp_layer2method[key]()
return zeroparam_wrapper_class( module , autogradfunction= autogradfunction )
elif isinstance(module, nn.BatchNorm2d):
key='nn.BatchNorm2d'
if key not in lrp_layer2method:
print("found no dictionary entry in lrp_layer2method for this module name:", key)
raise lrplookupnotfounderror( "found no dictionary entry in lrp_layer2method for this module name:", key)
#default relu_wrapper_fct()
autogradfunction = lrp_layer2method[key]()
return zeroparam_wrapper_class( module , autogradfunction= autogradfunction )
elif isinstance(module, nn.Linear):
key='nn.Linear'
if key not in lrp_layer2method:
print("found no dictionary entry in lrp_layer2method for this module name:", key)
raise lrplookupnotfounderror( "found no dictionary entry in lrp_layer2method for this module name:", key)
#default linearlayer_eps_wrapper_fct()
autogradfunction = lrp_layer2method[key]()
return oneparam_wrapper_class( module , autogradfunction = autogradfunction, parameter1 = lrp_params['linear_eps'] )
elif isinstance(module, nn.Conv2d):
if True== thisis_inputconv_andiwant_zbeta:
return conv2d_zbeta_wrapper_class(module , lrp_params['conv2d_ignorebias'])
else:
key='nn.Conv2d'
if key not in lrp_layer2method:
print("found no dictionary entry in lrp_layer2method for this module name:", key)
raise lrplookupnotfounderror( "found no dictionary entry in lrp_layer2method for this module name:", key)
#default conv2d_beta0_wrapper_fct()
#autogradfunction = lrp_layer2method[key]()
#return oneparam_wrapper_class(module, autogradfunction = autogradfunction, parameter1 = lrp_params['conv2d_ignorebias'] )
autogradfunction = lrp_layer2method[key]()
if type(autogradfunction) == conv2d_beta0_wrapper_fct: # dont want test for derived classes but equality
return oneparam_wrapper_class(module, autogradfunction = autogradfunction, parameter1 = lrp_params['conv2d_ignorebias'] )
elif type(autogradfunction) == conv2d_betaany_wrapper_fct:
return twoparam_wrapper_class(module, autogradfunction = autogradfunction, parameter1 = lrp_params['conv2d_ignorebias'], parameter2 = torch.tensor( lrp_params['conv2d_beta']) )
elif type(autogradfunction) == conv2d_betaadaptive_wrapper_fct:
return twoparam_wrapper_class(module, autogradfunction = autogradfunction, parameter1 = lrp_params['conv2d_ignorebias'], parameter2 = torch.tensor( lrp_params['conv2d_maxbeta']) )
else:
print('unknown autogradfunction', type(autogradfunction) )
exit()
elif isinstance(module, nn.AdaptiveAvgPool2d):
key='nn.AdaptiveAvgPool2d'
if key not in lrp_layer2method:
print("found no dictionary entry in lrp_layer2method for this module name:", key)
raise lrplookupnotfounderror( "found no dictionary entry in lrp_layer2method for this module name:", key)
#default adaptiveavgpool2d_wrapper_fct()
autogradfunction = lrp_layer2method[key]()
return oneparam_wrapper_class( module , autogradfunction = autogradfunction, parameter1 = lrp_params['pooling_eps'] )
elif isinstance(module, nn.AvgPool2d):
key='nn.AvgPool2d'
if key not in lrp_layer2method:
print("found no dictionary entry in lrp_layer2method for this module name:", key)
raise lrplookupnotfounderror( "found no dictionary entry in lrp_layer2method for this module name:", key)
#default adaptiveavgpool2d_wrapper_fct()
autogradfunction = lrp_layer2method[key]()
return oneparam_wrapper_class( module , autogradfunction = autogradfunction, parameter1 = lrp_params['pooling_eps'] )
elif isinstance(module, nn.MaxPool2d):
key='nn.MaxPool2d'
if key not in lrp_layer2method:
print("found no dictionary entry in lrp_layer2method for this module name:", key)
raise lrplookupnotfounderror( "found no dictionary entry in lrp_layer2method for this module name:", key)
#default maxpool2d_wrapper_fct()
autogradfunction = lrp_layer2method[key]()
return zeroparam_wrapper_class( module , autogradfunction = autogradfunction )
elif isinstance(module, sum_stacked2): # resnet specific
key='sum_stacked2'
if key not in lrp_layer2method:
print("found no dictionary entry in lrp_layer2method for this module name:", key)
raise lrplookupnotfounderror( "found no dictionary entry in lrp_layer2method for this module name:", key)
#default eltwisesum_stacked2_eps_wrapper_fct()
autogradfunction = lrp_layer2method[key]()
return oneparam_wrapper_class( module , autogradfunction = autogradfunction, parameter1 = lrp_params['eltwise_eps'] )
elif isinstance(module, clamplayer): # densenet specific
key='clamplayer'
if key not in lrp_layer2method:
print("found no dictionary entry in lrp_layer2method for this module name:", key)
raise lrplookupnotfounderror( "found no dictionary entry in lrp_layer2method for this module name:", key)
#default relu_wrapper_fct()
autogradfunction = lrp_layer2method[key]()
return zeroparam_wrapper_class( module , autogradfunction = autogradfunction)
elif isinstance(module, tensorbiased_linearlayer): # densenet specific
key='tensorbiased_linearlayer'
if key not in lrp_layer2method:
print("found no dictionary entry in lrp_layer2method for this module name:", key)
raise lrplookupnotfounderror( "found no dictionary entry in lrp_layer2method for this module name:", key)
#default relu_wrapper_fct()
autogradfunction = lrp_layer2method[key]()
return oneparam_wrapper_class( module , autogradfunction = autogradfunction, parameter1 = lrp_params['linear_eps'] )
elif isinstance(module, tensorbiased_convlayer): # densenet specific
key='tensorbiased_convlayer'
if key not in lrp_layer2method:
print("found no dictionary entry in lrp_layer2method for this module name:", key)
raise lrplookupnotfounderror( "found no dictionary entry in lrp_layer2method for this module name:", key)
#default relu_wrapper_fct()
autogradfunction = lrp_layer2method[key]()
return oneparam_wrapper_class( module , autogradfunction = autogradfunction, parameter1 = lrp_params['conv2d_ignorebias'] )
else:
print("found no lookup for this module:", module)
raise lrplookupnotfounderror( "found no lookup for this module:", module)
#######################################################
#######################################################
#canonization functions
#######################################################
#######################################################
def resetbn(bn):
assert (isinstance(bn,nn.BatchNorm2d))
bnc=copy.deepcopy(bn)
bnc.reset_parameters()
return bnc
#vanilla fusion conv-bn --> conv(updatedparams)
def bnafterconv_overwrite_intoconv(conv,bn): #after visatt
print(conv,bn)
assert (isinstance(bn,nn.BatchNorm2d))
assert (isinstance(conv,nn.Conv2d))
s = (bn.running_var+bn.eps)**.5
w = bn.weight
b = bn.bias
m = bn.running_mean
conv.weight = torch.nn.Parameter(conv.weight * (w / s).reshape(-1, 1, 1, 1))
#print( 'w/s, conv.bias', (w/s), conv.bias )
if conv.bias is None:
conv.bias = torch.nn.Parameter((0 - m) * (w / s) + b)
else:
conv.bias = torch.nn.Parameter(( conv.bias - m) * (w / s) + b)
#print( ' conv.bias new', conv.bias )
return conv
def getclamplayer(bn):
assert (isinstance(bn,nn.BatchNorm2d))
var_bn = (bn.running_var+bn.eps)**.5
w_bn = bn.weight
bias_bn = bn.bias
mu_bn = bn.running_mean
if torch.norm(w_bn) > 0:
thresh = -bias_bn * var_bn / w_bn + mu_bn
clamplay = clamplayer( thresh ,torch.sign(w_bn) , forconv = True )
else:
print('bad case, not (torch.norm(w_bn) > 0), exiting, see lrp_general*.py, you can outcomment the exit(), but it means that your batchnorm layer is messed up.')
exit()
if (bias_bn < 0): # never activated
thresh = 0
clamplay = clamplayer_const( thresh , forconv = True )
else:
thresh = bias_bn # never activated always fires the bias
spec = True
clamplay = clamplayer_const( thresh , forconv = True )
return clamplay
# for fusion of bn-conv into conv with tensor shaped bias
def convafterbn_returntensorbiasedconv(conv,bn): #after visatt
# y= w_{bn} (x-mu_{bn}) / vareps + b_{bn}
# y= w_{bn} / vareps x - w_{bn} / vareps * mu_{bn} + b_{bn}
# conv(y) = w y +b = w ( w_{bn} / vareps) x + w ( - w_{bn} / vareps * mu_{bn} + b_{bn} ) +b
# conv(y) = w ( w_{bn} / vareps).reshape((-1,1,1,1)) x + conv ( - w_{bn} / vareps * mu_{bn} + b_{bn} )
# the latter as bias for mu_{bn}, b_{bn} as ksize shaped tensors
assert (isinstance(bn,nn.BatchNorm2d))
assert (isinstance(conv,nn.Conv2d))
var_bn = (bn.running_var.clone().detach()+bn.eps)**.5
w_bn = bn.weight.clone().detach()
bias_bn = bn.bias.clone().detach()
mu_bn = bn.running_mean.clone().detach()
newweight=conv.weight.clone().detach() * (w_bn / var_bn).reshape(1, conv.weight.shape[1], 1, 1)
inputfornewbias= - (w_bn / var_bn * mu_bn)+ bias_bn #size [nchannels]
# can consider to always return tensorbiased ...
if conv.padding==0:
ksize=( conv.weight.shape[2], conv.weight.shape[3] )
inputfornewbias2=inputfornewbias.unsqueeze(1).unsqueeze(2).repeat((1, ksize[0] , ksize[1])).unsqueeze(0) # shape (1, 64, ksize,ksize)
#print (inputfornewbias.shape)
with torch.no_grad():
prebias= conv( inputfornewbias2 )
# in case of padding, the result might be not (1,nch,1,1)
mi = ( ( prebias.shape[2]-1)//2 , ( prebias.shape[3]-1)//2 )
prebias= prebias.clone().detach()
newconv_bias= prebias[0,:,mi[0],mi[1]]
conv2=copy.deepcopy(conv)
conv2.weight = torch.nn.Parameter( newweight )
conv2.bias = torch.nn.Parameter( newconv_bias)
return conv2
else:
#bias is a tensor! if there is padding
spatiallybiasedconv= tensorbiased_convlayer(newweight, conv,inputfornewbias.clone().detach())
return spatiallybiasedconv
# for fusion of bn-linear into linear with tensor shaped bias
def linearafterbn_returntensorbiasedlinearlayer(linearlayer,bn): #after visatt
assert (isinstance(bn,nn.BatchNorm2d))
assert (isinstance(linearlayer,nn.Linear))
var_bn = (bn.running_var+bn.eps)**.5
w_bn = bn.weight
bias_bn = bn.bias
mu_bn = bn.running_mean
newweight = torch.nn.Parameter(linearlayer.weight.clone().detach() * (w_bn / var_bn))
inputfornewbias= - (w_bn / var_bn * mu_bn)+ bias_bn #size [nchannels]
inputfornewbias= inputfornewbias.detach()
with torch.no_grad():
newbias= linearlayer.forward( inputfornewbias )
#print(newbias.shape, newbias.numel(),linearlayer.out_features)
#exit()
tensorbias_linearlayer = tensorbiased_linearlayer(linearlayer.in_features, linearlayer.out_features , newweight, newbias.data)
return tensorbias_linearlayer
#resnet stuff
###########################################################
#########################################################
###########################################################
#for resnet shortcut / residual connections
class eltwisesum2(nn.Module): # see torchray excitation backprop, using *inputs
def __init__(self):
super(eltwisesum2, self).__init__()
def forward(self, x1,x2):
return x1+x2
#densenet stuff
###########################################################
#########################################################
###########################################################
#bad name actually, threshrelu would be better
class clamplayer(nn.Module):
def __init__(self,thresh, w_bn_sign, forconv):
super(clamplayer,self).__init__()
# thresh will be -b_bn*vareps / w_bn + mu_bn
if True == forconv:
self.thresh = thresh.reshape((-1,1,1))
self.w_bn_sign = w_bn_sign.reshape((-1,1,1))
else:
# for linear that should be ok
self.thresh = thresh
self.w_bn_sign = w_bn_sign
def forward(self,x):
# for channels c with w_bn > 0 -- as checked by (self.w_bn_sign>0)
# return (x- self.thresh ) * (x>self.thresh) + self.thresh
#
# for channels c with w_bn < 0
# return thresh if (x>=self.thresh), x if (x < self. thresh)
# return (x- self.thresh ) * (x<self.thresh) + self.thresh
return (x- self.thresh ) * ( (x>self.thresh)* (self.w_bn_sign>0) + (x<self.thresh)* (self.w_bn_sign<0) ) + self.thresh
class tensorbiased_linearlayer(nn.Module):
def __init__(self, in_features, out_features , newweight, newbias ):
super(tensorbiased_linearlayer,self).__init__()
assert( newbias.numel()== out_features )
self.linearbase=nn.Linear(in_features, out_features, bias=False)
self.linearbase.weight = torch.nn.Parameter(newweight)
self.biastensor = torch.nn.Parameter(newbias)
# this is pure convenience
self.in_features= in_features
self.out_features= out_features
def forward(self,x):
y= self.linearbase.forward(x) + self.biastensor
return y
class tensorbiased_convlayer(nn.Module):
def _clone_module(self, module):
clone = nn.Conv2d(module.in_channels, module.out_channels, module.kernel_size,
**{attr: getattr(module, attr) for attr in ['stride', 'padding', 'dilation', 'groups']})
return clone.to(module.weight.device)
def __init__(self, newweight, baseconv, inputfornewbias):
super(tensorbiased_convlayer, self).__init__()
self.baseconv=baseconv #evtl store weights, clone mod
self.inputfornewbias=inputfornewbias
self.conv= self._clone_module(baseconv)
self.conv.weight = torch.nn.Parameter(newweight)
self.conv.bias=None
self.biasmode='neutr'
def gettensorbias(self,x):
with torch.no_grad():
tensorbias= self.baseconv( self.inputfornewbias.unsqueeze(1).unsqueeze(2).repeat((1, x.shape[2] , x.shape[3])).unsqueeze(0) )
print('done tensorbias', tensorbias.shape)
return tensorbias
def forward(self,x):
#self.input=(x)
print('tensorbias fwd', x.shape)
if len(x.shape)!=4:
print('bad tensor length')
exit()
if self.inputfornewbias is not None:
print ( 'self.inputfornewbias.shape',self.inputfornewbias.shape)
else:
print ( 'self.inputfornewbias',self.inputfornewbias)
#z= self.conv.forward(x)
#print('z.shape',z.shape)
if self.inputfornewbias is None:
return self.conv.forward(x) #z
else:
b= self.gettensorbias(x)
if self.biasmode=='neutr':
#z+=b
return self.conv.forward(x) +b
elif self.biasmode=='pos':
#z+= torch.clamp(b,min=0)
return self.conv.forward(x) +torch.clamp(b,min=0) #z
elif self.biasmode=='neg':
#z+= torch.clamp(b,max=0)
return self.conv.forward(x) +torch.clamp(b,max=0) #z
#######################################################
#######################################################
#######################################################
#######################################################
#######################################################
#######################################################
#######################################################
#######################################################
# autograd type modules
#######################################################
#######################################################
class conv2d_beta0_wrapper_fct(torch.autograd.Function):
"""
We can implement our own custom autograd Functions by subclassing
torch.autograd.Function and implementing the forward and backward passes
which operate on Tensors.
"""
@staticmethod
def forward(ctx, x, module, lrpignorebias):
"""
In the forward pass we receive a Tensor containing the input and return
a Tensor containing the output. ctx is a context object that can be used
to stash information for backward computation. You can cache arbitrary
objects for use in the backward pass using the ctx.save_for_backward method.
"""
def configvalues_totensorlist(module):
#[module.in_channels, module.out_channels, module.kernel_size, **{attr: getattr(module, attr) for attr in ['stride', 'padding', 'dilation', 'groups']}
propertynames=['in_channels', 'out_channels', 'kernel_size', 'stride', 'padding', 'dilation', 'groups']
values=[]
for attr in propertynames:
v = getattr(module, attr)
# convert it into tensor
# has no treatment for booleans yet
if isinstance(v, int):
v= torch.tensor([v], dtype=torch.int32, device= module.weight.device)
elif isinstance(v, tuple):
################
################
# FAILMODE: if it is not a tuple of ints but e.g. a tuple of floats, or a tuple of a tuple
v= torch.tensor(v, dtype=torch.int32, device= module.weight.device)
else:
print('v is neither int nor tuple. unexpected')
exit()
values.append(v)
return propertynames,values
### end of def classproperties2lists(conv2dclass): #####################
#stash module config params and trainable params
propertynames,values=configvalues_totensorlist(module)
if module.bias is None:
bias=None
else:
bias= module.bias.data.clone()
lrpignorebiastensor=torch.tensor([lrpignorebias], dtype=torch.bool, device= module.weight.device)
ctx.save_for_backward(x, module.weight.data.clone(), bias, lrpignorebiastensor, *values ) # *values unpacks the list
#print('ctx.needs_input_grad',ctx.needs_input_grad)
#exit()
#print('conv2d custom forward')
return module.forward(x)
@staticmethod
def backward(ctx, grad_output):
"""
In the backward pass we receive a Tensor containing the gradient of the loss
with respect to the output, and we need to compute the gradient of the loss
with respect to the input.
"""
#print('len(grad_output)',len(grad_output),grad_output[0].shape)
input_, conv2dweight, conv2dbias, lrpignorebiastensor, *values = ctx.saved_tensors
#print('retrieved', len(values))
#######################################################################
# reconstruct dictionary of config parameters
def tensorlist_todict(values):
propertynames=['in_channels', 'out_channels', 'kernel_size', 'stride', 'padding', 'dilation', 'groups']
# idea: paramsdict={ n: values[i] for i,n in enumerate(propertynames) } # but needs to turn tensors to ints or tuples!
paramsdict={}
for i,n in enumerate(propertynames):
v=values[i]
if v.numel==1:
paramsdict[n]=v.item() #to cpu?
else:
alist=v.tolist()
#print('alist',alist)
if len(alist)==1:
paramsdict[n]=alist[0]
else:
paramsdict[n]= tuple(alist)
return paramsdict
#######################################################################
paramsdict=tensorlist_todict(values)
if conv2dbias is None:
module=nn.Conv2d( **paramsdict, bias=False )
else:
module=nn.Conv2d( **paramsdict, bias=True )
module.bias= torch.nn.Parameter(conv2dbias)
#print('conv2dconstr')
module.weight= torch.nn.Parameter(conv2dweight)
#print('conv2dconstr weights')
pnconv = posnegconv(module, ignorebias = lrpignorebiastensor.item())
#print('conv2d custom input_.shape', input_.shape )
X = input_.clone().detach().requires_grad_(True)
R= lrp_backward(_input= X , layer = pnconv , relevance_output = grad_output, eps0 = 1e-12, eps=0)
#R= lrp_backward(_input= X , layer = pnconv , relevance_output = torch.ones_like(grad_output), eps0 = 1e-12, eps=0)
#print( 'beta 0 negR' ,torch.mean((R<0).float()).item() ) # no neg relevance
#print('conv2d custom R', R.shape )
#exit()
return R,None, None
class conv2d_zbeta_wrapper_fct(torch.autograd.Function):
"""
We can implement our own custom autograd Functions by subclassing
torch.autograd.Function and implementing the forward and backward passes
which operate on Tensors.
"""
@staticmethod
def forward(ctx, x, module, lrpignorebias, lowest, highest):
"""
In the forward pass we receive a Tensor containing the input and return
a Tensor containing the output. ctx is a context object that can be used
to stash information for backward computation. You can cache arbitrary
objects for use in the backward pass using the ctx.save_for_backward method.
"""
def configvalues_totensorlist(module):
#[module.in_channels, module.out_channels, module.kernel_size, **{attr: getattr(module, attr) for attr in ['stride', 'padding', 'dilation', 'groups']}
propertynames=['in_channels', 'out_channels', 'kernel_size', 'stride', 'padding', 'dilation', 'groups']
values=[]
for attr in propertynames:
v = getattr(module, attr)
# convert it into tensor
# has no treatment for booleans yet
if isinstance(v, int):
v= torch.tensor([v], dtype=torch.int32, device= module.weight.device)
elif isinstance(v, tuple):
################
################
# FAILMODE: if it is not a tuple of ints but e.g. a tuple of floats, or a tuple of a tuple
v= torch.tensor(v, dtype=torch.int32, device= module.weight.device)
else:
print('v is neither int nor tuple. unexpected')
exit()
values.append(v)
return propertynames,values
### end of def classproperties2lists(conv2dclass): #####################
#stash module config params and trainable params
propertynames,values=configvalues_totensorlist(module)
if module.bias is None:
bias=None
else:
bias= module.bias.data.clone()
lrpignorebiastensor=torch.tensor([lrpignorebias], dtype=torch.bool, device= module.weight.device)
ctx.save_for_backward(x, module.weight.data.clone(), bias, lrpignorebiastensor, lowest.to(module.weight.device), highest.to(module.weight.device), *values ) # *values unpacks the list
#print('ctx.needs_input_grad',ctx.needs_input_grad)
#exit()
#print('conv2d zbeta custom forward')
return module.forward(x)
@staticmethod
def backward(ctx, grad_output):
"""
In the backward pass we receive a Tensor containing the gradient of the loss
with respect to the output, and we need to compute the gradient of the loss
with respect to the input.
"""
#print('len(grad_output)',len(grad_output),grad_output[0].shape)
input_, conv2dweight, conv2dbias, lrpignorebiastensor, lowest_, highest_, *values = ctx.saved_tensors
#print('retrieved', len(values))
#######################################################################
# reconstruct dictionary of config parameters
def tensorlist_todict(values):
propertynames=['in_channels', 'out_channels', 'kernel_size', 'stride', 'padding', 'dilation', 'groups']
# idea: paramsdict={ n: values[i] for i,n in enumerate(propertynames) } # but needs to turn tensors to ints or tuples!
paramsdict={}
for i,n in enumerate(propertynames):
v=values[i]
if v.numel==1:
paramsdict[n]=v.item() #to cpu?
else:
alist=v.tolist()
#print('alist',alist)
if len(alist)==1:
paramsdict[n]=alist[0]
else:
paramsdict[n]= tuple(alist)
return paramsdict
#######################################################################
paramsdict=tensorlist_todict(values)
if conv2dbias is None:
module=nn.Conv2d( **paramsdict, bias=False )
else:
module=nn.Conv2d( **paramsdict, bias=True )
module.bias= torch.nn.Parameter(conv2dbias)
#print('conv2dconstr')
module.weight= torch.nn.Parameter(conv2dweight)
print('zbeta conv2dconstr weights')
any_conv = anysign_conv( module, ignorebias=lrpignorebiastensor.item())
X = input_.clone().detach().requires_grad_(True)
L = (lowest_ * torch.ones_like(X)).requires_grad_(True)
H = (highest_ * torch.ones_like(X)).requires_grad_(True)
with torch.enable_grad():
Z = any_conv.forward(mode='justasitis', x=X) - any_conv.forward(mode='pos', x=L) - any_conv.forward(mode='neg', x=H)
S = safe_divide(grad_output.clone().detach(), Z.clone().detach(), eps0=1e-6, eps=1e-6)
Z.backward(S)
R = (X * X.grad + L * L.grad + H * H.grad).detach()
print('zbeta conv2d custom R', R.shape )
#exit()
return R,None,None,None, None # for (x, conv2dclass,lrpignorebias, lowest, highest)
class conv2d_betaadaptive_wrapper_fct(torch.autograd.Function):
"""
We can implement our own custom autograd Functions by subclassing
torch.autograd.Function and implementing the forward and backward passes
which operate on Tensors.
"""
@staticmethod
def forward(ctx, x, module, lrpignorebias, maxbeta):
"""
In the forward pass we receive a Tensor containing the input and return
a Tensor containing the output. ctx is a context object that can be used
to stash information for backward computation. You can cache arbitrary
objects for use in the backward pass using the ctx.save_for_backward method.
"""
def configvalues_totensorlist(module):
#[module.in_channels, module.out_channels, module.kernel_size, **{attr: getattr(module, attr) for attr in ['stride', 'padding', 'dilation', 'groups']}
propertynames=['in_channels', 'out_channels', 'kernel_size', 'stride', 'padding', 'dilation', 'groups']
values=[]
for attr in propertynames:
v = getattr(module, attr)
# convert it into tensor
# has no treatment for booleans yet
if isinstance(v, int):
v= torch.tensor([v], dtype=torch.int32, device= module.weight.device)
elif isinstance(v, tuple):
################
################
# FAILMODE: if it is not a tuple of ints but e.g. a tuple of floats, or a tuple of a tuple
v= torch.tensor(v, dtype=torch.int32, device= module.weight.device)
else:
print('v is neither int nor tuple. unexpected')
exit()
values.append(v)
return propertynames,values
### end of def classproperties2lists(conv2dclass): #####################
#stash module config params and trainable params
propertynames,values=configvalues_totensorlist(module)
if module.bias is None:
bias=None
else:
bias= module.bias.data.clone()
lrpignorebiastensor=torch.tensor([lrpignorebias], dtype=torch.bool, device= module.weight.device)
ctx.save_for_backward(x, module.weight.data.clone(), bias, lrpignorebiastensor, maxbeta, *values ) # *values unpacks the list
#print('ctx.needs_input_grad',ctx.needs_input_grad)
#exit()
#print('conv2d custom forward')
return module.forward(x)
@staticmethod
def backward(ctx, grad_output):
"""
In the backward pass we receive a Tensor containing the gradient of the loss
with respect to the output, and we need to compute the gradient of the loss
with respect to the input.
"""
#print('len(grad_output)',len(grad_output),grad_output[0].shape)
input_, conv2dweight, conv2dbias, lrpignorebiastensor, maxbeta, *values = ctx.saved_tensors
#print('retrieved', len(values))
#######################################################################
# reconstruct dictionary of config parameters
def tensorlist_todict(values):
propertynames=['in_channels', 'out_channels', 'kernel_size', 'stride', 'padding', 'dilation', 'groups']
# idea: paramsdict={ n: values[i] for i,n in enumerate(propertynames) } # but needs to turn tensors to ints or tuples!
paramsdict={}
for i,n in enumerate(propertynames):
v=values[i]
if v.numel==1:
paramsdict[n]=v.item() #to cpu?
else:
alist=v.tolist()
#print('alist',alist)
if len(alist)==1:
paramsdict[n]=alist[0]
else:
paramsdict[n]= tuple(alist)
return paramsdict
#######################################################################
paramsdict=tensorlist_todict(values)
if conv2dbias is None:
module=nn.Conv2d( **paramsdict, bias=False )
else:
module=nn.Conv2d( **paramsdict, bias=True )
module.bias= torch.nn.Parameter(conv2dbias)
#print('conv2dconstr')
module.weight= torch.nn.Parameter(conv2dweight)
#print('conv2dconstr weights')
pnconv = posnegconv(module, ignorebias = lrpignorebiastensor.item())
invertedpnconv = invertedposnegconv(module, ignorebias = lrpignorebiastensor.item())
#print('get ratios per output')
# betatensor = -neg / conv but care for zeros
X = input_.clone().detach()
out = module(X)
negscores = -invertedpnconv(X)
betatensor = torch.zeros_like(out)
betatensor[ out>0 ] = torch.minimum( negscores[ out>0 ] / out [ out>0 ], maxbeta)
X.requires_grad_(True)
R1= lrp_backward(_input= X , layer = pnconv , relevance_output = grad_output * (1+betatensor), eps0 = 1e-12, eps=0)
R2= lrp_backward(_input= X , layer = invertedpnconv , relevance_output = grad_output * betatensor, eps0 = 1e-12, eps=0)
R = R1 -R2
return R, None, None, None
class adaptiveavgpool2d_wrapper_fct(torch.autograd.Function):
"""
We can implement our own custom autograd Functions by subclassing
torch.autograd.Function and implementing the forward and backward passes
which operate on Tensors.
"""
@staticmethod
def forward(ctx, x, module, eps):
"""
In the forward pass we receive a Tensor containing the input and return
a Tensor containing the output. ctx is a context object that can be used
to stash information for backward computation. You can cache arbitrary
objects for use in the backward pass using the ctx.save_for_backward method.
"""
def configvalues_totensorlist(module,device):
propertynames=['output_size']
values=[]
for attr in propertynames:
v = getattr(module, attr)
# convert it into tensor
# has no treatment for booleans yet
if isinstance(v, int):
v= torch.tensor([v], dtype=torch.int32, device= device)
elif isinstance(v, tuple):
################
################
# FAILMODE: if it is not a tuple of ints but e.g. a tuple of floats, or a tuple of a tuple
v= torch.tensor(v, dtype=torch.int32, device= device)
else:
print('v is neither int nor tuple. unexpected')
exit()
values.append(v)
return propertynames,values
### end of def classproperties2lists(conv2dclass): #####################
#stash module config params and trainable params
propertynames,values=configvalues_totensorlist(module,x.device)
epstensor = torch.tensor([eps], dtype=torch.float32, device= x.device)
ctx.save_for_backward(x, epstensor, *values ) # *values unpacks the list
print('ctx.needs_input_grad',ctx.needs_input_grad)
#exit()
print('sdaptiveavg2d custom forward')
return module.forward(x)
@staticmethod
def backward(ctx, grad_output):
"""
In the backward pass we receive a Tensor containing the gradient of the loss
with respect to the output, and we need to compute the gradient of the loss
with respect to the input.
"""
#print('len(grad_output)',len(grad_output),grad_output[0].shape)
input_, epstensor, *values = ctx.saved_tensors
print('retrieved', len(values))
#######################################################################
# reconstruct dictionary of config parameters
def tensorlist_todict(values):
propertynames=['output_size']
# idea: paramsdict={ n: values[i] for i,n in enumerate(propertynames) } # but needs to turn tensors to ints or tuples!
paramsdict={}
for i,n in enumerate(propertynames):
v=values[i]
if v.numel==1:
paramsdict[n]=v.item() #to cpu?
else:
alist=v.tolist()
#print('alist',alist)
if len(alist)==1:
paramsdict[n]=alist[0]
else:
paramsdict[n]= tuple(alist)
return paramsdict
#######################################################################
paramsdict=tensorlist_todict(values)
eps=epstensor.item()
#class instantiation
layerclass= torch.nn.AdaptiveAvgPool2d(**paramsdict)
print('adaptiveavg2d custom input_.shape', input_.shape )
X = input_.clone().detach().requires_grad_(True)
R= lrp_backward(_input= X , layer = layerclass , relevance_output = grad_output, eps0 = eps, eps=eps)
print('adaptiveavg2dcustom R', R.shape )
#exit()
return R,None,None
class maxpool2d_wrapper_fct(torch.autograd.Function):
"""
We can implement our own custom autograd Functions by subclassing
torch.autograd.Function and implementing the forward and backward passes
which operate on Tensors.
"""
@staticmethod
def forward(ctx, x, module):
"""
In the forward pass we receive a Tensor containing the input and return
a Tensor containing the output. ctx is a context object that can be used
to stash information for backward computation. You can cache arbitrary
objects for use in the backward pass using the ctx.save_for_backward method.
"""
def configvalues_totensorlist(module,device):
propertynames=['kernel_size','stride','padding','dilation','return_indices','ceil_mode']
values=[]
for attr in propertynames:
v = getattr(module, attr)
# convert it into tensor
# has no treatment for booleans yet
if isinstance(v, bool):
v= torch.tensor([v], dtype=torch.bool, device= device)
elif isinstance(v, int):
v= torch.tensor([v], dtype=torch.int32, device= device)
elif isinstance(v, bool):
v= torch.tensor([v], dtype=torch.int32, device= device)
elif isinstance(v, tuple):
################
################
# FAILMODE: if it is not a tuple of ints but e.g. a tuple of floats, or a tuple of a tuple