|
| 1 | +"""End-to-end LRP for whole PhysioEx models (Phase 2c wiring). |
| 2 | +
|
| 3 | +:func:`prepare_model_for_lrp` swaps every fused / attention block in a model for |
| 4 | +its relevance-carrying counterpart: |
| 5 | +
|
| 6 | +* ``nn.LSTM`` / ``nn.GRU`` → :class:`LRPLSTM` / :class:`LRPGRU` |
| 7 | +* ``nn.TransformerEncoder(Layer)`` → the ``transformer`` LRP versions |
| 8 | +* ``nn.MultiheadAttention`` → :class:`LRPMultiheadAttention` |
| 9 | +* custom softmax pooling (matched by class name ``AttentionPooling`` / |
| 10 | + ``AttentionLayer``) → the ``pooling`` CP-LRP versions |
| 11 | +* remaining leaf ``Linear`` / ``Conv`` / ``BatchNorm`` → LXT ``EpsilonRule`` |
| 12 | +* standalone ``LayerNorm`` → LXT ``IdentityRule`` |
| 13 | +
|
| 14 | +:class:`ModelLRP` deep-copies the trained model, prepares it, then runs a forward |
| 15 | +plus a target-seeded backward, returning relevance shaped like the input. |
| 16 | +
|
| 17 | +Requires the ``explain`` extra (``lxt``). |
| 18 | +""" |
| 19 | + |
| 20 | +from __future__ import annotations |
| 21 | + |
| 22 | +import copy |
| 23 | + |
| 24 | +import torch |
| 25 | +import torch.nn as nn |
| 26 | + |
| 27 | +from physioex.explain.lrp.pooling import LRPAttentionLayer, LRPAttentionPooling |
| 28 | +from physioex.explain.lrp.recurrent import LRPGRU, LRPLSTM |
| 29 | +from physioex.explain.lrp.transformer import ( |
| 30 | + LRPMultiheadAttention, |
| 31 | + LRPTransformerEncoder, |
| 32 | + LRPTransformerEncoderLayer, |
| 33 | +) |
| 34 | + |
| 35 | +# custom pooling classes are matched by name to avoid importing the model modules |
| 36 | +_POOLING_BY_NAME = { |
| 37 | + "AttentionPooling": LRPAttentionPooling, |
| 38 | + "AttentionLayer": LRPAttentionLayer, |
| 39 | +} |
| 40 | + |
| 41 | + |
| 42 | +def prepare_model_for_lrp(model: nn.Module, epsilon: float = 1e-6) -> nn.Module: |
| 43 | + """In-place: replace fused/attention blocks with their LRP counterparts and |
| 44 | + wrap remaining linear leaves with LXT rules. Returns ``model``. |
| 45 | +
|
| 46 | + Call on a copy (see :class:`ModelLRP`) — it mutates the module tree. |
| 47 | + """ |
| 48 | + from lxt.explicit.rules import EpsilonRule, IdentityRule |
| 49 | + |
| 50 | + for name, child in list(model.named_children()): |
| 51 | + cname = type(child).__name__ |
| 52 | + if isinstance(child, nn.LSTM): |
| 53 | + setattr(model, name, LRPLSTM.from_torch(child)) |
| 54 | + elif isinstance(child, nn.GRU): |
| 55 | + setattr(model, name, LRPGRU.from_torch(child)) |
| 56 | + elif isinstance(child, nn.TransformerEncoder): |
| 57 | + setattr(model, name, LRPTransformerEncoder.from_torch(child)) |
| 58 | + elif isinstance(child, nn.TransformerEncoderLayer): |
| 59 | + setattr(model, name, LRPTransformerEncoderLayer.from_torch(child)) |
| 60 | + elif isinstance(child, nn.MultiheadAttention): |
| 61 | + setattr(model, name, LRPMultiheadAttention.from_torch(child)) |
| 62 | + elif cname in _POOLING_BY_NAME: |
| 63 | + setattr(model, name, _POOLING_BY_NAME[cname](child, epsilon)) |
| 64 | + elif isinstance(child, (nn.Linear, nn.Conv1d, nn.Conv2d, nn.Conv3d)): |
| 65 | + setattr(model, name, EpsilonRule(child, epsilon)) |
| 66 | + elif isinstance(child, nn.LayerNorm): |
| 67 | + setattr(model, name, IdentityRule(child)) |
| 68 | + elif isinstance(child, (nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d)): |
| 69 | + # in eval mode BatchNorm is an affine-linear op → ε-LRP |
| 70 | + setattr(model, name, EpsilonRule(child, epsilon)) |
| 71 | + else: |
| 72 | + # not a leaf/known block: recurse into it |
| 73 | + prepare_model_for_lrp(child, epsilon) |
| 74 | + return model |
| 75 | + |
| 76 | + |
| 77 | +class ModelLRP(nn.Module): |
| 78 | + """LRP attribution for a whole PhysioEx model (recurrent / transformer / |
| 79 | + attention architectures). |
| 80 | +
|
| 81 | + Args: |
| 82 | + model: trained model, ``(B, L, C, T[, F]) -> (B, L, n_classes)`` (or a |
| 83 | + dict output — set ``output_key``). |
| 84 | + in_index / out_index: sequence epoch and class to explain. |
| 85 | + output_key: for models returning a dict (e.g. CoReSleep → ``"combined"``). |
| 86 | + epsilon: ε for the ε-LRP rules. |
| 87 | +
|
| 88 | + ``forward(x)`` returns relevance shaped like ``x``. The trained model is |
| 89 | + deep-copied and left untouched. |
| 90 | + """ |
| 91 | + |
| 92 | + def __init__( |
| 93 | + self, |
| 94 | + model: nn.Module, |
| 95 | + in_index: int = 0, |
| 96 | + out_index: int = 0, |
| 97 | + output_key: str | None = None, |
| 98 | + epsilon: float = 1e-6, |
| 99 | + ): |
| 100 | + super().__init__() |
| 101 | + self.in_index = in_index |
| 102 | + self.out_index = out_index |
| 103 | + self.output_key = output_key |
| 104 | + prepared = copy.deepcopy(model).eval() |
| 105 | + self.model = prepare_model_for_lrp(prepared, epsilon) |
| 106 | + # LRP saves tensors for the custom backward, so in-place ops (e.g. |
| 107 | + # ReLU(inplace=True)) would corrupt them — disable them on the copy. |
| 108 | + for m in self.model.modules(): |
| 109 | + if getattr(m, "inplace", False): |
| 110 | + m.inplace = False |
| 111 | + |
| 112 | + def forward(self, x: torch.Tensor) -> torch.Tensor: |
| 113 | + x = x.detach().requires_grad_(True) |
| 114 | + out = self.model(x) |
| 115 | + if self.output_key is not None: |
| 116 | + out = out[self.output_key] |
| 117 | + seed = torch.zeros_like(out) |
| 118 | + seed[:, self.in_index, self.out_index] = out[ |
| 119 | + :, self.in_index, self.out_index |
| 120 | + ].detach() |
| 121 | + out.backward(seed) |
| 122 | + return x.grad |
0 commit comments