|
| 1 | +"""Module-level LRP rule wrappers (relevance-as-gradient convention). |
| 2 | +
|
| 3 | +Small, dependency-free counterparts of LXT's ``EpsilonRule`` / ``IdentityRule`` |
| 4 | +module wrappers: they replace a module in the tree, reproduce its forward |
| 5 | +exactly, and substitute the backward with the LRP rule. |
| 6 | +
|
| 7 | +* :class:`EpsilonRule` — ε-LRP through a module that is **linear in its input** |
| 8 | + (``Linear``, ``Conv*``, eval-mode ``BatchNorm``, PhysioEx's |
| 9 | + ``LearnableFilterbank``): ``R_x = x ⊙ Jᵀ(R_y / (y ± ε))`` computed with a |
| 10 | + vector-Jacobian product, so any such module is handled without knowing its |
| 11 | + weights layout. Bias relevance is absorbed (standard LRP-ε). |
| 12 | +* :class:`IdentityRule` — relevance passes through unchanged (LayerNorm, |
| 13 | + GroupNorm, element-wise activations; shape-preserving modules only). |
| 14 | +""" |
| 15 | + |
| 16 | +from __future__ import annotations |
| 17 | + |
| 18 | +import torch |
| 19 | +import torch.nn as nn |
| 20 | + |
| 21 | +from physioex.explain.lrp._functional import stabilize, st_identity |
| 22 | + |
| 23 | + |
| 24 | +class _RuleWrapper(nn.Module): |
| 25 | + """Base class: holds the wrapped ``module`` (frozen).""" |
| 26 | + |
| 27 | + def __init__(self, module: nn.Module): |
| 28 | + super().__init__() |
| 29 | + self.module = module |
| 30 | + for p in module.parameters(): |
| 31 | + p.requires_grad_(False) |
| 32 | + |
| 33 | + def extra_repr(self) -> str: # pragma: no cover - repr only |
| 34 | + return "" |
| 35 | + |
| 36 | + |
| 37 | +class _EpsilonVJP(torch.autograd.Function): |
| 38 | + @staticmethod |
| 39 | + def forward(ctx, x, module, epsilon): |
| 40 | + y = module(x) |
| 41 | + ctx.module, ctx.epsilon = module, epsilon |
| 42 | + ctx.save_for_backward(x, y) |
| 43 | + return y |
| 44 | + |
| 45 | + @staticmethod |
| 46 | + def backward(ctx, relevance): |
| 47 | + x, y = ctx.saved_tensors |
| 48 | + s = relevance / stabilize(y, ctx.epsilon) |
| 49 | + with torch.enable_grad(): |
| 50 | + x_ = x.detach().requires_grad_(True) |
| 51 | + (grad,) = torch.autograd.grad(ctx.module(x_), x_, s) |
| 52 | + return x * grad, None, None |
| 53 | + |
| 54 | + |
| 55 | +class EpsilonRule(_RuleWrapper): |
| 56 | + """ε-LRP wrapper for a single-input module linear in its input.""" |
| 57 | + |
| 58 | + def __init__(self, module: nn.Module, epsilon: float = 1e-6): |
| 59 | + super().__init__(module) |
| 60 | + self.epsilon = float(epsilon) |
| 61 | + |
| 62 | + def forward(self, x): |
| 63 | + return _EpsilonVJP.apply(x, self.module, self.epsilon) |
| 64 | + |
| 65 | + |
| 66 | +class IdentityRule(_RuleWrapper): |
| 67 | + """Identity-rule wrapper: forward is the module's, backward passes relevance.""" |
| 68 | + |
| 69 | + def forward(self, x, *args, **kwargs): |
| 70 | + return st_identity(x, self.module(x, *args, **kwargs)) |
0 commit comments