diff --git a/docs/api/interpret.rst b/docs/api/interpret.rst index 14afcb314c..7f63aa30cd 100644 --- a/docs/api/interpret.rst +++ b/docs/api/interpret.rst @@ -1,5 +1,5 @@ Interpretability -=============== +================ We implement the following interpretability techniques to help you understand model predictions and identify important features in healthcare data. @@ -13,7 +13,7 @@ New to interpretability in PyHealth? Check out these complete examples: **Basic Gradient Example:** -- ``examples/ChestXrayClassificationWithSaliency.ipynb`` - Interactive notebook demonstrating gradient-based saliency mapping for medical image classification. Shows how to: +- ``examples/cxr/ChestXrayClassificationWithSaliency.ipynb`` - Interactive notebook demonstrating gradient-based saliency mapping for medical image classification. Shows how to: - Load and classify chest X-ray images using PyHealth's TorchvisionModel - Generate gradient saliency maps to visualize model attention @@ -81,14 +81,11 @@ Attribution Methods interpret/pyhealth.interpret.methods.chefer interpret/pyhealth.interpret.methods.attention_rollout interpret/pyhealth.interpret.methods.deeplift + interpret/pyhealth.interpret.methods.lrp interpret/pyhealth.interpret.methods.integrated_gradients interpret/pyhealth.interpret.methods.shap interpret/pyhealth.interpret.methods.lime interpret/pyhealth.interpret.methods.tree_shap - interpret/pyhealth.interpret.methods.ig_gim - interpret/pyhealth.interpret.methods.ensemble - interpret/pyhealth.interpret.methods.baseline - interpret/pyhealth.interpret.methods.base_interpreter Visualization Utilities ----------------------- diff --git a/docs/api/interpret/pyhealth.interpret.methods.basic_gradient.rst b/docs/api/interpret/pyhealth.interpret.methods.basic_gradient.rst index afdd4aa8f3..85a1518325 100644 --- a/docs/api/interpret/pyhealth.interpret.methods.basic_gradient.rst +++ b/docs/api/interpret/pyhealth.interpret.methods.basic_gradient.rst @@ -9,7 +9,7 @@ classification models. This helps identify which regions of medical images most model's prediction by visualizing gradients of model outputs with respect to input pixels. For a complete working example, see: -``examples/ChestXrayClassificationWithSaliency.ipynb`` +``examples/cxr/ChestXrayClassificationWithSaliency.ipynb`` API Reference ------------- diff --git a/docs/api/interpret/pyhealth.interpret.methods.lrp.rst b/docs/api/interpret/pyhealth.interpret.methods.lrp.rst new file mode 100644 index 0000000000..e52fab4411 --- /dev/null +++ b/docs/api/interpret/pyhealth.interpret.methods.lrp.rst @@ -0,0 +1,124 @@ +pyhealth.interpret.methods.lrp +=============================== + +Overview +-------- + +Layer-wise Relevance Propagation (LRP) explains a prediction by redistributing +the model's output score backwards through the network, layer by layer, until +every input feature carries a share of the relevance. Unlike gradient-based +saliency, which measures local sensitivity, LRP conserves a *quantity* of +relevance as it flows, so attributions are directly comparable across features +of the same sample. + +The implementation follows Bach et al. (2015), "On Pixel-Wise Explanations for +Non-Linear Classifier Decisions by Layer-Wise Relevance Propagation" +(https://doi.org/10.1371/journal.pone.0130140), with the local-renormalization +handling of Binder et al. (2016) (https://arxiv.org/abs/1604.00825). + +This method is particularly useful for: + +- **Multi-modal EHR models**: Attributing a prediction across discrete codes and continuous labs in one pass +- **Medical imaging**: Producing pixel-level relevance heatmaps for CNN classifiers +- **Model debugging**: Checking that relevance concentrates on clinically meaningful inputs +- **Method comparison**: Serving as a conservation-based counterpart to gradient and perturbation methods + +Propagation Rules +----------------- + +- ``rule="epsilon"`` — the :math:`\varepsilon`-rule stabilises the denominator + with :math:`z_j + \varepsilon \cdot \mathrm{sign}(z_j)`. Larger ``epsilon`` + absorbs more relevance and yields sparser, less noisy attributions. +- ``rule="alphabeta"`` — the :math:`\alpha\beta`-rule separates positive and + negative contributions and recombines them as + :math:`\alpha R^{+} - \beta R^{-}`, with ``alpha - beta == 1`` by convention. + The split is taken over the *contributions* :math:`z_{ij} = x_i w_{ij}`, not + over the weights alone -- for :math:`x_i < 0` a positive weight yields a + negative contribution, so both the input and the weight are split. With + ``beta=0`` the negative path is disabled and relevance keeps the sign of the + output relevance. + +Layer Handlers +-------------- + +Per-layer propagation lives in :mod:`pyhealth.interpret.methods.lrp_base`, which +defines an abstract :class:`~pyhealth.interpret.methods.lrp_base.LRPLayerHandler` +and an :class:`~pyhealth.interpret.methods.lrp_base.LRPHandlerRegistry` that maps +a layer type to its handler. ``LayerwiseRelevancePropagation`` builds a registry +at construction and dispatches each layer through it, so support for a custom +layer can be added without subclassing the interpreter:: + + lrp._registry.register(MyLayerHandler()) + +Handlers ship for ``Linear``, ``Conv2d``, ``ReLU``, ``MaxPool2d``, ``AvgPool2d``, +``AdaptiveAvgPool2d``, ``Flatten``, ``BatchNorm2d``, ``Dropout`` and the +recurrent ``LSTM``/``GRU`` layers. Layer types with no registered handler pass +relevance through unchanged. + +Usage Notes +----------- + +1. **Batch size**: Use ``batch_size=1`` for per-sample explanations. +2. **Evaluation mode**: Call ``model.eval()`` first so dropout and batch-norm + behave deterministically. +3. **Embeddings**: With ``use_embeddings=True`` the model must implement the + :class:`~pyhealth.interpret.api.Interpretable` interface (or expose both + ``forward_from_embedding`` and ``get_embedding_model``), and relevance is + propagated from the embedding output rather than the raw token indices. +4. **Conservation is approximate**: Per-layer conservation is exact only for a + bias-free linear layer under the :math:`\varepsilon`-rule. Biases, the + stabiliser itself, and pooling all absorb relevance, so + ``sum(attributions)`` tracks the logit rather than matching it exactly. The + gap is largest for models whose logit is small relative to their biases. +5. **Recurrent models**: ``StageNet`` applies the same ``nn.Linear`` repeatedly + inside a Python loop, so a forward hook retains only the final time step. + Relevance for recurrent layers is therefore distributed uniformly across + time steps, and per-time-step attributions from these models should be read + as a feature-level summary rather than a precise temporal attribution. + +Quick Start +----------- + +.. code-block:: python + + from pyhealth.datasets import get_dataloader + from pyhealth.interpret.methods import LayerwiseRelevancePropagation + from pyhealth.models import StageNet + + # Assume you have a trained model and dataset + model = StageNet(dataset=sample_dataset) + # ... train the model ... + model.eval() + + # Per-sample explanations + test_loader = get_dataloader(test_dataset, batch_size=1, shuffle=False) + batch = next(iter(test_loader)) + + lrp = LayerwiseRelevancePropagation( + model, rule="epsilon", epsilon=0.01, use_embeddings=True + ) + attributions = lrp.attribute(**batch) + + for feature_key, relevance in attributions.items(): + print(f"{feature_key}: {relevance.shape}, total={relevance.sum():.4f}") + +For complete working examples, see: + +- ``examples/interpretability/lrp_stagenet_synthetic.py`` — self-contained run on synthetic data, no external dataset required +- ``examples/interpretability/lrp_stagenet_mimic4.py`` — mortality prediction on MIMIC-IV +- ``examples/ChestXray-Classification-ResNet-with-Saliency.ipynb`` — LRP heatmaps on chest X-rays, compared against gradient saliency + +API Reference +------------- + +.. autoclass:: pyhealth.interpret.methods.LayerwiseRelevancePropagation + :members: + :undoc-members: + :show-inheritance: + :member-order: bysource + +.. automodule:: pyhealth.interpret.methods.lrp_base + :members: + :undoc-members: + :show-inheritance: + :member-order: bysource diff --git a/pyhealth/interpret/methods/__init__.py b/pyhealth/interpret/methods/__init__.py index 4a67fbd2a6..ab86089020 100644 --- a/pyhealth/interpret/methods/__init__.py +++ b/pyhealth/interpret/methods/__init__.py @@ -13,21 +13,29 @@ from pyhealth.interpret.methods.ensemble_crh import CrhEnsemble from pyhealth.interpret.methods.ensemble_avg import AvgEnsemble from pyhealth.interpret.methods.ensemble_var import VarEnsemble +from pyhealth.interpret.methods.lrp import LayerwiseRelevancePropagation +from pyhealth.interpret.methods.saliency_visualization import ( + SaliencyVisualizer, + visualize_attribution, +) __all__ = [ "BaseInterpreter", + "BasicGradientSaliencyMaps", "CheferRelevance", "AttentionRollout", "DeepLift", "GIM", "IntegratedGradientGIM", "IntegratedGradients", - "BasicGradientSaliencyMaps", "RandomBaseline", + "LayerwiseRelevancePropagation", + "SaliencyVisualizer", + "visualize_attribution", "ShapExplainer", "LimeExplainer", "TreeSHAP", "CrhEnsemble", "AvgEnsemble", - "VarEnsemble" + "VarEnsemble", ] diff --git a/pyhealth/interpret/methods/basic_gradient.py b/pyhealth/interpret/methods/basic_gradient.py index 452811fac0..3c4d292c11 100644 --- a/pyhealth/interpret/methods/basic_gradient.py +++ b/pyhealth/interpret/methods/basic_gradient.py @@ -1,8 +1,8 @@ import torch -import numpy as np -from typing import Dict + from pyhealth.interpret.methods.base_interpreter import BaseInterpreter + class BasicGradientSaliencyMaps(BaseInterpreter): """Compute gradient-based saliency maps for image classification models. @@ -28,47 +28,43 @@ class BasicGradientSaliencyMaps(BaseInterpreter): where c iterates over color channels (RGB or grayscale) Examples: - Basic usage with a batch:: - - from pyhealth.interpret.methods.basic_gradient import BasicGradientSaliencyMaps - import matplotlib.pyplot as plt - - # Create batch - batch = { - 'image': torch.randn(2, 3, 224, 224), - 'disease': torch.tensor([0, 1]) - } - - # Compute saliency maps - saliency = BasicGradientSaliencyMaps(model, input_batch=batch) - - # Visualize - saliency.visualize_saliency_map( - plt, - image_index=0, - title="Saliency Map", - id2label={0: "Normal", 1: "COVID"} - ) - - Using the attribute() interface:: - - # Initialize without batch - saliency = BasicGradientSaliencyMaps(model) - - # Compute attributions for new data - attributions = saliency.attribute(**batch) - # Returns: {'image': tensor with saliency maps} - - # Save to batch history - attributions = saliency.attribute(save_to_batch=True, **batch) - + >>> import torch + >>> import matplotlib.pyplot as plt + >>> from pyhealth.interpret.methods.basic_gradient import ( + ... BasicGradientSaliencyMaps, + ... ) + >>> + >>> batch = { + ... "image": torch.randn(2, 3, 224, 224), + ... "disease": torch.tensor([0, 1]), + ... } + >>> # ... train an image classification model ... + >>> + >>> # Compute saliency maps up front for a batch + >>> saliency = BasicGradientSaliencyMaps(model, input_batch=batch) + >>> saliency.visualize_saliency_map( + ... plt, + ... image_index=0, + ... title="Saliency Map", + ... id2label={0: "Normal", 1: "COVID"}, + ... ) + >>> + >>> # Or use the attribute() interface on new data + >>> saliency = BasicGradientSaliencyMaps(model) + >>> attributions = saliency.attribute(**batch) + >>> # Returns dict: {"image": tensor of saliency maps} + >>> attributions["image"].shape # [batch, H, W] + >>> + >>> # Append the result to the interpreter's batch history + >>> attributions = saliency.attribute(save_to_batch=True, **batch) + Note: - Do not use within ``torch.no_grad()`` context as gradients are required - Works with any PyHealth image classification model - For best results, normalize input images consistently with training See Also: - - ``examples/ChestXrayClassificationWithSaliency.ipynb``: Complete tutorial + - ``examples/cxr/ChestXrayClassificationWithSaliency.ipynb``: Complete tutorial - :class:`~pyhealth.interpret.methods.IntegratedGradients`: Alternative attribution method """ def __init__(self, model, input_batch=None, image_key='image', label_key='disease'): @@ -99,7 +95,7 @@ def __init__(self, model, input_batch=None, image_key='image', label_key='diseas if input_batch is not None: self._compute_saliency_maps() - def attribute(self, save_to_batch=False, **data) -> Dict[str, torch.Tensor]: + def attribute(self, save_to_batch=False, **data) -> dict[str, torch.Tensor]: """Compute attribution scores for input features. This method implements the BaseInterpreter interface by computing @@ -210,6 +206,9 @@ def _process_batch(self, batch): def visualize_saliency_map(self, plt, *, image_index, title=None, id2label=None, alpha=0.3): """Display an image with its saliency map overlay. + This method uses the SaliencyVisualizer for rendering and adds model + prediction information to the visualization. + Args: plt: matplotlib.pyplot instance image_index: Index of image within batch @@ -217,6 +216,8 @@ def visualize_saliency_map(self, plt, *, image_index, title=None, id2label=None, id2label: Optional dictionary mapping class indices to labels alpha: Transparency of saliency overlay (default: 0.3) """ + from pyhealth.interpret.methods.saliency_visualization import SaliencyVisualizer + if plt is None: import matplotlib.pyplot as plt @@ -258,26 +259,13 @@ def visualize_saliency_map(self, plt, *, image_index, title=None, id2label=None, title = f"True: {true_label_str}, Predicted: {pred_label_str}" else: title = f"{title} - True: {true_label_str}, Predicted: {pred_label_str}" - - # Convert image to numpy for display - if img_tensor.dim() == 4: - img_tensor = img_tensor[0] - img_np = img_tensor.detach().cpu().numpy() - if img_np.shape[0] in [1, 3]: # CHW to HWC - img_np = np.transpose(img_np, (1, 2, 0)) - if img_np.shape[-1] == 1: - img_np = img_np.squeeze(-1) - - # Convert saliency to numpy - if saliency.dim() > 2: - saliency = saliency[0] - saliency_np = saliency.detach().cpu().numpy() - # Create visualization - plt.figure(figsize=(15, 7)) - plt.axis('off') - plt.imshow(img_np, cmap='gray') - plt.imshow(saliency_np, cmap='hot', alpha=alpha) - if title: - plt.title(title) - plt.show() \ No newline at end of file + # Use SaliencyVisualizer for rendering + visualizer = SaliencyVisualizer(default_alpha=alpha) + visualizer.plot_saliency_overlay( + plt, + image=img_tensor[0], + saliency=saliency, + title=title, + alpha=alpha + ) \ No newline at end of file diff --git a/pyhealth/interpret/methods/lrp.py b/pyhealth/interpret/methods/lrp.py new file mode 100644 index 0000000000..fc3e73b275 --- /dev/null +++ b/pyhealth/interpret/methods/lrp.py @@ -0,0 +1,794 @@ +"""Layer-wise Relevance Propagation (LRP) for PyHealth models. + +Implements epsilon-rule and alphabeta-rule LRP for computing feature +attributions. Supports embedding-based models (discrete medical codes) +and CNN-based models (images). + +References: + Binder et al., "Layer-wise Relevance Propagation for Neural Networks + with Local Renormalization Layers", arXiv:1604.00825, 2016. +""" + +import contextlib +import logging +from typing import Literal, Self + +import torch +import torch.nn.functional as F +from torch import nn + +from pyhealth.interpret.api import Interpretable +from pyhealth.interpret.methods.base_interpreter import BaseInterpreter +from pyhealth.interpret.methods.lrp_base import ( + AdaptiveAvgPool2dLRPHandler, + AvgPool2dLRPHandler, + BatchNorm2dLRPHandler, + Conv2dLRPHandler, + DropoutLRPHandler, + FlattenLRPHandler, + LinearLRPHandler, + LRPHandlerRegistry, + MaxPool2dLRPHandler, + ReLULRPHandler, + RNNLRPHandler, + stabilize_denominator, +) +from pyhealth.models import BaseModel + +logger = logging.getLogger(__name__) + + +class _LRPHookContext(contextlib.AbstractContextManager): + """Owns all mutable hook state for one LRP forward+backward pass. + + Creating a fresh context per :meth:`LayerwiseRelevancePropagation.attribute` + call eliminates the concurrency / re-entrancy hazard that arises when hook + state is stored as instance attributes on the interpreter. + """ + + def __init__(self, model: nn.Module) -> None: + self.model = model + self.activations: dict[str, dict] = {} + self.hooks: list = [] + self.residual_blocks: dict[str, dict] = {} + + def __enter__(self) -> Self: + self._register_hooks() + return self + + def __exit__(self, exc_type, exc, exc_tb) -> bool: + for hook in self.hooks: + hook.remove() + self.hooks.clear() + self.activations.clear() + self.residual_blocks.clear() + return False + + def _register_hooks(self) -> None: + def save_activation(name: str): + def hook(module, input, output): + in_t = input[0] if isinstance(input, tuple) else input + out_t = output[0] if isinstance(output, tuple) else output + entry: dict = {"input": in_t, "output": out_t, "module": module} + # Pre-compute pool indices so MaxPool2dLRPHandler can unpool + if isinstance(module, nn.MaxPool2d): + _, indices = F.max_pool2d( + in_t, + kernel_size=module.kernel_size, + stride=module.stride, + padding=module.padding, + dilation=module.dilation, + return_indices=True, + ) + entry["indices"] = indices + self.activations[name] = entry + return hook + + for name, module in self.model.named_modules(): + if isinstance( + module, + ( + nn.Linear, nn.ReLU, nn.LSTM, nn.GRU, + nn.Conv2d, nn.MaxPool2d, nn.AvgPool2d, + nn.AdaptiveAvgPool2d, nn.BatchNorm2d, + nn.Flatten, nn.Dropout, + ), + ): + handle = module.register_forward_hook(save_activation(name)) + self.hooks.append(handle) + + try: + from torchvision.models.resnet import BasicBlock, Bottleneck + + def save_residual_block(block_name: str): + def hook(module, input, output): + x = input[0] if isinstance(input, tuple) else input + self.residual_blocks[block_name] = { + "input": x, + "has_downsample": module.downsample is not None, + } + return hook + + for name, module in self.model.named_modules(): + if isinstance(module, (BasicBlock, Bottleneck)): + handle = module.register_forward_hook(save_residual_block(name)) + self.hooks.append(handle) + except (ImportError, AttributeError): + pass + + +class LayerwiseRelevancePropagation(BaseInterpreter): + """LRP attribution method for PyHealth models. + + Decomposes a model's prediction into per-feature relevance scores + via backward propagation. Satisfies the conservation property: + sum of relevances ~ f(x). + + Args: + model: Trained PyHealth model to interpret. + rule: Propagation rule ('epsilon' or 'alphabeta'). + epsilon: Stabilizer for epsilon-rule (default: 0.01). + alpha: Positive weight for alphabeta-rule (default: 1.0). + beta: Negative weight for alphabeta-rule (default: 0.0). + use_embeddings: If True, propagate from embedding layer. + + Examples: + >>> lrp = LayerwiseRelevancePropagation(model, rule="epsilon") + >>> attributions = lrp.attribute(**test_batch) + >>> for key, rel in attributions.items(): + ... print(f"{key}: sum={rel.sum().item():.4f}") + """ + + def __init__( + self, + model: BaseModel, + rule: Literal["epsilon", "alphabeta"] = "epsilon", + epsilon: float = 0.01, + alpha: float = 1.0, + beta: float = 0.0, + use_embeddings: bool = True, + ): + super().__init__(model) + if use_embeddings: + has_forward_from_embedding = hasattr(model, "forward_from_embedding") + has_get_embedding_model = hasattr(model, "get_embedding_model") + if not (isinstance(model, Interpretable) or (has_forward_from_embedding and has_get_embedding_model)): + raise ValueError( + "Model must implement Interpretable interface (or provide both " + "forward_from_embedding and get_embedding_model methods) when " + "use_embeddings=True" + ) + self.rule = rule + self.epsilon = epsilon + self.alpha = alpha + self.beta = beta + self.use_embeddings = use_embeddings + + self._registry = LRPHandlerRegistry() + for handler in [ + LinearLRPHandler(), + ReLULRPHandler(), + Conv2dLRPHandler(), + MaxPool2dLRPHandler(), + AvgPool2dLRPHandler(), + AdaptiveAvgPool2dLRPHandler(), + BatchNorm2dLRPHandler(), + FlattenLRPHandler(), + DropoutLRPHandler(), + RNNLRPHandler(), + ]: + self._registry.register(handler) + + def attribute( + self, + target_class_idx: int | None = None, + **data, + ) -> dict[str, torch.Tensor]: + """Compute LRP attributions for input features. + + Args: + target_class_idx: Target class for attribution (None = predicted). + **data: Input data from a dataloader batch. + + Returns: + Dict mapping each feature key to its relevance tensor. + """ + feature_keys = getattr(self.model, "feature_keys", list(data.keys())) + device = next(self.model.parameters()).device + has_processors = hasattr(self.model, "dataset") and hasattr( + getattr(self.model, "dataset", None), "input_processors" + ) + + # Keep original input tuples (matching processor schema) and extract values + inputs, values, label_data = {}, {}, {} + for key in feature_keys: + if key not in data: + continue + v = data[key] + if isinstance(v, torch.Tensor): + v = (v,) + inputs[key] = tuple( + t.to(device) if isinstance(t, torch.Tensor) else t for t in v + ) + if has_processors and key in self.model.dataset.input_processors: + schema = self.model.dataset.input_processors[key].schema() + values[key] = inputs[key][schema.index("value")] + else: + # Fallback for models without processor schema + values[key] = inputs[key][0] + + # Build and re-append padding masks so sequence models receive them (Issue 3) + if has_processors: + masks: dict[str, torch.Tensor] = {} + for k in list(inputs.keys()): + if k not in self.model.dataset.input_processors: + continue + schema = self.model.dataset.input_processors[k].schema() + if "mask" in schema: + masks[k] = inputs[k][schema.index("mask")] + else: + processor = self.model.dataset.input_processors[k] + val = values[k] + if processor.is_token(): + # For nested tokens (val is 3D [B, seq, inner]), produce a + # visit-level mask [B, seq] so temporal models receive 2D masks + raw = (val != 0) + if raw.dim() == 3: + masks[k] = raw.any(dim=-1).int() + else: + masks[k] = raw.int() + elif val.dim() >= 3: + masks[k] = (val.abs().sum(dim=-1) != 0).int() + else: + masks[k] = (val != 0).int() + for k in list(inputs.keys()): + if k in masks and k in self.model.dataset.input_processors: + schema = self.model.dataset.input_processors[k].schema() + if "mask" not in schema: + inputs[k] = (*inputs[k], masks[k]) + + for key in getattr(self.model, "label_keys", []): + if key in data: + val = data[key] + if not isinstance(val, torch.Tensor): + val = torch.tensor(val) + label_data[key] = val.to(device) + + if self.use_embeddings: + return self._compute_from_embeddings( + inputs, values, target_class_idx, label_data + ) + return self._compute_from_inputs(inputs, values, target_class_idx, label_data) + + def visualize(self, plt, image, relevance, title=None, method="overlay", **kwargs): + """Visualize LRP relevance maps using SaliencyVisualizer.""" + from pyhealth.interpret.methods.saliency_visualization import ( + visualize_attribution, + ) + + if title is None: + title = f"LRP Attribution ({self.rule}-rule)" + visualize_attribution(plt, image, relevance, title=title, method=method, **kwargs) + + # ------------------------------------------------------------------ + # Core computation + # ------------------------------------------------------------------ + + def _compute_from_embeddings(self, inputs, values, target_class_idx, label_data): + """LRP starting from embedding layer (for discrete inputs).""" + embedding_model = self.model.get_embedding_model() + assert embedding_model is not None, ( + "Model must have an embedding model for embedding-based LRP. " + "Set use_embeddings=False for continuous features only." + ) + input_embeddings, input_shapes = {}, {} + + for key in values: + input_shapes[key] = values[key].shape + embedded = embedding_model({key: values[key]}) + x = embedded[key] + if x.dim() == 4: + x = x.sum(dim=2) + input_embeddings[key] = x + + # Reconstruct input tuples with embedded values spliced in + forward_kwargs = {} + has_processors = hasattr(self.model, "dataset") and hasattr( + getattr(self.model, "dataset", None), "input_processors" + ) + for key in inputs: + if has_processors and key in self.model.dataset.input_processors: + schema = self.model.dataset.input_processors[key].schema() + val_idx = schema.index("value") + original = inputs[key] + forward_kwargs[key] = ( + *original[:val_idx], + input_embeddings[key], + *original[val_idx + 1:], + ) + else: + # Fallback: pass bare embedding tensor + forward_kwargs[key] = input_embeddings[key] + if label_data: + forward_kwargs.update(label_data) + + with _LRPHookContext(self.model) as ctx: + with torch.no_grad(): + output = self.model.forward_from_embedding(**forward_kwargs) + logits = output["logit"] + output_relevance = self._init_output_relevance(logits, target_class_idx) + relevance_at_emb = self._propagate_relevance_backward( + output_relevance, input_embeddings, ctx + ) + + result = {} + for key in input_embeddings: + rel = relevance_at_emb.get(key) + if rel is None: + continue + # Sum over embedding dim to get per-token relevance + if rel.dim() >= 2: + result[key] = rel.sum(dim=-1) + else: + result[key] = rel + # Expand to match original input shape if needed + orig = input_shapes[key] + if result[key].shape != orig and len(orig) == 3 and result[key].dim() == 2: + result[key] = result[key].unsqueeze(-1).expand(orig) + return result + + def _compute_from_inputs(self, inputs, values, target_class_idx, label_data): + """LRP starting from continuous inputs (e.g., images).""" + self.model.eval() + forward_kwargs = {**values} + if label_data: + forward_kwargs.update(label_data) + with _LRPHookContext(self.model) as ctx: + with torch.no_grad(): + output = self.model(**forward_kwargs) + logits = self._extract_logits(output, ctx) + output_relevance = self._init_output_relevance(logits, target_class_idx) + result = self._propagate_relevance_backward(output_relevance, values, ctx) + if not isinstance(result, dict): + result = {next(iter(values)): result} + return result + + def _extract_logits( + self, output: dict, ctx: "_LRPHookContext" + ) -> torch.Tensor: + """Return raw pre-softmax logits for LRP initialisation. + + Priority: + 1. ``output["logit"]`` — model explicitly exposes raw logits. + 2. Last ``nn.Linear`` hook in *ctx* — the final classification head + fires its hook *before* ``prepare_y_prob`` applies softmax, so + its cached output is the true pre-softmax logit even for models + like ``TorchvisionModel`` that do not return a "logit" key. + 3. ``output["y_prob"]`` — last-resort fallback; conservation will + not hold because softmax collapses the logit scale. + """ + if "logit" in output: + return output["logit"] + + # Walk the activations dict (insertion = forward-execution order). + # Keeping the last Linear hit gives the final classification head. + last_linear_output: torch.Tensor | None = None + for info in ctx.activations.values(): + if isinstance(info["module"], nn.Linear): + last_linear_output = info["output"] + + if last_linear_output is not None: + logger.debug( + "Extracted raw logits from the final Linear layer hook " + "(model does not return a 'logit' key)." + ) + return last_linear_output + + if "y_prob" in output: + logger.debug( + "Model forward() did not return a 'logit' key; falling back " + "to 'y_prob'. LRP conservation property may not hold." + ) + return output["y_prob"] + + raise KeyError( + "Model forward() must return a 'logit' key for LRP. " + f"Got keys: {list(output.keys())}" + ) + + def _init_output_relevance(self, logits, target_class_idx): + """Initialize relevance at the output layer using prediction-mode dispatch.""" + try: + mode = self._prediction_mode() + except (AssertionError, AttributeError, KeyError, IndexError): + # Fall back to shape-based heuristic for models that don't expose + # output schema (e.g. TorchvisionModel with use_embeddings=False). + mode = "multiclass" if logits.dim() == 2 and logits.size(-1) > 1 else "binary" + + if mode == "binary": + # Binary logits have shape [B] or [B, 1]. + # Convention: class index 1 (or None) → positive class (logit as-is). + # class index 0 → negative class (negate logit). + # This makes target_class_idx meaningful for binary models. + if target_class_idx == 0: + return -logits + return logits + if mode in ("multiclass", "multilabel"): + if target_class_idx is None: + target_class_idx = torch.argmax(logits, dim=-1) + elif not isinstance(target_class_idx, torch.Tensor): + target_class_idx = torch.tensor( + target_class_idx, device=logits.device + ) + batch_size = logits.size(0) + output_relevance = torch.zeros_like(logits) + output_relevance[range(batch_size), target_class_idx] = logits[ + range(batch_size), target_class_idx + ] + return output_relevance + # Regression or unknown mode: return logits unchanged. + return logits + + # ------------------------------------------------------------------ + # Backward propagation + # ------------------------------------------------------------------ + + def _get_block_for_layer(self, layer_name: str, ctx: _LRPHookContext) -> str | None: + """Return the residual block prefix if this layer belongs to a tracked block.""" + for bname in ctx.residual_blocks: + if layer_name.startswith(bname + "."): + return bname + return None + + def _propagate_through_residual_block( + self, + block_name: str, + block_layer_names_rev: list, + r_in: torch.Tensor, + ctx: _LRPHookContext, + ) -> torch.Tensor: + """Propagate relevance through a residual block with correct LRP skip-connection split. + + At each residual addition ``out = main_path + identity`` the LRP rule requires + splitting the incoming relevance proportionally. The active rule (epsilon or + alpha-beta) is determined by ``self.rule``: + R_main = (main_path / stabilise(main_path + identity)) * R_in + R_identity = (identity / stabilise(main_path + identity)) * R_in + + R_main is then propagated back through the block's convolutional layers while + R_identity bypasses them (or is propagated through the downsample layers when + the block includes a projection shortcut). + """ + has_downsample = ctx.residual_blocks[block_name]["has_downsample"] + block_input = ctx.residual_blocks[block_name]["input"] + + # Partition layers into main path vs. downsample path + main_layers = [l for l in block_layer_names_rev if ".downsample." not in l] + ds_layers = [l for l in block_layer_names_rev if ".downsample." in l] + + # main_out = output of the last main-path BN (first encountered in reversed order, + # e.g. bn2 for BasicBlock, bn3 for Bottleneck) + main_out = ctx.activations[main_layers[0]]["output"] if main_layers else None + + # identity = output of the final downsample BN (projection shortcut) OR raw input + if has_downsample and ds_layers: + identity = ctx.activations[ds_layers[0]]["output"] + else: + identity = block_input + + # LRP split at the residual addition, dispatched by rule. + if (main_out is not None + and identity is not None + and main_out.shape == identity.shape + and r_in.shape == main_out.shape): + if self.rule == "alphabeta": + # Alpha-beta rule for an addition node: + # z_j^+ = sum of positive inputs, z_j^- = sum of negative inputs + # R_i = (alpha * a_i^+ / stabilise(z_j^+) + # - beta * a_i^- / stabilise(z_j^-)) * R_j + z_pos = torch.clamp(main_out, min=0) + torch.clamp(identity, min=0) + z_neg = torch.clamp(main_out, max=0) + torch.clamp(identity, max=0) + denom_pos = stabilize_denominator(z_pos, self.epsilon) + denom_neg = stabilize_denominator(z_neg, self.epsilon) + r_for_main = ( + self.alpha * torch.clamp(main_out, min=0) / denom_pos + - self.beta * torch.clamp(main_out, max=0) / denom_neg + ) * r_in + r_for_identity = ( + self.alpha * torch.clamp(identity, min=0) / denom_pos + - self.beta * torch.clamp(identity, max=0) / denom_neg + ) * r_in + else: + # Epsilon rule for an addition node: + # R_i = (a_i / stabilise(z_j)) * R_j + total = main_out + identity + sign = total.sign() + sign = torch.where(sign == 0, torch.ones_like(sign), sign) + denom = total + self.epsilon * sign + r_for_main = (main_out / denom) * r_in + r_for_identity = (identity / denom) * r_in + else: + r_for_main = r_in + r_for_identity = None + + # Propagate r_for_main backward through the main-path layers + r_at_input = r_for_main + for ln in main_layers: + ai = ctx.activations[ln] + if r_at_input.shape != ai["output"].shape: + r_at_input = self._match_shapes(r_at_input, ai["output"].shape) + r_at_input = self._propagate_through_layer(ai["module"], ai, r_at_input) + + # Propagate r_for_identity through downsample layers (projection shortcut) + if has_downsample and ds_layers and r_for_identity is not None: + r_ds = r_for_identity + for ln in ds_layers: + ai = ctx.activations[ln] + if r_ds.shape != ai["output"].shape: + r_ds = self._match_shapes(r_ds, ai["output"].shape) + r_ds = self._propagate_through_layer(ai["module"], ai, r_ds) + if r_ds.shape == r_at_input.shape: + r_at_input = r_at_input + r_ds + elif not has_downsample and r_for_identity is not None: + # No projection: identity goes directly to block input + if r_for_identity.shape == r_at_input.shape: + r_at_input = r_at_input + r_for_identity + + return r_at_input + + def _propagate_relevance_backward(self, output_relevance, input_embeddings, ctx: _LRPHookContext): + """Propagate relevance from output back to input embeddings. + + Iterates layers in reverse-forward order. When a layer belongs to a + tracked residual block (BasicBlock / Bottleneck), all sub-layers of that + block are handled by ``_propagate_through_residual_block`` which applies + a proper LRP-epsilon split at the skip-connection addition. + + For models with per-feature branches (e.g. MLP, StageNet) the relevance + is split across features *immediately after* propagating through the shared + classifier head (``self.model.fc``), which is the mathematically correct + split point. Each feature's slice is then independently propagated through + its own sub-network layers (identified by the feature key appearing as a + dotted path component in the layer name, e.g. ``mlp.conditions.0``). + This preserves the relevance-conservation invariant of Eq. (2) in the + Binder et al. (2016) paper, up to the epsilon perturbation. + """ + current_relevance = output_relevance + layer_names = list(reversed(list(ctx.activations.keys()))) + + feature_relevances = {} + blocks_handled: set = set() + + feat_keys: list = [] + n_features = 0 + if isinstance(input_embeddings, dict) and hasattr(self.model, "feature_keys"): + feat_keys = [k for k in self.model.feature_keys if k in input_embeddings] + n_features = len(feat_keys) + + # Detect whether the model has separate per-feature branches that feed + # into a shared classifier (self.model.fc). This is True when: + # (a) the model exposes a `fc` attribute (the final Linear head), AND + # (b) every feature key appears as a dotted path component in at least + # one recorded layer activation (e.g. "mlp.conditions.0"). + # Both MLP and StageNet satisfy these criteria. + all_layer_name_parts: set = set() + for ln in ctx.activations: + all_layer_name_parts.update(ln.split(".")) + has_per_feature_branches = ( + n_features > 1 + and hasattr(self.model, "fc") + and all(fk in all_layer_name_parts for fk in feat_keys) + ) + + idx = 0 + while idx < len(layer_names): + layer_name = layer_names[idx] + + # ---- Residual block handling ---- + block_name = self._get_block_for_layer(layer_name, ctx) + if block_name is not None and block_name not in blocks_handled: + # Collect all consecutive layers that belong to this block + block_layers = [] + j = idx + while j < len(layer_names) and self._get_block_for_layer(layer_names[j], ctx) == block_name: + block_layers.append(layer_names[j]) + j += 1 + + current_relevance = self._propagate_through_residual_block( + block_name, block_layers, current_relevance, ctx + ) + blocks_handled.add(block_name) + idx = j + continue + + # ---- Regular layer handling ---- + activation_info = ctx.activations[layer_name] + module = activation_info["module"] + output_tensor = activation_info["output"] + + if current_relevance.shape != output_tensor.shape: + current_relevance = self._match_shapes( + current_relevance, output_tensor.shape + ) + + current_relevance = self._propagate_through_layer( + module, activation_info, current_relevance + ) + + # After propagating through the shared classifier head, split the + # relevance across per-feature branches and propagate each independently. + # Using module identity avoids fragile shape-based heuristics and + # ensures the split happens at the correct point in the computation graph. + if ( + has_per_feature_branches + and module is self.model.fc + and current_relevance.dim() == 2 + ): + per_feat = current_relevance.size(1) // n_features + for i, fk in enumerate(feat_keys): + feature_relevances[fk] = current_relevance[ + :, i * per_feat : (i + 1) * per_feat + ] + # Propagate each feature's relevance through its own sub-network. + # A layer belongs to feature fk when fk is a dotted-path component + # of the layer name (e.g. "mlp.conditions.0" → "conditions"). + for fk in feat_keys: + cur = feature_relevances[fk] + for ln in layer_names[idx + 1:]: + if fk not in ln.split("."): + continue + ai = ctx.activations[ln] + cur = self._propagate_through_layer(ai["module"], ai, cur) + feature_relevances[fk] = cur + return self._split_relevance_to_features( + feature_relevances, input_embeddings + ) + + idx += 1 + + return self._split_relevance_to_features( + current_relevance, input_embeddings + ) + + def _invoke_handler( + self, + handler, + module: nn.Module, + activation_info: dict, + relevance: torch.Tensor, + ) -> torch.Tensor: + """Populate *handler*'s activation cache from *activation_info* and call it. + + The handlers in ``lrp_base`` use ``self._get_cached(layer)`` internally. + We bridge that by pre-populating the cache entry before the call and + removing it immediately after, so the handler never observes stale data. + """ + if isinstance(module, nn.Flatten): + cache_entry = { + "input_shape": activation_info["input"].shape, + "output": activation_info["output"], + } + else: + cache_entry = {k: v for k, v in activation_info.items() if k != "module"} + handler.activations_cache[id(module)] = cache_entry + try: + return handler.backward_relevance( + module, + relevance, + rule=self.rule, + epsilon=self.epsilon, + alpha=self.alpha, + beta=self.beta, + ) + finally: + handler.activations_cache.pop(id(module), None) + + def _propagate_through_layer(self, module, activation_info, relevance): + """Route relevance propagation to the correct handler via the registry.""" + handler = self._registry.get_handler(module) + if handler is None: + return relevance + return self._invoke_handler(handler, module, activation_info, relevance) + + # ------------------------------------------------------------------ + # Shape utilities + # ------------------------------------------------------------------ + + def _match_shapes(self, relevance, target_shape): + if relevance.shape == target_shape: + return relevance + batch_size = relevance.shape[0] + + # 2D -> 4D + if relevance.dim() == 2 and len(target_shape) == 4: + total = target_shape[1] * target_shape[2] * target_shape[3] + if relevance.shape[1] == total: + return relevance.view(batch_size, *target_shape[1:]) + return (relevance.sum(dim=1, keepdim=True) / total).view( + batch_size, 1, 1, 1 + ).expand(batch_size, *target_shape[1:]) + + # 4D -> 4D + if relevance.dim() == 4 and len(target_shape) == 4: + if relevance.shape[1] != target_shape[1]: + relevance = relevance.mean(dim=1, keepdim=True).expand( + -1, target_shape[1], -1, -1 + ) + if relevance.shape[2:] != target_shape[2:]: + relevance = F.interpolate( + relevance, size=target_shape[2:], mode="bilinear", + align_corners=False, + ) + return relevance + + # 3D -> 4D + if relevance.dim() == 3 and len(target_shape) == 4: + relevance = relevance.unsqueeze(1).expand( + -1, target_shape[1], -1, -1 + ) + if relevance.shape[2:] != target_shape[2:]: + relevance = F.interpolate( + relevance, size=target_shape[2:], mode="bilinear", + align_corners=False, + ) + return relevance + + return relevance + + def _split_relevance_to_features(self, relevance, input_embeddings): + """Split combined relevance back to individual features.""" + result = {} + + # Already split per feature + if isinstance(relevance, dict): + for key, rel in relevance.items(): + if key not in input_embeddings: + continue + emb = input_embeddings[key] + if emb.dim() == 3 and rel.dim() == 2: + T = emb.size(1) + feat_dim = emb.size(-1) + if rel.size(1) > feat_dim: + # Strip appended dimensions (e.g. StageNet concatenates + # a 1-D time interval to the embedding before its + # kernel Linear; LRP returns relevance for the full + # concatenated input, so discard the time columns). + rel = rel[:, :feat_dim] + # Divide by T to reverse mean pooling: each of the T + # timesteps contributed equally, so each receives 1/T of + # the pooled relevance. This preserves the relevance-sum + # conservation invariant (Eq. 2) through the pooling step. + rel = (rel.unsqueeze(1) / T).expand_as(emb) + result[key] = rel + return result + + # Compute per-feature sizes (after pooling) + feature_sizes = {} + for key, emb in input_embeddings.items(): + if emb.dim() == 3: + feature_sizes[key] = emb.size(2) + elif emb.dim() == 2: + feature_sizes[key] = emb.size(1) + else: + feature_sizes[key] = emb.numel() // emb.size(0) + + total = sum(feature_sizes.values()) + if relevance.dim() != 2 or relevance.size(1) != total: + # Fallback: distribute equally + for key in input_embeddings: + result[key] = relevance / len(input_embeddings) + return result + + idx = 0 + for key in self.model.feature_keys: + if key not in input_embeddings: + continue + size = feature_sizes[key] + chunk = relevance[:, idx : idx + size] + emb = input_embeddings[key] + if emb.dim() == 3: + chunk = chunk.unsqueeze(1).expand_as(emb) + result[key] = chunk + idx += size + + return result \ No newline at end of file diff --git a/pyhealth/interpret/methods/lrp_base.py b/pyhealth/interpret/methods/lrp_base.py new file mode 100644 index 0000000000..c27f1c13d9 --- /dev/null +++ b/pyhealth/interpret/methods/lrp_base.py @@ -0,0 +1,855 @@ +"""Base classes and layer handlers for Layer-wise Relevance Propagation (LRP). + +Provides abstract base classes, a handler registry, and concrete LRP handlers +for common layer types (Linear, Conv2d, pooling, normalization, embedding). + +References: + Binder et al., "Layer-wise Relevance Propagation for Neural Networks + with Local Renormalization Layers", arXiv:1604.00825, 2016. +""" + +import logging +from abc import ABC, abstractmethod + +import torch +import torch.nn.functional as F +from torch import nn + +logger = logging.getLogger(__name__) + + +# ============================================================================ +# Utility functions +# ============================================================================ + + +def stabilize_denominator( + z: torch.Tensor, + epsilon: float = 1e-2, + rule: str = "epsilon", +) -> torch.Tensor: + """Stabilize denominator to prevent division by zero. + + Args: + z: Tensor to stabilize. + epsilon: Stabilization parameter. + rule: LRP rule ('epsilon' or 'z+'). + + Returns: + Stabilized tensor safe for division. + + Examples: + >>> import torch + >>> from pyhealth.interpret.methods.lrp_base import stabilize_denominator + >>> z = torch.tensor([[2.0, -2.0, 0.0]]) + >>> out = stabilize_denominator(z, epsilon=0.1, rule="epsilon") + >>> bool(torch.allclose(out, torch.tensor([[2.1, -2.1, 0.1]]))) + True + >>> bool((stabilize_denominator(z, 0.1, rule="z+") >= 0.1).all()) + True + """ + if rule == "epsilon": + sign = z.sign() + # sign(0) == 0 would make the denominator zero; treat zero as positive + sign = torch.where(sign == 0, torch.ones_like(sign), sign) + return z + epsilon * sign + elif rule == "z+": + return torch.clamp(z, min=epsilon) + return z + epsilon + + +def check_tensor_validity(tensor: torch.Tensor, name: str = "tensor") -> bool: + """Check tensor for NaN or Inf values. + + Examples: + >>> import torch + >>> from pyhealth.interpret.methods.lrp_base import check_tensor_validity + >>> check_tensor_validity(torch.ones(2, 2), "relevance") + True + >>> import logging + >>> logging.disable(logging.ERROR) # silence the diagnostic log line + >>> check_tensor_validity(torch.tensor([float("nan")]), "relevance") + False + >>> logging.disable(logging.NOTSET) + """ + if torch.isnan(tensor).any().item(): + logger.error(f"{name} contains NaN values!") + return False + if torch.isinf(tensor).any().item(): + logger.error(f"{name} contains Inf values!") + return False + return True + + +def pad_to_match( + x: torch.Tensor, expected_size: int +) -> tuple[torch.Tensor, int]: + """Pad or truncate *x* along dim=1 to *expected_size*. + + Returns: + Tuple of (adjusted_x, original_size). + + Examples: + >>> import torch + >>> from pyhealth.interpret.methods.lrp_base import pad_to_match + >>> padded, original = pad_to_match(torch.ones(1, 3), 5) + >>> padded.shape, original + (torch.Size([1, 5]), 3) + >>> truncated, original = pad_to_match(torch.ones(1, 6), 4) + >>> truncated.shape, original + (torch.Size([1, 4]), 6) + """ + orig = x.size(1) + if orig == expected_size: + return x, orig + if orig < expected_size: + pad = torch.zeros( + x.size(0), expected_size - orig, device=x.device, dtype=x.dtype + ) + return torch.cat([x, pad], dim=1), orig + return x[:, :expected_size], orig + + +def match_relevance_dim( + relevance: torch.Tensor, target_size: int +) -> torch.Tensor: + """Pad or truncate *relevance* along dim=1 to *target_size*. + + Examples: + >>> import torch + >>> from pyhealth.interpret.methods.lrp_base import match_relevance_dim + >>> match_relevance_dim(torch.ones(1, 5), 3).shape + torch.Size([1, 3]) + >>> match_relevance_dim(torch.ones(1, 2), 4).shape + torch.Size([1, 4]) + """ + current = relevance.size(1) + if current == target_size: + return relevance + if current < target_size: + pad = torch.zeros( + relevance.size(0), + target_size - current, + device=relevance.device, + dtype=relevance.dtype, + ) + return torch.cat([relevance, pad], dim=1) + return relevance[:, :target_size] + + +def conv_output_padding( + layer: nn.Module, z_shape: tuple, x_shape: tuple +) -> tuple: + """Compute output_padding for conv_transpose2d to recover input spatial size. + + Examples: + >>> import torch + >>> from torch import nn + >>> from pyhealth.interpret.methods.lrp_base import conv_output_padding + >>> layer = nn.Conv2d(1, 1, kernel_size=3, stride=2, padding=1) + >>> x = torch.randn(1, 1, 8, 8) + >>> conv_output_padding(layer, layer(x).shape, x.shape) + (1, 1) + """ + pads = [] + for i in range(2): + s = layer.stride[i] if isinstance(layer.stride, tuple) else layer.stride + p = layer.padding[i] if isinstance(layer.padding, tuple) else layer.padding + k = layer.weight.shape[2 + i] + expected = (z_shape[2 + i] - 1) * s - 2 * p + k + pads.append(max(0, x_shape[2 + i] - expected)) + return tuple(pads) + + +def crop_spatial(tensor: torch.Tensor, target_shape: tuple) -> torch.Tensor: + """Crop or zero-pad a 4-D tensor to match *target_shape* in the spatial dims. + + Examples: + >>> import torch + >>> from pyhealth.interpret.methods.lrp_base import crop_spatial + >>> crop_spatial(torch.ones(1, 1, 8, 8), (1, 1, 5, 5)).shape + torch.Size([1, 1, 5, 5]) + >>> crop_spatial(torch.ones(1, 1, 3, 3), (1, 1, 4, 4)).shape + torch.Size([1, 1, 4, 4]) + """ + if tensor.shape[2:] == target_shape[2:]: + return tensor + if tensor.shape[2] > target_shape[2] or tensor.shape[3] > target_shape[3]: + return tensor[:, :, : target_shape[2], : target_shape[3]] + pad_h = target_shape[2] - tensor.shape[2] + pad_w = target_shape[3] - tensor.shape[3] + return F.pad(tensor, (0, pad_w, 0, pad_h)) + + +# ============================================================================ +# Abstract base class and registry +# ============================================================================ + + +class LRPLayerHandler(ABC): + """Abstract base class for layer-specific LRP propagation rules. + + Each handler implements forward activation caching and backward + relevance propagation for a specific layer type. + + Examples: + >>> from torch import nn + >>> from pyhealth.interpret.methods.lrp_base import ( + ... LinearLRPHandler, + ... LRPLayerHandler, + ... ) + >>> issubclass(LinearLRPHandler, LRPLayerHandler) + True + >>> LinearLRPHandler().supports(nn.Linear(4, 2)) + True + """ + + def __init__(self, name: str): + self.name = name + self.activations_cache = {} + + @abstractmethod + def supports(self, layer: nn.Module) -> bool: + """Return True if this handler can process the given layer type.""" + + def forward_hook( + self, module: nn.Module, input: tuple, output: torch.Tensor + ) -> None: + """Cache input/output activations during forward pass.""" + input_tensor = input[0] if isinstance(input, tuple) else input + self.activations_cache[id(module)] = { + "input": input_tensor.detach(), + "output": output.detach(), + } + + @abstractmethod + def backward_relevance( + self, + layer: nn.Module, + relevance_output: torch.Tensor, + rule: str = "epsilon", + **kwargs, + ) -> torch.Tensor: + """Propagate relevance backward through the layer. + + Args: + layer: PyTorch module to propagate through. + relevance_output: Relevance scores at layer output. + rule: LRP rule ('epsilon', 'alphabeta'). + **kwargs: Rule-specific parameters (epsilon, alpha, beta). + + Returns: + Relevance scores at layer input. + """ + + def clear_cache(self): + self.activations_cache.clear() + + def _get_cached(self, layer: nn.Module) -> dict: + module_id = id(layer) + if module_id not in self.activations_cache: + raise RuntimeError( + f"forward_hook not called for {type(layer).__name__}. " + f"Run forward pass before backward_relevance." + ) + return self.activations_cache[module_id] + + +class LRPHandlerRegistry: + """Registry that maps layer types to their LRP handlers. + + Examples: + >>> from torch import nn + >>> from pyhealth.interpret.methods.lrp_base import ( + ... LinearLRPHandler, + ... LRPHandlerRegistry, + ... ) + >>> registry = LRPHandlerRegistry() + >>> registry.register(LinearLRPHandler()) + >>> registry.get_handler(nn.Linear(4, 2)).name + 'LinearHandler' + >>> registry.get_handler(nn.LayerNorm(4)) is None + True + """ + + def __init__(self): + self._handlers: list[LRPLayerHandler] = [] + self._cache: dict[type, LRPLayerHandler] = {} + + def register(self, handler: LRPLayerHandler) -> None: + if not isinstance(handler, LRPLayerHandler): + raise TypeError(f"Expected LRPLayerHandler, got {type(handler)}") + self._handlers.append(handler) + self._cache.clear() + + def get_handler(self, layer: nn.Module) -> LRPLayerHandler | None: + layer_type = type(layer) + if layer_type in self._cache: + return self._cache[layer_type] + for handler in self._handlers: + if handler.supports(layer): + self._cache[layer_type] = handler + return handler + return None + + def clear(self) -> None: + self._handlers.clear() + self._cache.clear() + + +# ============================================================================ +# Embedding & activation handlers +# ============================================================================ + + +class LinearLRPHandler(LRPLayerHandler): + """LRP handler for nn.Linear layers. + + Epsilon rule: R_i = sum_j (z_ij / (z_j + eps*sign(z_j))) * R_j + AlphaBeta rule: R_i = sum_j [alpha*z_ij+ / z_j+ - beta*z_ij- / z_j-] * R_j + + Handles higher-dimensional inputs by flattening to 2-D and pads/truncates + when the input width does not perfectly match the weight matrix width. + + Examples: + >>> import torch + >>> from torch import nn + >>> from pyhealth.interpret.methods.lrp_base import LinearLRPHandler + >>> layer, handler = nn.Linear(4, 2), LinearLRPHandler() + >>> x = torch.randn(1, 4) + >>> handler.forward_hook(layer, (x,), layer(x)) + >>> handler.backward_relevance(layer, torch.ones(1, 2), rule="epsilon").shape + torch.Size([1, 4]) + """ + + def __init__(self): + super().__init__(name="LinearHandler") + + def supports(self, layer: nn.Module) -> bool: + return isinstance(layer, nn.Linear) + + def backward_relevance( + self, + layer: nn.Module, + relevance_output: torch.Tensor, + rule: str = "epsilon", + epsilon: float = 1e-2, + alpha: float = 1.0, + beta: float = 0.0, + **kwargs, + ) -> torch.Tensor: + cache = self._get_cached(layer) + x = cache["input"] + if x.dim() > 2: + x = x.view(x.size(0), -1) + if rule == "epsilon": + return self._epsilon_rule(layer, x, relevance_output, epsilon) + elif rule == "alphabeta": + return self._alphabeta_rule(layer, x, relevance_output, alpha, beta) + raise ValueError(f"Unsupported rule: {rule}") + + def _epsilon_rule(self, layer, x, relevance_output, epsilon): + x_p, orig = pad_to_match(x, layer.weight.size(1)) + z = F.linear(x_p, layer.weight, layer.bias) + relevance_output = match_relevance_dim(relevance_output, z.size(1)) + z = stabilize_denominator(z, epsilon, rule="epsilon") + c = torch.einsum("bo,oi->bi", relevance_output / z, layer.weight) + result = x_p * c + if result.size(1) != orig: + result = result[:, :orig] + return result + + def _alphabeta_rule(self, layer, x, relevance_output, alpha, beta): + # The alpha-beta rule splits each *contribution* z_ij = x_i * w_ij into + # its positive and negative parts -- not the weights alone. For x_i < 0 a + # positive weight produces a negative contribution, so pairing W+ with a + # signed input mixes the two paths and lets relevance change sign even + # when beta == 0. Split the input as well: + # z+ = x+ @ W+ + x- @ W- (both products positive) + # z- = x+ @ W- + x- @ W+ (both products negative) + x_p, orig = pad_to_match(x, layer.weight.size(1)) + W_pos = torch.clamp(layer.weight, min=0) + W_neg = torch.clamp(layer.weight, max=0) + b_pos = torch.clamp(layer.bias, min=0) if layer.bias is not None else None + b_neg = torch.clamp(layer.bias, max=0) if layer.bias is not None else None + x_pos = torch.clamp(x_p, min=0) + x_neg = torch.clamp(x_p, max=0) + + z_pos = F.linear(x_pos, W_pos, b_pos) + F.linear(x_neg, W_neg, None) + 1e-9 + z_neg = F.linear(x_pos, W_neg, b_neg) + F.linear(x_neg, W_pos, None) - 1e-9 + + relevance_output = match_relevance_dim(relevance_output, z_pos.size(1)) + s_pos = relevance_output / z_pos + s_neg = relevance_output / z_neg + + c_pos = x_pos * torch.einsum("bo,oi->bi", s_pos, W_pos) + x_neg * torch.einsum( + "bo,oi->bi", s_pos, W_neg + ) + c_neg = x_pos * torch.einsum("bo,oi->bi", s_neg, W_neg) + x_neg * torch.einsum( + "bo,oi->bi", s_neg, W_pos + ) + + result = alpha * c_pos - beta * c_neg + if result.size(1) != orig: + result = result[:, :orig] + return result + + +class ReLULRPHandler(LRPLayerHandler): + """LRP handler for nn.ReLU — relevance passes through unchanged. + + Examples: + >>> import torch + >>> from torch import nn + >>> from pyhealth.interpret.methods.lrp_base import ReLULRPHandler + >>> handler = ReLULRPHandler() + >>> handler.supports(nn.ReLU()) + True + >>> relevance = torch.tensor([[1.0, -2.0]]) + >>> bool(torch.equal(handler.backward_relevance(nn.ReLU(), relevance), relevance)) + True + """ + + def __init__(self): + super().__init__(name="ReLUHandler") + + def supports(self, layer: nn.Module) -> bool: + return isinstance(layer, nn.ReLU) + + def backward_relevance(self, layer, relevance_output, **kwargs): + return relevance_output + + +class EmbeddingLRPHandler(LRPLayerHandler): + """LRP handler for nn.Embedding — sum over embedding dim. + + Examples: + >>> import torch + >>> from torch import nn + >>> from pyhealth.interpret.methods.lrp_base import EmbeddingLRPHandler + >>> handler = EmbeddingLRPHandler() + >>> handler.supports(nn.Embedding(10, 4)) + True + >>> handler.backward_relevance(nn.Embedding(10, 4), torch.ones(1, 3, 4)).shape + torch.Size([1, 3]) + """ + + def __init__(self): + super().__init__(name="EmbeddingHandler") + + def supports(self, layer: nn.Module) -> bool: + return isinstance(layer, nn.Embedding) + + def forward_hook(self, module, input, output): + input_tensor = input[0] if isinstance(input, tuple) else input + self.activations_cache[id(module)] = { + "indices": input_tensor.detach(), + "output": output.detach(), + } + + def backward_relevance(self, layer, relevance_output, **kwargs): + if relevance_output.dim() == 3: + return relevance_output.sum(dim=-1) + return relevance_output + + +# ============================================================================ +# CNN layer handlers +# ============================================================================ + + +class Conv2dLRPHandler(LRPLayerHandler): + """LRP handler for nn.Conv2d layers (epsilon and alphabeta rules). + + Examples: + >>> import torch + >>> from torch import nn + >>> from pyhealth.interpret.methods.lrp_base import Conv2dLRPHandler + >>> layer, handler = nn.Conv2d(1, 2, kernel_size=3, padding=1), Conv2dLRPHandler() + >>> x = torch.randn(1, 1, 8, 8) + >>> z = layer(x) + >>> handler.forward_hook(layer, (x,), z) + >>> handler.backward_relevance(layer, torch.ones_like(z)).shape + torch.Size([1, 1, 8, 8]) + """ + + def __init__(self): + super().__init__(name="Conv2dHandler") + + def supports(self, layer: nn.Module) -> bool: + return isinstance(layer, nn.Conv2d) + + def backward_relevance( + self, + layer: nn.Module, + relevance_output: torch.Tensor, + rule: str = "epsilon", + epsilon: float = 1e-2, + alpha: float = 1.0, + beta: float = 0.0, + **kwargs, + ) -> torch.Tensor: + cache = self._get_cached(layer) + x = cache["input"] + if rule == "epsilon": + return self._epsilon_rule(layer, x, relevance_output, epsilon) + elif rule == "alphabeta": + return self._alphabeta_rule(layer, x, relevance_output, alpha, beta, epsilon) + raise ValueError(f"Unsupported rule: {rule}") + + def _epsilon_rule(self, layer, x, relevance_output, epsilon): + conv_kw = { + "stride": layer.stride, + "padding": layer.padding, + "dilation": layer.dilation, + "groups": layer.groups, + } + z = F.conv2d(x, layer.weight, layer.bias, **conv_kw) + z = stabilize_denominator(z, epsilon, rule="epsilon") + s = relevance_output / z + out_pad = conv_output_padding(layer, z.shape, x.shape) + c = F.conv_transpose2d( + s, layer.weight, None, + stride=layer.stride, padding=layer.padding, + output_padding=out_pad, dilation=layer.dilation, groups=layer.groups, + ) + return x * crop_spatial(c, x.shape) + + def _alphabeta_rule(self, layer, x, relevance_output, alpha, beta, epsilon): + conv_kw = { + "stride": layer.stride, + "padding": layer.padding, + "dilation": layer.dilation, + "groups": layer.groups, + } + W_pos = torch.clamp(layer.weight, min=0) + W_neg = torch.clamp(layer.weight, max=0) + b_pos = torch.clamp(layer.bias, min=0) if layer.bias is not None else None + b_neg = torch.clamp(layer.bias, max=0) if layer.bias is not None else None + + # Split the input as well as the weights, so that each path collects only + # same-signed contributions z_ij = x_i * w_ij (see LinearLRPHandler): + # z+ = conv(x+, W+) + conv(x-, W-) + # z- = conv(x+, W-) + conv(x-, W+) + # Pairing W+ with a signed input would mix the two and let relevance flip + # sign even when beta == 0. + x_pos = torch.clamp(x, min=0) + x_neg = torch.clamp(x, max=0) + + z_pos = F.conv2d(x_pos, W_pos, b_pos, **conv_kw) + F.conv2d( + x_neg, W_neg, None, **conv_kw + ) + z_neg = F.conv2d(x_pos, W_neg, b_neg, **conv_kw) + F.conv2d( + x_neg, W_pos, None, **conv_kw + ) + denom_pos = z_pos + epsilon + denom_neg = z_neg - epsilon + + out_pad = conv_output_padding(layer, z_pos.shape, x.shape) + trans_kw = { + "stride": layer.stride, "padding": layer.padding, + "output_padding": out_pad, "dilation": layer.dilation, + "groups": layer.groups, + } + s_pos = relevance_output / denom_pos + s_neg = relevance_output / denom_neg + + def _back(s, W): + return crop_spatial( + F.conv_transpose2d(s, W, None, **trans_kw), x.shape + ) + + c_pos = x_pos * _back(s_pos, W_pos) + x_neg * _back(s_pos, W_neg) + c_neg = x_pos * _back(s_neg, W_neg) + x_neg * _back(s_neg, W_pos) + return alpha * c_pos - beta * c_neg + + +class MaxPool2dLRPHandler(LRPLayerHandler): + """LRP handler for nn.MaxPool2d — winner-take-all relevance routing. + + Examples: + >>> import torch + >>> from torch import nn + >>> from pyhealth.interpret.methods.lrp_base import MaxPool2dLRPHandler + >>> layer, handler = nn.MaxPool2d(kernel_size=2, stride=2), MaxPool2dLRPHandler() + >>> x = torch.randn(1, 1, 4, 4) + >>> z = layer(x) + >>> handler.forward_hook(layer, (x,), z) + >>> handler.backward_relevance(layer, torch.ones_like(z)).shape + torch.Size([1, 1, 4, 4]) + """ + + def __init__(self): + super().__init__(name="MaxPool2dHandler") + + def supports(self, layer: nn.Module) -> bool: + return isinstance(layer, nn.MaxPool2d) + + def forward_hook(self, module, input, output): + input_tensor = input[0] if isinstance(input, tuple) else input + _, indices = F.max_pool2d( + input_tensor, + kernel_size=module.kernel_size, + stride=module.stride, + padding=module.padding, + dilation=module.dilation, + return_indices=True, + ) + self.activations_cache[id(module)] = { + "input": input_tensor.detach(), + "output": output.detach(), + "indices": indices, + } + + def backward_relevance(self, layer, relevance_output, **kwargs): + cache = self._get_cached(layer) + input_shape = cache["input"].shape + try: + return F.max_unpool2d( + relevance_output, + cache["indices"], + kernel_size=layer.kernel_size, + stride=layer.stride, + padding=layer.padding, + output_size=input_shape, + ) + except RuntimeError: + return F.interpolate( + relevance_output, size=input_shape[2:], mode="nearest" + ) + + +class AvgPool2dLRPHandler(LRPLayerHandler): + """LRP handler for nn.AvgPool2d — uniform relevance distribution via transposed conv. + + Examples: + >>> import torch + >>> from torch import nn + >>> from pyhealth.interpret.methods.lrp_base import AvgPool2dLRPHandler + >>> layer, handler = nn.AvgPool2d(kernel_size=2, stride=2), AvgPool2dLRPHandler() + >>> x = torch.randn(1, 1, 4, 4) + >>> z = layer(x) + >>> handler.forward_hook(layer, (x,), z) + >>> handler.backward_relevance(layer, torch.ones_like(z)).shape + torch.Size([1, 1, 4, 4]) + """ + + def __init__(self): + super().__init__(name="AvgPool2dHandler") + + def supports(self, layer: nn.Module) -> bool: + return isinstance(layer, nn.AvgPool2d) + + def backward_relevance(self, layer, relevance_output, **kwargs): + cache = self._get_cached(layer) + x = cache["input"] + channels = relevance_output.size(1) + ks = layer.kernel_size if isinstance(layer.kernel_size, tuple) else (layer.kernel_size, layer.kernel_size) + st = layer.stride if isinstance(layer.stride, tuple) else (layer.stride, layer.stride) + pd = layer.padding if isinstance(layer.padding, tuple) else (layer.padding, layer.padding) + weight = torch.ones(channels, 1, *ks, device=x.device, dtype=x.dtype) / (ks[0] * ks[1]) + result = F.conv_transpose2d(relevance_output, weight, stride=st, padding=pd, groups=channels) + return crop_spatial(result, x.shape) + + +class AdaptiveAvgPool2dLRPHandler(LRPLayerHandler): + """LRP handler for nn.AdaptiveAvgPool2d — uniform distribution. + + Examples: + >>> import torch + >>> from torch import nn + >>> from pyhealth.interpret.methods.lrp_base import AdaptiveAvgPool2dLRPHandler + >>> layer = nn.AdaptiveAvgPool2d((1, 1)) + >>> handler = AdaptiveAvgPool2dLRPHandler() + >>> x = torch.randn(1, 2, 6, 6) + >>> z = layer(x) + >>> handler.forward_hook(layer, (x,), z) + >>> handler.backward_relevance(layer, torch.ones_like(z)).shape + torch.Size([1, 2, 6, 6]) + """ + + def __init__(self): + super().__init__(name="AdaptiveAvgPool2dHandler") + + def supports(self, layer: nn.Module) -> bool: + return isinstance(layer, nn.AdaptiveAvgPool2d) + + def backward_relevance(self, layer, relevance_output, **kwargs): + cache = self._get_cached(layer) + input_shape = cache["input"].shape + output_shape = cache["output"].shape + + # Handle flattened relevance (e.g. after a Flatten layer) + if relevance_output.dim() == 2 and len(output_shape) == 4: + relevance_output = relevance_output.view(output_shape) + + in_h, in_w = input_shape[2], input_shape[3] + out_h, out_w = relevance_output.shape[2], relevance_output.shape[3] + + if out_h == 1 and out_w == 1: + return relevance_output.expand(-1, -1, in_h, in_w) / (in_h * in_w) + + result = torch.zeros_like(cache["input"]) + stride_h, stride_w = in_h / out_h, in_w / out_w + for i in range(out_h): + for j in range(out_w): + h_s, h_e = int(i * stride_h), int((i + 1) * stride_h) + w_s, w_e = int(j * stride_w), int((j + 1) * stride_w) + region_size = (h_e - h_s) * (w_e - w_s) + result[:, :, h_s:h_e, w_s:w_e] = ( + relevance_output[:, :, i : i + 1, j : j + 1] / region_size + ) + return result + + +class FlattenLRPHandler(LRPLayerHandler): + """LRP handler for nn.Flatten — reshape relevance back. + + Examples: + >>> import torch + >>> from torch import nn + >>> from pyhealth.interpret.methods.lrp_base import FlattenLRPHandler + >>> layer, handler = nn.Flatten(), FlattenLRPHandler() + >>> x = torch.randn(1, 2, 3, 3) + >>> z = layer(x) + >>> handler.forward_hook(layer, (x,), z) + >>> handler.backward_relevance(layer, torch.ones_like(z)).shape + torch.Size([1, 2, 3, 3]) + """ + + def __init__(self): + super().__init__(name="FlattenHandler") + + def supports(self, layer: nn.Module) -> bool: + return isinstance(layer, nn.Flatten) + + def forward_hook(self, module, input, output): + input_tensor = input[0] if isinstance(input, tuple) else input + self.activations_cache[id(module)] = { + "input_shape": input_tensor.shape, + "output": output.detach(), + } + + def backward_relevance(self, layer, relevance_output, **kwargs): + return relevance_output.view(self._get_cached(layer)["input_shape"]) + + +class BatchNorm2dLRPHandler(LRPLayerHandler): + """LRP handler for nn.BatchNorm2d — pass relevance through. + + Examples: + >>> import torch + >>> from torch import nn + >>> from pyhealth.interpret.methods.lrp_base import BatchNorm2dLRPHandler + >>> handler = BatchNorm2dLRPHandler() + >>> handler.supports(nn.BatchNorm2d(3)) + True + >>> relevance = torch.ones(1, 3, 4, 4) + >>> out = handler.backward_relevance(nn.BatchNorm2d(3), relevance) + >>> bool(torch.equal(out, relevance)) + True + """ + + def __init__(self): + super().__init__(name="BatchNorm2dHandler") + + def supports(self, layer: nn.Module) -> bool: + return isinstance(layer, nn.BatchNorm2d) + + def backward_relevance(self, layer, relevance_output, **kwargs): + return relevance_output + + +class DropoutLRPHandler(LRPLayerHandler): + """LRP handler for nn.Dropout — identity in eval mode. + + Examples: + >>> import torch + >>> from torch import nn + >>> from pyhealth.interpret.methods.lrp_base import DropoutLRPHandler + >>> handler = DropoutLRPHandler() + >>> handler.supports(nn.Dropout(0.5)) + True + >>> relevance = torch.ones(1, 4) + >>> bool(torch.equal(handler.backward_relevance(nn.Dropout(), relevance), relevance)) + True + """ + + def __init__(self): + super().__init__(name="DropoutHandler") + + def supports(self, layer: nn.Module) -> bool: + return isinstance(layer, nn.Dropout) + + def backward_relevance(self, layer, relevance_output, **kwargs): + return relevance_output + + +class RNNLRPHandler(LRPLayerHandler): + """LRP handler for nn.LSTM and nn.GRU. + + LRP for recurrent layers is an active research area; this implementation + uses the simple heuristic of distributing the hidden-state relevance + uniformly across all input time-steps, which is consistent with the + epsilon-rule interpretation of the recurrent read-out. + + Examples: + >>> import torch + >>> from torch import nn + >>> from pyhealth.interpret.methods.lrp_base import RNNLRPHandler + >>> layer = nn.LSTM(input_size=4, hidden_size=3, batch_first=True) + >>> handler = RNNLRPHandler() + >>> x = torch.randn(1, 5, 4) + >>> out, _ = layer(x) + >>> handler.forward_hook(layer, (x,), out) + >>> handler.backward_relevance(layer, torch.ones(1, 3)).shape + torch.Size([1, 5, 3]) + """ + + def __init__(self): + super().__init__(name="RNNHandler") + + def supports(self, layer: nn.Module) -> bool: + return isinstance(layer, (nn.LSTM, nn.GRU)) + + def backward_relevance(self, layer, relevance_output, **kwargs): + cache = self._get_cached(layer) + x = cache["input"] + if x.dim() == 3: + # relevance_output: [B, H] → distribute equally over T timesteps. + # Dividing by T preserves the total relevance sum (Eq. 2 conservation). + T = x.shape[1] + return (relevance_output.unsqueeze(1) / T).expand(x.shape[0], T, -1).contiguous() + return relevance_output + + +# ============================================================================ +# Default registry +# ============================================================================ + + +def create_default_registry() -> LRPHandlerRegistry: + """Create a registry with handlers for all supported layer types. + + Examples: + >>> from torch import nn + >>> from pyhealth.interpret.methods.lrp_base import create_default_registry + >>> registry = create_default_registry() + >>> registry.get_handler(nn.Linear(4, 2)).name + 'LinearHandler' + >>> registry.get_handler(nn.Conv2d(1, 1, 3)).name + 'Conv2dHandler' + """ + registry = LRPHandlerRegistry() + registry.register(LinearLRPHandler()) + registry.register(ReLULRPHandler()) + registry.register(EmbeddingLRPHandler()) + registry.register(Conv2dLRPHandler()) + registry.register(MaxPool2dLRPHandler()) + registry.register(AvgPool2dLRPHandler()) + registry.register(AdaptiveAvgPool2dLRPHandler()) + registry.register(FlattenLRPHandler()) + registry.register(BatchNorm2dLRPHandler()) + registry.register(DropoutLRPHandler()) + registry.register(RNNLRPHandler()) + return registry diff --git a/pyhealth/interpret/methods/saliency_visualization.py b/pyhealth/interpret/methods/saliency_visualization.py new file mode 100644 index 0000000000..18a4ba3692 --- /dev/null +++ b/pyhealth/interpret/methods/saliency_visualization.py @@ -0,0 +1,493 @@ +""" +Saliency Map Visualization Utilities for PyHealth Interpretability Methods. + +This module provides visualization tools for various attribution methods including: +- Gradient-based saliency maps +- Layer-wise Relevance Propagation (LRP) +- Integrated Gradients +- Other attribution methods + +The visualizations support both grayscale and RGB images with customizable +overlays and color maps. +""" + + +import numpy as np +import torch + + +class SaliencyVisualizer: + """Unified visualization class for saliency maps and attribution results. + + This class provides methods to visualize attribution results from various + interpretability methods. It handles tensor-to-image conversion, normalization, + and overlay generation for intuitive interpretation of model decisions. + + Examples: + >>> from pyhealth.interpret.methods import BasicGradient, SaliencyVisualizer + >>> import matplotlib.pyplot as plt + >>> + >>> # Initialize visualizer + >>> visualizer = SaliencyVisualizer() + >>> + >>> # Visualize gradient saliency + >>> gradient = BasicGradient(model) + >>> attributions = gradient.attribute(**batch) + >>> visualizer.plot_saliency_overlay( + ... plt, + ... image=batch['image'][0], + ... saliency=attributions['image'][0], + ... title="Gradient Saliency" + ... ) + """ + + def __init__( + self, + default_cmap: str = 'hot', + default_alpha: float = 0.3, + figure_size: tuple[int, int] = (15, 7) + ): + """Initialize the saliency visualizer. + + Args: + default_cmap: Default colormap for saliency overlay (e.g., 'hot', 'jet', 'viridis') + default_alpha: Default transparency for overlay (0.0 to 1.0) + figure_size: Default figure size (width, height) in inches + """ + self.default_cmap = default_cmap + self.default_alpha = default_alpha + self.figure_size = figure_size + + def plot_saliency_overlay( + self, + plt, + image: torch.Tensor | np.ndarray, + saliency: torch.Tensor | np.ndarray, + title: str | None = None, + alpha: float | None = None, + cmap: str | None = None, + normalize: bool = True, + show: bool = True, + save_path: str | None = None + ) -> None: + """Plot image with saliency map overlay. + + Args: + plt: matplotlib.pyplot instance + image: Input image tensor [C, H, W] or [H, W] or [H, W, C] + saliency: Saliency map tensor [H, W] or [C, H, W] + title: Optional title for the plot + alpha: Transparency of saliency overlay (default: uses self.default_alpha) + cmap: Colormap for saliency (default: uses self.default_cmap) + normalize: Whether to normalize saliency values to [0, 1] + show: Whether to call plt.show() + save_path: Optional path to save the figure + """ + if alpha is None: + alpha = self.default_alpha + if cmap is None: + cmap = self.default_cmap + + # Convert tensors to numpy + img_np = self._to_numpy(image) + sal_np = self._to_numpy(saliency) + + # Process image dimensions + img_np = self._process_image(img_np) + + # Process saliency dimensions + sal_np = self._process_saliency(sal_np) + + # Normalize saliency if requested + if normalize: + sal_np = self._normalize_saliency(sal_np) + + # Create visualization + plt.figure(figsize=self.figure_size) + plt.axis('off') + + # Display image + if img_np.ndim == 2 or (img_np.ndim == 3 and img_np.shape[-1] == 1): + plt.imshow(img_np.squeeze(), cmap='gray') + else: + plt.imshow(img_np) + + # Overlay saliency + plt.imshow(sal_np, cmap=cmap, alpha=alpha) + + if title: + plt.title(title, fontsize=14) + + plt.colorbar(label='Attribution Magnitude', fraction=0.046, pad=0.04) + + if save_path: + plt.savefig(save_path, bbox_inches='tight', dpi=150) + + if show: + plt.show() + + def plot_multiple_attributions( + self, + plt, + image: torch.Tensor | np.ndarray, + attributions: dict[str, torch.Tensor | np.ndarray], + method_names: dict[str, str] | None = None, + alpha: float | None = None, + cmap: str | None = None, + normalize: bool = True, + save_path: str | None = None + ) -> None: + """Plot multiple attribution methods side-by-side for comparison. + + Args: + plt: matplotlib.pyplot instance + image: Input image tensor + attributions: Dictionary mapping method keys to attribution tensors + method_names: Optional dictionary mapping keys to display names + alpha: Transparency of saliency overlay + cmap: Colormap for saliency + normalize: Whether to normalize saliency values + save_path: Optional path to save the figure + """ + if alpha is None: + alpha = self.default_alpha + if cmap is None: + cmap = self.default_cmap + + num_methods = len(attributions) + _fig, axes = plt.subplots( + 1, num_methods + 1, figsize=(5 * (num_methods + 1), 5) + ) + + # Convert image to numpy + img_np = self._process_image(self._to_numpy(image)) + + # Display original image + if img_np.ndim == 2 or (img_np.ndim == 3 and img_np.shape[-1] == 1): + axes[0].imshow(img_np.squeeze(), cmap='gray') + else: + axes[0].imshow(img_np) + axes[0].set_title('Original Image', fontsize=12) + axes[0].axis('off') + + # Display each attribution method + for idx, (key, attribution) in enumerate(attributions.items(), start=1): + sal_np = self._process_saliency(self._to_numpy(attribution)) + + if normalize: + sal_np = self._normalize_saliency(sal_np) + + # Show image with overlay + if img_np.ndim == 2 or (img_np.ndim == 3 and img_np.shape[-1] == 1): + axes[idx].imshow(img_np.squeeze(), cmap='gray') + else: + axes[idx].imshow(img_np) + + im = axes[idx].imshow(sal_np, cmap=cmap, alpha=alpha) + + # Set title + title = method_names.get(key, key) if method_names else key + axes[idx].set_title(title, fontsize=12) + axes[idx].axis('off') + + # Add colorbar + plt.colorbar(im, ax=axes[idx], fraction=0.046, pad=0.04) + + plt.tight_layout() + + if save_path: + plt.savefig(save_path, bbox_inches='tight', dpi=150) + + plt.show() + + def plot_saliency_heatmap( + self, + plt, + saliency: torch.Tensor | np.ndarray, + title: str | None = None, + cmap: str | None = None, + normalize: bool = True, + show: bool = True, + save_path: str | None = None + ) -> None: + """Plot saliency map as a standalone heatmap (no image overlay). + + Args: + plt: matplotlib.pyplot instance + saliency: Saliency map tensor [H, W] or [C, H, W] + title: Optional title for the plot + cmap: Colormap for heatmap (default: uses self.default_cmap) + normalize: Whether to normalize saliency values + show: Whether to call plt.show() + save_path: Optional path to save the figure + """ + if cmap is None: + cmap = self.default_cmap + + # Convert and process saliency + sal_np = self._process_saliency(self._to_numpy(saliency)) + + if normalize: + sal_np = self._normalize_saliency(sal_np) + + # Create heatmap + plt.figure(figsize=self.figure_size) + plt.imshow(sal_np, cmap=cmap) + plt.colorbar(label='Attribution Magnitude') + + if title: + plt.title(title, fontsize=14) + + plt.axis('off') + + if save_path: + plt.savefig(save_path, bbox_inches='tight', dpi=150) + + if show: + plt.show() + + def plot_attribution_distribution( + self, + plt, + attributions: torch.Tensor | np.ndarray, + title: str | None = None, + bins: int = 50, + show: bool = True, + save_path: str | None = None + ) -> None: + """Plot histogram of attribution values. + + Useful for understanding the distribution of attribution magnitudes. + + Args: + plt: matplotlib.pyplot instance + attributions: Attribution tensor of any shape + title: Optional title for the plot + bins: Number of histogram bins + show: Whether to call plt.show() + save_path: Optional path to save the figure + """ + # Convert to numpy and flatten + attr_np = self._to_numpy(attributions).flatten() + + plt.figure(figsize=(10, 6)) + plt.hist(attr_np, bins=bins, alpha=0.7, edgecolor='black') + plt.xlabel('Attribution Value', fontsize=12) + plt.ylabel('Frequency', fontsize=12) + + if title: + plt.title(title, fontsize=14) + else: + plt.title('Attribution Value Distribution', fontsize=14) + + plt.grid(True, alpha=0.3) + + # Add statistics + mean_val = np.mean(attr_np) + median_val = np.median(attr_np) + plt.axvline(mean_val, color='r', linestyle='--', label=f'Mean: {mean_val:.4f}') + plt.axvline(median_val, color='g', linestyle='--', label=f'Median: {median_val:.4f}') + plt.legend() + + if save_path: + plt.savefig(save_path, bbox_inches='tight', dpi=150) + + if show: + plt.show() + + def plot_top_k_features( + self, + plt, + image: torch.Tensor | np.ndarray, + attributions: torch.Tensor | np.ndarray, + k: int = 10, + title: str | None = None, + show: bool = True, + save_path: str | None = None + ) -> None: + """Highlight top-k most important pixels/features. + + Args: + plt: matplotlib.pyplot instance + image: Input image tensor + attributions: Attribution tensor + k: Number of top features to highlight + title: Optional title for the plot + show: Whether to call plt.show() + save_path: Optional path to save the figure + """ + # Convert to numpy + img_np = self._process_image(self._to_numpy(image)) + attr_np = self._process_saliency(self._to_numpy(attributions)) + + # Find top-k positions + flat_attr = attr_np.flatten() + top_k_indices = np.argsort(np.abs(flat_attr))[-k:] + + # Create mask + mask = np.zeros_like(flat_attr) + mask[top_k_indices] = 1 + mask = mask.reshape(attr_np.shape) + + # Create visualization + fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5)) + + # Original image with saliency + if img_np.ndim == 2 or (img_np.ndim == 3 and img_np.shape[-1] == 1): + ax1.imshow(img_np.squeeze(), cmap='gray') + else: + ax1.imshow(img_np) + ax1.imshow(attr_np, cmap=self.default_cmap, alpha=self.default_alpha) + ax1.set_title('Full Attribution Map', fontsize=12) + ax1.axis('off') + + # Top-k features + if img_np.ndim == 2 or (img_np.ndim == 3 and img_np.shape[-1] == 1): + ax2.imshow(img_np.squeeze(), cmap='gray') + else: + ax2.imshow(img_np) + ax2.imshow(mask, cmap='Reds', alpha=0.5) + ax2.set_title(f'Top-{k} Most Important Features', fontsize=12) + ax2.axis('off') + + if title: + fig.suptitle(title, fontsize=14) + + plt.tight_layout() + + if save_path: + plt.savefig(save_path, bbox_inches='tight', dpi=150) + + if show: + plt.show() + + # Helper methods + + def _to_numpy(self, tensor: torch.Tensor | np.ndarray) -> np.ndarray: + """Convert tensor to numpy array.""" + if isinstance(tensor, torch.Tensor): + return tensor.detach().cpu().numpy() + return np.array(tensor) + + def _process_image(self, img: np.ndarray) -> np.ndarray: + """Process image to HWC or HW format for visualization. + + Args: + img: Image array in various formats + + Returns: + Processed image array ready for visualization + """ + # Remove batch dimension if present + if img.ndim == 4: + img = img[0] + + # Convert CHW to HWC for color images + if img.ndim == 3 and img.shape[0] in [1, 3]: + img = np.transpose(img, (1, 2, 0)) + + # Squeeze single channel + if img.ndim == 3 and img.shape[-1] == 1: + img = img.squeeze(-1) + + # Ensure values are in reasonable range for display + if img.max() > 1.0 and img.max() <= 255.0: + img = img / 255.0 + + return img + + def _process_saliency(self, saliency: np.ndarray) -> np.ndarray: + """Process saliency map to 2D format. + + Args: + saliency: Saliency array in various formats + + Returns: + 2D saliency array + """ + # Remove batch dimension if present + if saliency.ndim == 4: + saliency = saliency[0] + + # For multi-channel saliency, aggregate across channels + if saliency.ndim == 3: + # Take absolute maximum across channels or sum + saliency = np.sum(np.abs(saliency), axis=0) + + return saliency + + def _normalize_saliency(self, saliency: np.ndarray, percentile_clip: float = 1.0) -> np.ndarray: + """Normalize saliency values to [0, 1] range with optional percentile clipping. + + Percentile clipping removes extreme outliers before normalization so that the + color scale spans the meaningful value range rather than being dominated by a + few extreme pixels (common with LRP which produces heavy-tailed distributions). + + For signed attributions (e.g. LRP epsilon rule, which can have both positive and + negative relevance that nearly cancels), normalization is applied to the absolute + values so that high-magnitude pixels — excitatory *and* inhibitory — appear as + hotspots rather than averaging to the midpoint of the colormap. + + Args: + saliency: Saliency array + percentile_clip: Clip values below this percentile and above (100 - + percentile_clip) before normalizing. Set to 0 for pure min-max. + + Returns: + Normalized saliency array in [0, 1] + """ + # If the attribution is meaningfully signed (significant negative values), + # work on magnitudes so positive and negative evidence both appear bright. + max_abs = np.abs(saliency).max() + if max_abs > 1e-8 and saliency.min() < -0.1 * max_abs: + saliency = np.abs(saliency) + + if percentile_clip > 0: + low = np.percentile(saliency, percentile_clip) + high = np.percentile(saliency, 100 - percentile_clip) + saliency = np.clip(saliency, low, high) + + min_val = saliency.min() + max_val = saliency.max() + + if max_val - min_val > 1e-8: + return (saliency - min_val) / (max_val - min_val) + else: + return np.zeros_like(saliency) + + +# Convenience function for quick visualization +def visualize_attribution( + plt, + image: torch.Tensor | np.ndarray, + attribution: torch.Tensor | np.ndarray, + title: str | None = None, + method: str = 'overlay', + **kwargs +) -> None: + """Quick visualization of attribution results. + + Convenience function that creates a SaliencyVisualizer and plots. + + Args: + plt: matplotlib.pyplot instance + image: Input image + attribution: Attribution map + title: Optional title + method: Visualization method ('overlay', 'heatmap', 'top_k') + **kwargs: Additional arguments passed to the visualization method + + Examples: + >>> import matplotlib.pyplot as plt + >>> visualize_attribution(plt, image, attribution, title="Gradient") + """ + visualizer = SaliencyVisualizer() + + if method == 'overlay': + visualizer.plot_saliency_overlay(plt, image, attribution, title, **kwargs) + elif method == 'heatmap': + visualizer.plot_saliency_heatmap(plt, attribution, title, **kwargs) + elif method == 'top_k': + visualizer.plot_top_k_features(plt, image, attribution, title=title, **kwargs) + else: + raise ValueError(f"Unknown visualization method: {method}") diff --git a/pyhealth/metrics/interpretability/base.py b/pyhealth/metrics/interpretability/base.py index 23634a4088..263f5362c6 100644 --- a/pyhealth/metrics/interpretability/base.py +++ b/pyhealth/metrics/interpretability/base.py @@ -4,6 +4,7 @@ metrics like Comprehensiveness and Sufficiency. """ +import warnings from abc import ABC, abstractmethod from typing import Dict, List, Optional @@ -161,6 +162,39 @@ def _detect_classifier_type(self): print("[RemovalBasedMetric] WARNING: Unknown classifier") print(f" - Mode detected: {mode}") + def _mean_baseline(self, x: torch.Tensor) -> torch.Tensor: + """Replacement values for the ``"mean"`` ablation strategy. + + The across-batch mean is only a meaningful baseline when there is more + than one sample. With ``batch_size == 1``, ``x.mean(dim=0)`` *is* ``x``, + so ``x * (1 - mask) + x_mean * mask`` reduces to ``x`` and the ablation + silently does nothing -- every score comes back exactly 0.0, which for + sufficiency (lower is better) looks like a perfect result rather than a + no-op. Since ``batch_size=1`` is the usual setting for per-sample + interpretability, fall back to each sample's mean over its own feature + dimensions, which is a genuine uninformative baseline. + + Args: + x: Input tensor with the batch on dimension 0. + + Returns: + Tensor broadcastable to ``x`` holding the replacement values. + """ + if x.shape[0] > 1: + return x.mean(dim=0, keepdim=True) + + warnings.warn( + "ablation_strategy='mean' with batch_size=1: the across-batch mean " + "equals the sample itself, which would make ablation a no-op. " + "Falling back to the sample's mean over its feature dimensions. " + "Pass more than one sample to get a per-feature batch mean.", + RuntimeWarning, + stacklevel=3, + ) + if x.dim() == 1: + return x.mean().expand_as(x) + return x.mean(dim=tuple(range(1, x.dim())), keepdim=True) + @abstractmethod def _create_ablated_inputs( self, @@ -274,7 +308,7 @@ def _apply_ablation( if self.ablation_strategy == "zero": ablated_values = x_values * (1 - mask) elif self.ablation_strategy == "mean": - x_mean = x_values.mean(dim=0, keepdim=True) + x_mean = self._mean_baseline(x_values) ablated_values = x_values * (1 - mask) + x_mean * mask elif self.ablation_strategy == "noise": noise = torch.randn_like(x_values) * x_values.std() @@ -315,8 +349,8 @@ def _apply_ablation( ablated_inputs[key] = x * (1 - mask) elif self.ablation_strategy == "mean": - # Set ablated features to mean across batch - x_mean = x.mean(dim=0, keepdim=True) + # Set ablated features to a mean baseline (see _mean_baseline) + x_mean = self._mean_baseline(x) ablated_inputs[key] = x * (1 - mask) + x_mean * mask elif self.ablation_strategy == "noise": diff --git a/tests/core/test_interp_metrics.py b/tests/core/test_interp_metrics.py index f61943b3a5..a27881546c 100644 --- a/tests/core/test_interp_metrics.py +++ b/tests/core/test_interp_metrics.py @@ -8,6 +8,7 @@ """ import unittest +import warnings import torch @@ -537,3 +538,71 @@ def test_sufficiency_decreases_with_retention(self): if __name__ == "__main__": # Run tests unittest.main() + + +class TestMeanAblationBaseline(unittest.TestCase): + """The 'mean' ablation strategy must actually modify the input. + + Regression test: ``x.mean(dim=0)`` over a batch of one *is* that sample, so + ``x * (1 - mask) + x_mean * mask`` used to reduce to ``x``. Ablation became a + silent no-op and every score came back exactly 0.0 -- which for sufficiency + (lower is better) reads as a perfect result rather than a broken one. + """ + + def _metric(self): + return ComprehensivenessMetric.__new__(ComprehensivenessMetric) + + def test_mean_ablation_changes_input_at_batch_size_one(self): + metric = self._metric() + x = torch.randn(1, 3, 8, 8) + mask = torch.zeros_like(x) + mask[..., :4, :] = 1 + + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + baseline = metric._mean_baseline(x) + caught_msgs = [str(c.message) for c in caught] + + ablated = x * (1 - mask) + baseline * mask + self.assertFalse( + torch.equal(ablated, x), + "mean ablation must not be a no-op at batch_size=1", + ) + self.assertTrue( + any("batch_size=1" in m for m in caught_msgs), + "falling back to a per-sample mean should warn", + ) + + def test_mean_ablation_keeps_batch_mean_for_real_batches(self): + metric = self._metric() + x = torch.randn(4, 3, 8, 8) + baseline = metric._mean_baseline(x) + self.assertTrue(torch.allclose(baseline, x.mean(dim=0, keepdim=True))) + self.assertEqual(tuple(baseline.shape), (1, 3, 8, 8)) + + def test_mean_baseline_for_1d_input(self): + metric = self._metric() + x = torch.tensor([1.0, 2.0, 6.0]) # batch of one, no feature dims + with warnings.catch_warnings(): + warnings.simplefilter("ignore", RuntimeWarning) + baseline = metric._mean_baseline(x[:1]) + baseline_3 = metric._mean_baseline(x.unsqueeze(0)) + self.assertEqual(baseline.shape, (1,)) + self.assertTrue(torch.allclose(baseline_3, torch.full((1, 1), 3.0))) + + def test_apply_ablation_mean_uses_baseline(self): + metric = self._metric() + metric.ablation_strategy = "mean" + x = torch.tensor([[1.0, 2.0, 3.0, 6.0]]) + mask = torch.tensor([[1.0, 0.0, 0.0, 1.0]]) + times = torch.zeros(1, 4) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", RuntimeWarning) + out = metric._apply_ablation( + {"plain": x, "tupled": (times, x)}, + {"plain": mask, "tupled": mask}, + ) + expected = torch.tensor([[3.0, 2.0, 3.0, 3.0]]) + self.assertTrue(torch.allclose(out["plain"], expected)) + self.assertIs(out["tupled"][0], times) + self.assertTrue(torch.allclose(out["tupled"][1], expected)) diff --git a/tests/core/test_lrp.py b/tests/core/test_lrp.py new file mode 100644 index 0000000000..c5330a6b02 --- /dev/null +++ b/tests/core/test_lrp.py @@ -0,0 +1,1328 @@ +""" +Comprehensive tests for Layer-wise Relevance Propagation (LRP). + +This test suite covers: +1. LRP initialization with different rules +2. Attribution computation and shapes +3. Relevance conservation property (with acceptable tolerances) +4. Comparison of different LRP rules (epsilon vs alpha-beta) +5. End-to-end integration with PyHealth MLP models +6. Embedding-based models (discrete medical codes) + +Note on ResNet support: +- LRP uses sequential approximation for ResNet architectures +- Downsample layers (parallel paths) are excluded during hook registration +- This is a standard approach in the LRP literature +""" + +import unittest +import torch +import numpy as np +import tempfile +import shutil +import pickle +import os +import litdata + +import random + +from pyhealth.datasets import SampleDataset, create_sample_dataset +from pyhealth.datasets.sample_dataset import SampleBuilder +from pyhealth.interpret.methods import LayerwiseRelevancePropagation +from pyhealth.models import MLP, StageNet + + +class TestLRPInitialization(unittest.TestCase): + """Test LRP initialization and setup.""" + + def setUp(self): + """Set up test fixtures.""" + self.temp_dir = None + self.simple_dataset = self._create_simple_dataset() + self.trained_model = self._create_trained_model() + + def tearDown(self): + """Clean up after tests.""" + if self.temp_dir: + shutil.rmtree(self.temp_dir, ignore_errors=True) + + def _create_simple_dataset(self): + """Create a simple synthetic dataset for testing.""" + samples = [ + { + "patient_id": f"patient-{i}", + "visit_id": f"visit-0", + "conditions": [f"cond-{j}" for j in range(3)], + "labs": [float(j) for j in range(4)], + "label": i % 2, + } + for i in range(20) + ] + self.temp_dir = tempfile.mkdtemp() + builder = SampleBuilder( + input_schema={"conditions": "sequence", "labs": "tensor"}, + output_schema={"label": "binary"}, + ) + builder.fit(samples) + builder.save(f"{self.temp_dir}/schema.pkl") + def sample_generator(): + for sample in samples: + yield {"sample": pickle.dumps(sample)} + litdata.optimize( + fn=builder.transform, + inputs=list(sample_generator()), + output_dir=self.temp_dir, + num_workers=1, + chunk_bytes="64MB", + ) + dataset = SampleDataset(path=self.temp_dir, dataset_name="test_dataset") + return dataset + + def _create_trained_model(self): + """Create and return a simple trained model.""" + model = MLP( + dataset=self.simple_dataset, + feature_keys=["conditions", "labs"], + embedding_dim=32, + hidden_dim=32, + dropout=0.0, + ) + model.eval() + return model + + def test_init_epsilon_rule(self): + """Test initialization with epsilon rule.""" + lrp = LayerwiseRelevancePropagation( + self.trained_model, rule="epsilon", epsilon=0.01 + ) + self.assertEqual(lrp.rule, "epsilon") + self.assertEqual(lrp.epsilon, 0.01) + self.assertIsNotNone(lrp.model) + + def test_init_alphabeta_rule(self): + """Test initialization with alphabeta rule.""" + lrp = LayerwiseRelevancePropagation( + self.trained_model, rule="alphabeta", alpha=1.0, beta=0.0 + ) + self.assertEqual(lrp.rule, "alphabeta") + self.assertEqual(lrp.alpha, 1.0) + self.assertEqual(lrp.beta, 0.0) + + def test_init_requires_forward_from_embedding(self): + """Test that model must have forward_from_embedding when use_embeddings=True.""" + # MLP has forward_from_embedding, so this should work + lrp = LayerwiseRelevancePropagation(self.trained_model, use_embeddings=True) + self.assertTrue(lrp.use_embeddings) + + +class TestLRPAttributions(unittest.TestCase): + """Test LRP attribution computation.""" + + def setUp(self): + """Set up test fixtures.""" + self.temp_dir = None + self.simple_dataset = self._create_simple_dataset() + self.trained_model = self._create_trained_model() + self.test_batch = self._create_test_batch() + + def tearDown(self): + """Clean up after tests.""" + if self.temp_dir: + shutil.rmtree(self.temp_dir, ignore_errors=True) + + def _create_simple_dataset(self): + """Create a simple synthetic dataset for testing.""" + samples = [ + { + "patient_id": f"patient-{i}", + "visit_id": f"visit-0", + "conditions": [f"cond-{j}" for j in range(3)], + "labs": [float(j) for j in range(4)], + "label": i % 2, + } + for i in range(20) + ] + self.temp_dir = tempfile.mkdtemp() + builder = SampleBuilder( + input_schema={"conditions": "sequence", "labs": "tensor"}, + output_schema={"label": "binary"}, + ) + builder.fit(samples) + builder.save(f"{self.temp_dir}/schema.pkl") + def sample_generator(): + for sample in samples: + yield {"sample": pickle.dumps(sample)} + litdata.optimize( + fn=builder.transform, + inputs=list(sample_generator()), + output_dir=self.temp_dir, + num_workers=1, + chunk_bytes="64MB", + ) + return SampleDataset(path=self.temp_dir, dataset_name="test_dataset") + + def _create_trained_model(self): + """Create and return a simple trained model.""" + model = MLP( + dataset=self.simple_dataset, + feature_keys=["conditions", "labs"], + embedding_dim=32, + hidden_dim=32, + dropout=0.0, + ) + model.eval() + return model + + def _create_test_batch(self): + """Create a test batch.""" + raw_sample = { + "patient_id": "patient-0", + "visit_id": "visit-0", + "conditions": ["cond-0", "cond-1", "cond-2"], + "labs": [0.0, 1.0, 2.0, 3.0], + "label": 0, + } + processed = {} + for key, processor in self.simple_dataset.input_processors.items(): + if key in raw_sample: + processed[key] = processor.process(raw_sample[key]) + for key, processor in self.simple_dataset.output_processors.items(): + if key in raw_sample: + processed[key] = processor.process(raw_sample[key]) + batch = {} + for key, value in processed.items(): + if isinstance(value, torch.Tensor): + batch[key] = value.unsqueeze(0) + else: + batch[key] = torch.tensor([value]) + batch["patient_id"] = [raw_sample["patient_id"]] + return batch + + def test_attribution_shape(self): + """Test that attributions have correct shapes.""" + lrp = LayerwiseRelevancePropagation(self.trained_model, rule="epsilon") + attributions = lrp.attribute(**self.test_batch) + + # Check that we have attributions for each feature + self.assertIn("conditions", attributions) + self.assertIn("labs", attributions) + + # Check shapes match input shapes + self.assertEqual(attributions["conditions"].shape[0], self.test_batch["conditions"].shape[0]) + self.assertEqual(attributions["labs"].shape[0], self.test_batch["labs"].shape[0]) + + def test_attribution_types(self): + """Test that attributions are tensors.""" + lrp = LayerwiseRelevancePropagation(self.trained_model) + attributions = lrp.attribute(**self.test_batch) + + for key, attr in attributions.items(): + self.assertIsInstance(attr, torch.Tensor) + + def test_epsilon_rule_attributions(self): + """Test epsilon rule produces valid attributions.""" + lrp = LayerwiseRelevancePropagation(self.trained_model, rule="epsilon", epsilon=0.01) + attributions = lrp.attribute(**self.test_batch, target_class_idx=1) + + # Attributions should contain numbers (not NaN or Inf) + for key, attr in attributions.items(): + self.assertFalse(torch.isnan(attr).any()) + self.assertFalse(torch.isinf(attr).any()) + + def test_alphabeta_rule_attributions(self): + """Test alphabeta rule produces valid attributions.""" + lrp = LayerwiseRelevancePropagation( + self.trained_model, rule="alphabeta", alpha=1.0, beta=0.0 + ) + attributions = lrp.attribute(**self.test_batch, target_class_idx=1) + + # Attributions should contain numbers (not NaN or Inf) + for key, attr in attributions.items(): + self.assertFalse(torch.isnan(attr).any()) + self.assertFalse(torch.isinf(attr).any()) + + +class TestRelevanceConservation(unittest.TestCase): + """Test the relevance conservation property of LRP.""" + + def setUp(self): + """Set up fixtures for each test.""" + self.temp_dir = None + self.simple_dataset = self._create_simple_dataset() + self.trained_model = self._create_trained_model() + self.test_batch = self._create_test_batch() + + def tearDown(self): + """Clean up temporary directory.""" + if self.temp_dir and os.path.exists(self.temp_dir): + shutil.rmtree(self.temp_dir, ignore_errors=True) + + def _create_simple_dataset(self): + """Create a simple dataset for testing.""" + # Create synthetic data + samples = [] + for i in range(20): + samples.append({ + "patient_id": f"patient-{i}", + "visit_id": f"visit-{i}", + "conditions": [f"cond-{j}" for j in range(5)], + "labs": np.random.rand(4).tolist(), + "label": i % 2, + }) + + # Create temporary directory + self.temp_dir = tempfile.mkdtemp() + + # Build dataset using SampleBuilder + builder = SampleBuilder( + input_schema={"conditions": "sequence", "labs": "tensor"}, + output_schema={"label": "binary"}, + ) + builder.fit(samples) + builder.save(f"{self.temp_dir}/schema.pkl") + + # Optimize samples + def sample_generator(): + for sample in samples: + yield {"sample": pickle.dumps(sample)} + + litdata.optimize( + fn=builder.transform, + inputs=list(sample_generator()), + output_dir=self.temp_dir, + num_workers=1, + chunk_bytes="64MB", + ) + + dataset = SampleDataset( + path=self.temp_dir, + dataset_name="test_mlp", + ) + return dataset + + def _create_trained_model(self): + """Create and return a trained model.""" + model = MLP( + dataset=self.simple_dataset, + feature_keys=["conditions", "labs"], + embedding_dim=32, + hidden_dim=32, + dropout=0.0, + ) + model.eval() + return model + + def _create_test_batch(self): + """Create a test batch from the dataset.""" + sample = self.simple_dataset[0] + batch = {} + for key, value in sample.items(): + if isinstance(value, torch.Tensor): + batch[key] = value.unsqueeze(0) + elif key not in ["patient_id", "visit_id"]: + if isinstance(value, (int, float)): + batch[key] = torch.tensor([value]) + return batch + + def test_relevance_sums_to_output(self): + """Test that sum of relevances approximately equals model output. + + This is the key property of LRP: conservation. + Sum of input relevances ≈ f(x) for the target class. + + The epsilon rule is only *approximately* conservative: for each Linear + layer the per-layer conservation ratio is (Wx)/(Wx+b+ε). With a + randomly-initialised model the logit is tiny, so biases can be + comparable in magnitude and cause multi-hundred-percent relative + error even though the absolute error is small. The 3× bound below + is therefore a structural sanity check (catch NaN, sign-flips from + catastrophic cancellation, or broken split logic) rather than a + tight conservation guarantee. Tight conservation (≤15 %) is expected + for trained models where |logit| ≫ |bias|. + """ + lrp = LayerwiseRelevancePropagation(self.trained_model, rule="epsilon", epsilon=0.01) + + # Get model output + with torch.no_grad(): + output = self.trained_model(**self.test_batch) + logit = output["logit"][0, 0].item() + + # Get LRP attributions + attributions = lrp.attribute(**self.test_batch, target_class_idx=1) + + # Sum all relevances + total_relevance = sum(attr.sum().item() for attr in attributions.values()) + + # Check conservation — 3× bound is the structural safety net + print(f"\nLogit: {logit:.4f}, Total relevance: {total_relevance:.4f}") + relative_diff = abs(total_relevance - logit) / max(abs(logit), 1e-6) + print(f"Relative difference: {relative_diff:.2%}") + + self.assertLess(relative_diff, 3.0, + f"Conservation violated beyond acceptable threshold: " + f"total_relevance={total_relevance:.4f}, logit={logit:.4f}, " + f"relative_diff={relative_diff:.2%}" + ) + + +class TestDifferentRules(unittest.TestCase): + """Test that different rules produce different results.""" + + def setUp(self): + """Set up fixtures for each test.""" + self.temp_dir = None + self.simple_dataset = self._create_simple_dataset() + self.trained_model = self._create_trained_model() + self.test_batch = self._create_test_batch() + + def tearDown(self): + """Clean up temporary directory.""" + if self.temp_dir and os.path.exists(self.temp_dir): + shutil.rmtree(self.temp_dir, ignore_errors=True) + + def _create_simple_dataset(self): + """Create a simple dataset for testing.""" + # Create synthetic data + samples = [] + for i in range(20): + samples.append({ + "patient_id": f"patient-{i}", + "visit_id": f"visit-{i}", + "conditions": [f"cond-{j}" for j in range(5)], + "labs": np.random.rand(4).tolist(), + "label": i % 2, + }) + + # Create temporary directory + self.temp_dir = tempfile.mkdtemp() + + # Build dataset using SampleBuilder + builder = SampleBuilder( + input_schema={"conditions": "sequence", "labs": "tensor"}, + output_schema={"label": "binary"}, + ) + builder.fit(samples) + builder.save(f"{self.temp_dir}/schema.pkl") + + # Optimize samples + def sample_generator(): + for sample in samples: + yield {"sample": pickle.dumps(sample)} + + litdata.optimize( + fn=builder.transform, + inputs=list(sample_generator()), + output_dir=self.temp_dir, + num_workers=1, + chunk_bytes="64MB", + ) + + dataset = SampleDataset( + path=self.temp_dir, + dataset_name="test_mlp", + ) + return dataset + + def _create_trained_model(self): + """Create and return a trained model.""" + model = MLP( + dataset=self.simple_dataset, + feature_keys=["conditions", "labs"], + embedding_dim=32, + hidden_dim=32, + dropout=0.0, + ) + model.eval() + return model + + def _create_test_batch(self): + """Create a test batch from the dataset.""" + sample = self.simple_dataset[0] + batch = {} + for key, value in sample.items(): + if isinstance(value, torch.Tensor): + batch[key] = value.unsqueeze(0) + elif key not in ["patient_id", "visit_id"]: + if isinstance(value, (int, float)): + batch[key] = torch.tensor([value]) + return batch + + def test_epsilon_vs_alphabeta(self): + """Test that epsilon and alphabeta rules produce different attributions.""" + lrp_epsilon = LayerwiseRelevancePropagation( + self.trained_model, rule="epsilon", epsilon=0.01 + ) + lrp_alphabeta = LayerwiseRelevancePropagation( + self.trained_model, rule="alphabeta", alpha=2.0, beta=1.0 + ) + + attrs_epsilon = lrp_epsilon.attribute(**self.test_batch) + attrs_alphabeta = lrp_alphabeta.attribute(**self.test_batch) + + # Compare on a RELATIVE scale. LRP attributions on this fixture are + # O(1e-3), so an absolute tolerance of 0.1 is larger than the entire + # signal and would call any two tensors "close" -- including genuinely + # different ones. + different = False + for key in attrs_epsilon.keys(): + e, a = attrs_epsilon[key], attrs_alphabeta[key] + scale = max(e.abs().max().item(), a.abs().max().item(), 1e-12) + if ((e - a).abs().max().item() / scale) > 0.01: + different = True + break + + # Different rules should produce different results + # Note: With alpha=1.0, beta=0.0, results may be similar to epsilon rule + # Using alpha=2.0, beta=1.0 should produce more distinct results + print(f"\nRules produce different attributions: {different}") + self.assertTrue(different, "Epsilon and alphabeta rules should produce different attributions") + + +class TestEmbeddingModels(unittest.TestCase): + """Test LRP with embedding-based models (discrete medical codes).""" + + def test_embedding_model_forward_from_embedding(self): + """Test LRP with a model that has forward_from_embedding method.""" + + class SimpleEmbeddingModel: + """Simple embedding model matching PyHealth's EmbeddingModel interface.""" + def __init__(self, vocab_size, embedding_dim, feature_keys): + self.feature_keys = feature_keys + self.embeddings = torch.nn.ModuleDict({ + key: torch.nn.Embedding(vocab_size, embedding_dim) + for key in feature_keys + }) + + def __call__(self, inputs): + """Embed input tokens.""" + output = {} + for key in self.feature_keys: + if key in inputs: + output[key] = self.embeddings[key](inputs[key]) + return output + + class EmbeddingModel(torch.nn.Module): + def __init__(self, vocab_size=100, embedding_dim=32, hidden_dim=64, + output_dim=2, feature_keys=None): + super().__init__() + self.feature_keys = feature_keys if feature_keys else ["diagnosis"] + self.embedding_model = SimpleEmbeddingModel( + vocab_size, embedding_dim, self.feature_keys + ) + self.fc1 = torch.nn.Linear(embedding_dim, hidden_dim) + self.relu = torch.nn.ReLU() + self.fc2 = torch.nn.Linear(hidden_dim, output_dim) + + def forward(self, diagnosis, **kwargs): + embedded = self.embedding_model({"diagnosis": diagnosis}) + x = embedded["diagnosis"] # (batch_size, seq_length, embedding_dim) + x = x.mean(dim=1) # Average pool over sequence + x = self.fc1(x) + x = self.relu(x) + x = self.fc2(x) + return {"logit": x, "y_prob": torch.softmax(x, dim=-1)} + + def forward_from_embedding(self, **kwargs): + """Forward pass starting from embeddings (required for LRP).""" + embeddings = [] + for key in self.feature_keys: + emb = kwargs[key] + if isinstance(emb, tuple): + emb = emb[0] + if emb.dim() == 3: + emb = emb.mean(dim=1) # Average pool over sequence + embeddings.append(emb) + + x = torch.cat(embeddings, dim=-1) if len(embeddings) > 1 else embeddings[0] + x = self.fc1(x) + x = self.relu(x) + x = self.fc2(x) + return {"logit": x, "y_prob": torch.softmax(x, dim=-1)} + + def get_embedding_model(self): + return self.embedding_model + + # Create model + model = EmbeddingModel() + model.eval() + + # Initialize LRP + lrp = LayerwiseRelevancePropagation( + model=model, + rule="epsilon", + epsilon=1e-6, + use_embeddings=True + ) + + # Create discrete input: batch of sequences with token indices + batch_size = 4 + seq_length = 10 + vocab_size = 100 + x = torch.randint(0, vocab_size, (batch_size, seq_length)) + inputs = {"diagnosis": x} + + # Compute attributions + attributions = lrp.attribute(target_class_idx=0, **inputs) + + # Validations + self.assertIsInstance(attributions, dict) + self.assertIn("diagnosis", attributions) + self.assertEqual(attributions["diagnosis"].shape[0], batch_size) + self.assertFalse(torch.isnan(attributions["diagnosis"]).any()) + self.assertFalse(torch.isinf(attributions["diagnosis"]).any()) + + def test_embedding_model_different_targets(self): + """Test that attributions differ for different target classes.""" + + class EmbeddingLayer: + def __init__(self): + self.embeddings = torch.nn.ModuleDict({ + "diagnosis": torch.nn.Embedding(100, 32) + }) + + def __call__(self, inputs): + return {k: self.embeddings[k](v) for k, v in inputs.items()} + + class SimpleEmbeddingModel(torch.nn.Module): + def __init__(self): + super().__init__() + self.feature_keys = ["diagnosis"] + self.embedding_model = EmbeddingLayer() + self.fc1 = torch.nn.Linear(32, 64) + self.relu = torch.nn.ReLU() + self.fc2 = torch.nn.Linear(64, 2) + + def forward(self, diagnosis, **kwargs): + embedded = self.embedding_model({"diagnosis": diagnosis}) + x = embedded["diagnosis"].mean(dim=1) + x = self.fc1(x) + x = self.relu(x) + x = self.fc2(x) + return {"logit": x, "y_prob": torch.softmax(x, dim=-1)} + + def forward_from_embedding(self, **kwargs): + x = kwargs["diagnosis"] + if isinstance(x, tuple): + x = x[0] + if x.dim() == 3: + x = x.mean(dim=1) + x = self.fc1(x) + x = self.relu(x) + x = self.fc2(x) + return {"logit": x, "y_prob": torch.softmax(x, dim=-1)} + + def get_embedding_model(self): + return self.embedding_model + + model = SimpleEmbeddingModel() + model.eval() + + lrp = LayerwiseRelevancePropagation(model, rule="epsilon", use_embeddings=True) + + x = torch.randint(0, 100, (2, 10)) + inputs = {"diagnosis": x} + + attr_class0 = lrp.attribute(target_class_idx=0, **inputs) + attr_class1 = lrp.attribute(target_class_idx=1, **inputs) + + # Attributions for different classes should differ + diff = (attr_class0["diagnosis"] - attr_class1["diagnosis"]).abs().mean() + self.assertGreater(diff, 1e-6, "Attributions should differ between target classes") + + def test_embedding_model_variable_batch_sizes(self): + """Test LRP works with different batch sizes.""" + + class EmbeddingLayer: + def __init__(self): + self.embeddings = torch.nn.ModuleDict({ + "diagnosis": torch.nn.Embedding(100, 32) + }) + + def __call__(self, inputs): + return {k: self.embeddings[k](v) for k, v in inputs.items()} + + class SimpleEmbeddingModel(torch.nn.Module): + def __init__(self): + super().__init__() + self.feature_keys = ["diagnosis"] + self.embedding_model = EmbeddingLayer() + self.fc = torch.nn.Linear(32, 2) + + def forward(self, diagnosis, **kwargs): + embedded = self.embedding_model({"diagnosis": diagnosis}) + x = embedded["diagnosis"].mean(dim=1) + x = self.fc(x) + return {"logit": x} + + def forward_from_embedding(self, **kwargs): + x = kwargs["diagnosis"] + if isinstance(x, tuple): + x = x[0] + x = x.mean(dim=1) if x.dim() == 3 else x + return {"logit": self.fc(x)} + + def get_embedding_model(self): + return self.embedding_model + + model = SimpleEmbeddingModel() + model.eval() + lrp = LayerwiseRelevancePropagation(model, rule="epsilon", use_embeddings=True) + + # Test different batch sizes + for batch_size in [1, 2, 8]: + x = torch.randint(0, 100, (batch_size, 10)) + inputs = {"diagnosis": x} + attr = lrp.attribute(target_class_idx=0, **inputs) + + self.assertEqual(attr["diagnosis"].shape[0], batch_size) + + +class TestEndToEndIntegration(unittest.TestCase): + """Test complete end-to-end workflow with realistic scenarios.""" + + def test_branching_architecture_support(self): + """Test LRP with PyHealth's branching MLP architecture.""" + # Create dataset with multiple features + np.random.seed(42) + all_conditions = [f"cond-{j}" for j in range(15)] + + samples = [] + for i in range(30): + n_conditions = np.random.randint(3, 6) + selected_conditions = np.random.choice( + all_conditions, size=n_conditions, replace=False + ).tolist() + + samples.append({ + "patient_id": f"patient-{i}", + "visit_id": f"visit-0", + "conditions": selected_conditions, + "procedures": np.random.rand(4).tolist(), + "label": i % 2, + }) + + # Create dataset using SampleBuilder + temp_dir = tempfile.mkdtemp() + input_schema = {"conditions": "sequence", "procedures": "tensor"} + output_schema = {"label": "binary"} + builder = SampleBuilder(input_schema, output_schema) + builder.fit(samples) + builder.save(f"{temp_dir}/schema.pkl") + + # Optimize samples into dataset format + def sample_generator(): + for sample in samples: + yield {"sample": pickle.dumps(sample)} + + # Create optimized dataset + litdata.optimize( + fn=builder.transform, + inputs=list(sample_generator()), + output_dir=temp_dir, + num_workers=1, + chunk_bytes="64MB", + ) + + dataset = SampleDataset(path=temp_dir) + + # Create model with branching architecture + model = MLP( + dataset=dataset, + feature_keys=["conditions", "procedures"], + embedding_dim=64, + hidden_dim=128, + dropout=0.1, + n_layers=2, + ) + model.eval() + + # Initialize LRP + lrp_epsilon = LayerwiseRelevancePropagation( + model=model, rule="epsilon", epsilon=1e-6, use_embeddings=True + ) + lrp_alphabeta = LayerwiseRelevancePropagation( + model=model, rule="alphabeta", alpha=2.0, beta=1.0, use_embeddings=True + ) + + # Prepare batch + batch_size = 5 + batch_samples = [dataset[i] for i in range(batch_size)] + + batch_inputs = {} + for feature_key in model.feature_keys: + batch_list = [] + for sample in batch_samples: + feature_data = sample[feature_key] + if isinstance(feature_data, torch.Tensor): + batch_list.append(feature_data) + else: + batch_list.append(torch.tensor(feature_data)) + + # Pad sequences if needed + if batch_list and len(batch_list[0].shape) > 0: + max_len = max(t.shape[0] for t in batch_list) + padded_list = [] + for t in batch_list: + if t.shape[0] < max_len: + pad_size = max_len - t.shape[0] + if len(t.shape) == 1: + padded = torch.cat([t, torch.zeros(pad_size, dtype=t.dtype)]) + else: + padded = torch.cat([t, torch.zeros(pad_size, *t.shape[1:], dtype=t.dtype)]) + padded_list.append(padded) + else: + padded_list.append(t) + batch_inputs[feature_key] = torch.stack(padded_list) + else: + batch_inputs[feature_key] = torch.stack(batch_list) + + labels = torch.tensor( + [s['label'] for s in batch_samples], dtype=torch.float32 + ).unsqueeze(-1) + batch_data = {**batch_inputs, model.label_key: labels} + + # Get model predictions + with torch.no_grad(): + output = model(**batch_inputs, **{model.label_key: labels}) + predictions = output['y_prob'] + + # Compute attributions with both rules + attributions_eps = lrp_epsilon.attribute(target_class_idx=0, **batch_data) + attributions_ab = lrp_alphabeta.attribute(target_class_idx=0, **batch_data) + + # Validation checks + # 1. Attribution batch dimensions match + for key in batch_inputs: + self.assertEqual(attributions_eps[key].shape[0], batch_inputs[key].shape[0]) + self.assertEqual(attributions_ab[key].shape[0], batch_inputs[key].shape[0]) + + # 2. Attributions contain non-zero values + self.assertTrue(all( + torch.abs(attributions_eps[key]).sum() > 1e-6 + for key in attributions_eps + )) + self.assertTrue(all( + torch.abs(attributions_ab[key]).sum() > 1e-6 + for key in attributions_ab + )) + + # 3. Different rules produce different results + different_rules = False + for key in attributions_eps: + diff = torch.abs(attributions_eps[key] - attributions_ab[key]).mean() + if diff > 1e-6: + different_rules = True + break + self.assertTrue(different_rules, "Epsilon and alphabeta rules should produce different results") + + # 4. Attributions vary across samples + found_variance = False + for key in attributions_eps: + if attributions_eps[key].shape[0] > 1: + variance = torch.var(attributions_eps[key], dim=0).mean() + if variance > 1e-6: + found_variance = True + break + self.assertTrue(found_variance, "Attributions should vary across samples") + + # 5. No NaN or Inf values + for key in attributions_eps: + self.assertFalse(torch.isnan(attributions_eps[key]).any()) + self.assertFalse(torch.isinf(attributions_eps[key]).any()) + self.assertFalse(torch.isnan(attributions_ab[key]).any()) + self.assertFalse(torch.isinf(attributions_ab[key]).any()) + + # Cleanup + shutil.rmtree(temp_dir, ignore_errors=True) + + def test_multiple_feature_types(self): + """Test LRP handles different feature types (sequences and tensors).""" + samples = [ + { + "patient_id": f"patient-{i}", + "visit_id": f"visit-0", + "conditions": [f"cond-{j}" for j in range(3)], + "measurements": np.random.rand(5).tolist(), + "label": i % 2, + } + for i in range(20) + ] + + # Create dataset using SampleBuilder + temp_dir = tempfile.mkdtemp() + input_schema = {"conditions": "sequence", "measurements": "tensor"} + output_schema = {"label": "binary"} + builder = SampleBuilder(input_schema, output_schema) + builder.fit(samples) + builder.save(f"{temp_dir}/schema.pkl") + + # Optimize samples into dataset format + def sample_generator(): + for sample in samples: + yield {"sample": pickle.dumps(sample)} + + # Create optimized dataset + litdata.optimize( + fn=builder.transform, + inputs=list(sample_generator()), + output_dir=temp_dir, + num_workers=1, + chunk_bytes="64MB", + ) + + dataset = SampleDataset(path=temp_dir) + + model = MLP( + dataset=dataset, + feature_keys=["conditions", "measurements"], + embedding_dim=32, + hidden_dim=32, + ) + model.eval() + + lrp = LayerwiseRelevancePropagation(model, rule="epsilon") + + # Get a sample + sample = dataset[0] + batch = {} + for key, value in sample.items(): + if isinstance(value, torch.Tensor): + batch[key] = value.unsqueeze(0) + elif isinstance(value, (int, float)): + batch[key] = torch.tensor([value]) + + # Compute attributions + attributions = lrp.attribute(**batch) + + # Both feature types should have attributions + self.assertIn("conditions", attributions) + self.assertIn("measurements", attributions) + + # Check shapes + self.assertEqual(attributions["conditions"].shape[0], 1) + self.assertEqual(attributions["measurements"].shape[0], 1) + + # Cleanup + shutil.rmtree(temp_dir, ignore_errors=True) + + def test_real_pyhealth_mlp_model(self): + """Test LRP with actual PyHealth MLP model end-to-end.""" + # Create synthetic dataset + samples = [] + for i in range(20): + samples.append({ + "patient_id": f"patient-{i}", + "visit_id": f"visit-{i}", + "conditions": [f"cond-{j}" for j in range(5)], + "label": i % 2, + }) + + # Create temporary directory + temp_dir = tempfile.mkdtemp() + + # Build dataset using SampleBuilder + builder = SampleBuilder( + input_schema={"conditions": "sequence"}, + output_schema={"label": "binary"}, + ) + builder.fit(samples) + builder.save(f"{temp_dir}/schema.pkl") + + # Optimize samples + def sample_generator(): + for sample in samples: + yield {"sample": pickle.dumps(sample)} + + litdata.optimize( + fn=builder.transform, + inputs=list(sample_generator()), + output_dir=temp_dir, + num_workers=1, + chunk_bytes="64MB", + ) + + dataset = SampleDataset( + path=temp_dir, + dataset_name="test_mlp", + ) + + # Create MLP model + model = MLP( + dataset=dataset, + feature_keys=["conditions"], + embedding_dim=32, + hidden_dim=64, + dropout=0.0, + ) + model.eval() + + # Initialize LRP + lrp = LayerwiseRelevancePropagation( + model=model, + rule="epsilon", + epsilon=1e-6, + use_embeddings=True + ) + + # Get a sample and compute attributions + sample = dataset[0] + batch_input = {} + for key, value in sample.items(): + if isinstance(value, torch.Tensor): + batch_input[key] = value.unsqueeze(0) + elif key not in ["patient_id", "visit_id"]: + if isinstance(value, (int, float)): + batch_input[key] = torch.tensor([value]) + + # Compute attributions + attributions = lrp.attribute(**batch_input, target_class_idx=0) + + # Validations + self.assertIsInstance(attributions, dict) + self.assertIn("conditions", attributions) + self.assertEqual(attributions["conditions"].shape[0], 1) + self.assertFalse(torch.isnan(attributions["conditions"]).any()) + self.assertFalse(torch.isinf(attributions["conditions"]).any()) + + # Cleanup + shutil.rmtree(temp_dir, ignore_errors=True) + + def test_mlp_batch_processing(self): + """Test LRP with PyHealth MLP on multiple samples.""" + # Create dataset + samples = [] + for i in range(15): + samples.append({ + "patient_id": f"patient-{i}", + "visit_id": f"visit-{i}", + "conditions": [f"cond-{j}" for j in range(4)], + "label": i % 2, + }) + + # Create temporary directory + temp_dir = tempfile.mkdtemp() + + # Build dataset using SampleBuilder + builder = SampleBuilder( + input_schema={"conditions": "sequence"}, + output_schema={"label": "binary"}, + ) + builder.fit(samples) + builder.save(f"{temp_dir}/schema.pkl") + + # Optimize samples + def sample_generator(): + for sample in samples: + yield {"sample": pickle.dumps(sample)} + + litdata.optimize( + fn=builder.transform, + inputs=list(sample_generator()), + output_dir=temp_dir, + num_workers=1, + chunk_bytes="64MB", + ) + + dataset = SampleDataset( + path=temp_dir, + dataset_name="test_batch", + ) + + model = MLP( + dataset=dataset, + feature_keys=["conditions"], + embedding_dim=32, + hidden_dim=32, + ) + model.eval() + + lrp = LayerwiseRelevancePropagation( + model=model, + rule="alphabeta", + alpha=2.0, + beta=1.0, + use_embeddings=True + ) + + # Process multiple samples + batch_size = 3 + batch_data = [] + for i in range(batch_size): + sample = dataset[i] + batch_data.append(sample["conditions"]) + + # Stack into batch + batch_input = {"conditions": torch.stack(batch_data)} + + # Add label for PyHealth MLP + labels = torch.tensor([dataset[i]["label"] for i in range(batch_size)], dtype=torch.float32).unsqueeze(-1) + batch_input["label"] = labels + + # Compute attributions + attributions = lrp.attribute(target_class_idx=0, **batch_input) + + # Validations + self.assertEqual(attributions["conditions"].shape[0], batch_size) + + # Check no NaN or Inf values + self.assertFalse(torch.isnan(attributions["conditions"]).any()) + self.assertFalse(torch.isinf(attributions["conditions"]).any()) + + # Cleanup + shutil.rmtree(temp_dir, ignore_errors=True) + + +class TestStageNetLRP(unittest.TestCase): + """End-to-end LRP tests using StageNet on synthetic temporal EHR data. + + StageNet implements Interpretable and returns a 'logit' key, so + conservation is tested with a tighter tolerance than branching MLP. + """ + + @classmethod + def _make_dataset(cls, num_samples: int = 40, seed: int = 7) -> "SampleDataset": + random.seed(seed) + np.random.seed(seed) + samples = [] + for i in range(num_samples): + num_visits = random.randint(3, 8) + codes = [ + [f"D{j}" for j in random.choices(range(30), k=random.randint(2, 5))] + for _ in range(num_visits) + ] + times = [v * 24.0 for v in range(num_visits)] + labs = [ + [round(random.gauss(5.0, 1.0), 2) for _ in range(5)] + for _ in range(num_visits) + ] + samples.append({ + "patient_id": f"P{i}", + "visit_id": f"V{i}", + "diagnoses": (times, codes), + "labs": (times, labs), + "label": i % 2, + }) + return create_sample_dataset( + samples=samples, + input_schema={"diagnoses": "stagenet", "labs": "stagenet_tensor"}, + output_schema={"label": "binary"}, + in_memory=True, + ) + + def setUp(self): + self.dataset = self._make_dataset() + self.model = StageNet( + dataset=self.dataset, + embedding_dim=32, + chunk_size=32, + levels=2, + ) + self.model.eval() + + def _make_batch(self, idx: int = 0): + sample = self.dataset[idx] + return { + k: v.unsqueeze(0) if isinstance(v, torch.Tensor) + else tuple(t.unsqueeze(0) if isinstance(t, torch.Tensor) else t for t in v) + if isinstance(v, tuple) else v + for k, v in sample.items() + } + + def test_epsilon_attribution_shapes(self): + """Attributions have the same batch dimension as the input.""" + batch = self._make_batch() + lrp = LayerwiseRelevancePropagation( + self.model, rule="epsilon", epsilon=0.01, use_embeddings=True + ) + attrs = lrp.attribute(**batch) + self.assertIn("diagnoses", attrs) + self.assertIn("labs", attrs) + for key in ["diagnoses", "labs"]: + self.assertEqual(attrs[key].shape[0], 1) + + def test_alphabeta_attribution_shapes(self): + """AlphaBeta rule also produces correct batch dimension.""" + batch = self._make_batch() + lrp = LayerwiseRelevancePropagation( + self.model, rule="alphabeta", alpha=1.0, beta=0.0, use_embeddings=True + ) + attrs = lrp.attribute(**batch) + for key in attrs: + self.assertEqual(attrs[key].shape[0], 1) + + def test_no_nan_or_inf(self): + """Neither epsilon nor alphabeta attributions contain NaN/Inf.""" + batch = self._make_batch() + for rule, kwargs in [ + ("epsilon", {"epsilon": 0.01}), + ("alphabeta", {"alpha": 1.0, "beta": 0.0}), + ]: + lrp = LayerwiseRelevancePropagation( + self.model, rule=rule, use_embeddings=True, **kwargs + ) + attrs = lrp.attribute(**batch) + for key, attr in attrs.items(): + self.assertFalse(torch.isnan(attr).any(), + f"{rule}: NaN in {key}") + self.assertFalse(torch.isinf(attr).any(), + f"{rule}: Inf in {key}") + + def test_conservation_epsilon(self): + """Epsilon-rule relevances sum close to the model logit (StageNet returns logit).""" + batch = self._make_batch() + lrp = LayerwiseRelevancePropagation( + self.model, rule="epsilon", epsilon=0.01, use_embeddings=True + ) + with torch.no_grad(): + out = self.model(**batch) + logit = out["logit"][0, 0].item() + + attrs = lrp.attribute(**batch, target_class_idx=0) + total = sum(a.sum().item() for a in attrs.values()) + + rel = abs(total - logit) / max(abs(logit), 1e-6) + # StageNet uses a custom step-wise LSTM implementation whose repeated + # Linear calls overwrite hook activations, so only the last timestep is + # seen during backward propagation. Combined with the bias-induced + # epsilon-rule error (see note in TestRelevanceConservation), a 1.5× + # relative bound is a structural sanity check rather than a tight + # conservation guarantee. + self.assertLess(rel, 1.5, + f"Conservation violated: logit={logit:.4f}, sum={total:.4f}, rel={rel:.2%}") + + def test_epsilon_vs_alphabeta_differ(self): + """Epsilon and alphabeta rules produce different attributions.""" + batch = self._make_batch() + lrp_eps = LayerwiseRelevancePropagation( + self.model, rule="epsilon", epsilon=0.01, use_embeddings=True + ) + lrp_ab = LayerwiseRelevancePropagation( + self.model, rule="alphabeta", alpha=2.0, beta=1.0, use_embeddings=True + ) + attrs_eps = lrp_eps.attribute(**batch) + attrs_ab = lrp_ab.attribute(**batch) + + # Relative comparison: absolute tolerances larger than the attribution + # scale make this assertion vacuous (see TestDifferentRules). + def _rel_diff(e, a): + scale = max(e.abs().max().item(), a.abs().max().item(), 1e-12) + return (e - a).abs().max().item() / scale + + different = any(_rel_diff(attrs_eps[k], attrs_ab[k]) > 0.01 for k in attrs_eps) + self.assertTrue(different, + "Epsilon and alphabeta rules should produce different attributions") + + def test_batch_size_invariance(self): + """Attributions work for batch_size > 1 and first sample matches single-sample result.""" + # Single sample + batch1 = self._make_batch(0) + lrp = LayerwiseRelevancePropagation( + self.model, rule="epsilon", epsilon=0.01, use_embeddings=True + ) + attrs1 = lrp.attribute(**batch1, target_class_idx=0) + + # Batch of 3 (same sample repeated) + batch3 = {} + for k, v in batch1.items(): + if isinstance(v, torch.Tensor): + batch3[k] = v.repeat(3, *([1] * (v.dim() - 1))) + elif isinstance(v, tuple): + batch3[k] = tuple( + t.repeat(3, *([1] * (t.dim() - 1))) if isinstance(t, torch.Tensor) else t + for t in v + ) + else: + batch3[k] = v + attrs3 = lrp.attribute(**batch3, target_class_idx=0) + + for key in attrs1: + self.assertEqual(attrs3[key].shape[0], 3) + # First sample in batched result should match single result + self.assertTrue( + torch.allclose(attrs1[key][0], attrs3[key][0], atol=1e-5), + f"Batch[0] != single for feature '{key}'" + ) + + def test_attributions_nonzero(self): + """Attributions contain non-trivially-zero values.""" + batch = self._make_batch() + lrp = LayerwiseRelevancePropagation( + self.model, rule="epsilon", epsilon=0.01, use_embeddings=True + ) + attrs = lrp.attribute(**batch) + for key, attr in attrs.items(): + self.assertGreater(attr.abs().sum().item(), 1e-8, + f"All-zero attributions for '{key}'") + + def test_target_class_changes_attributions(self): + """Attributions for class 0 and class 1 differ.""" + batch = self._make_batch() + lrp = LayerwiseRelevancePropagation( + self.model, rule="epsilon", epsilon=0.01, use_embeddings=True + ) + attrs0 = lrp.attribute(**batch, target_class_idx=0) + attrs1 = lrp.attribute(**batch, target_class_idx=1) + self.assertTrue( + any(not torch.allclose(attrs0[k], attrs1[k]) for k in attrs0), + "Attributions for class 0 and class 1 are identical", + ) + + +class TestAlphaBetaSignSeparation(unittest.TestCase): + """alpha-beta must split on contributions x_i*w_ij, not on weights alone. + + Regression test: the handlers used to pair W+ with the raw signed input, so + for x_i < 0 a positive weight still routed relevance down the "positive" + path. With beta=0 (negative path disabled) relevance could still come back + negative, and totals diverged wildly from the propagated relevance. + """ + + def test_linear_alphabeta_is_sign_preserving_with_beta_zero(self): + from torch import nn + + from pyhealth.interpret.methods.lrp_base import LinearLRPHandler + + layer = nn.Linear(4, 1, bias=False) + with torch.no_grad(): + layer.weight.copy_(torch.tensor([[1.0, 1.0, 1.0, 1.0]])) + handler = LinearLRPHandler() + + x = torch.tensor([[1.0, -2.0, 3.0, -4.0]]) # signed, as embeddings are + handler.forward_hook(layer, (x,), layer(x)) + relevance = handler.backward_relevance( + layer, torch.tensor([[1.0]]), rule="alphabeta", alpha=1.0, beta=0.0 + ) + + self.assertFalse( + bool((relevance < 0).any()), + f"beta=0 disables the negative path, so relevance must stay " + f"non-negative for positive output relevance; got {relevance}", + ) + # alpha - beta == 1 => relevance is conserved + self.assertAlmostEqual(relevance.sum().item(), 1.0, places=4) + + def test_conv2d_alphabeta_is_sign_preserving_with_beta_zero(self): + from torch import nn + + from pyhealth.interpret.methods.lrp_base import Conv2dLRPHandler + + layer = nn.Conv2d(1, 2, kernel_size=3, padding=1, bias=False) + with torch.no_grad(): + layer.weight.abs_() + handler = Conv2dLRPHandler() + + x = torch.randn(1, 1, 8, 8) # signed input + z = layer(x) + handler.forward_hook(layer, (x,), z) + relevance = handler.backward_relevance( + layer, torch.ones_like(z), rule="alphabeta", alpha=1.0, beta=0.0 + ) + + self.assertFalse( + bool((relevance < 0).any()), + "beta=0 must not produce negative relevance on the conv path", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/core/test_lrp_base.py b/tests/core/test_lrp_base.py new file mode 100644 index 0000000000..828f5ff607 --- /dev/null +++ b/tests/core/test_lrp_base.py @@ -0,0 +1,297 @@ +"""Unit tests for the LRP utility functions and per-layer handlers in lrp_base.""" + +import logging +import unittest + +import torch +from torch import nn + +from pyhealth.interpret.methods.lrp_base import ( + AdaptiveAvgPool2dLRPHandler, + AvgPool2dLRPHandler, + BatchNorm2dLRPHandler, + Conv2dLRPHandler, + DropoutLRPHandler, + EmbeddingLRPHandler, + FlattenLRPHandler, + LinearLRPHandler, + LRPHandlerRegistry, + MaxPool2dLRPHandler, + ReLULRPHandler, + RNNLRPHandler, + check_tensor_validity, + create_default_registry, + crop_spatial, + match_relevance_dim, + pad_to_match, + stabilize_denominator, +) + + +def _run_forward(handler, layer, x): + """Run *layer* on *x* and populate *handler*'s activation cache.""" + out = layer(x) + handler.forward_hook(layer, (x,), out) + return out + + +class TestUtilityFunctions(unittest.TestCase): + + def test_stabilize_denominator_rules(self): + z = torch.tensor([[2.0, -2.0, 0.0]]) + self.assertTrue(torch.allclose( + stabilize_denominator(z, 0.1, rule="epsilon"), + torch.tensor([[2.1, -2.1, 0.1]]), + )) + self.assertTrue(torch.allclose( + stabilize_denominator(z, 0.1, rule="z+"), + torch.tensor([[2.0, 0.1, 0.1]]), + )) + # Unknown rule falls back to adding epsilon + self.assertTrue(torch.allclose( + stabilize_denominator(z, 0.1, rule="other"), + torch.tensor([[2.1, -1.9, 0.1]]), + )) + + def test_check_tensor_validity(self): + self.assertTrue(check_tensor_validity(torch.ones(2, 2))) + with self.assertLogs("pyhealth.interpret.methods.lrp_base", level=logging.ERROR): + self.assertFalse(check_tensor_validity(torch.tensor([float("nan")]), "r")) + with self.assertLogs("pyhealth.interpret.methods.lrp_base", level=logging.ERROR): + self.assertFalse(check_tensor_validity(torch.tensor([float("inf")]), "r")) + + def test_pad_to_match(self): + x = torch.ones(2, 3) + same, orig = pad_to_match(x, 3) + self.assertIs(same, x) + self.assertEqual(orig, 3) + padded, orig = pad_to_match(x, 5) + self.assertEqual(padded.shape, (2, 5)) + self.assertEqual(padded[:, 3:].abs().sum().item(), 0.0) + truncated, orig = pad_to_match(torch.ones(2, 6), 4) + self.assertEqual((truncated.shape, orig), ((2, 4), 6)) + + def test_match_relevance_dim(self): + r = torch.ones(1, 3) + self.assertIs(match_relevance_dim(r, 3), r) + self.assertEqual(match_relevance_dim(r, 5).shape, (1, 5)) + self.assertEqual(match_relevance_dim(r, 2).shape, (1, 2)) + + def test_crop_spatial(self): + t = torch.ones(1, 1, 4, 4) + self.assertIs(crop_spatial(t, (1, 1, 4, 4)), t) + self.assertEqual(crop_spatial(t, (1, 1, 2, 3)).shape, (1, 1, 2, 3)) + padded = crop_spatial(t, (1, 1, 6, 5)) + self.assertEqual(padded.shape, (1, 1, 6, 5)) + # Padding is zero-filled and the sum is preserved + self.assertEqual(padded.sum().item(), 16.0) + + +class TestRegistry(unittest.TestCase): + + def test_register_rejects_non_handlers(self): + with self.assertRaises(TypeError): + LRPHandlerRegistry().register(object()) + + def test_lookup_cache_and_clear(self): + registry = LRPHandlerRegistry() + handler = LinearLRPHandler() + registry.register(handler) + self.assertIs(registry.get_handler(nn.Linear(2, 2)), handler) + # Second lookup is served from the per-type cache + self.assertIs(registry.get_handler(nn.Linear(3, 3)), handler) + self.assertIsNone(registry.get_handler(nn.Tanh())) + registry.clear() + self.assertIsNone(registry.get_handler(nn.Linear(2, 2))) + + def test_default_registry_covers_all_layer_types(self): + registry = create_default_registry() + layers = [ + nn.Linear(2, 2), nn.ReLU(), nn.Embedding(5, 2), nn.Conv2d(1, 1, 3), + nn.MaxPool2d(2), nn.AvgPool2d(2), nn.AdaptiveAvgPool2d(1), + nn.Flatten(), nn.BatchNorm2d(1), nn.Dropout(), nn.LSTM(2, 2), nn.GRU(2, 2), + ] + for layer in layers: + self.assertIsNotNone(registry.get_handler(layer), type(layer).__name__) + + def test_backward_without_forward_raises(self): + with self.assertRaises(RuntimeError): + LinearLRPHandler().backward_relevance(nn.Linear(2, 2), torch.ones(1, 2)) + + def test_clear_cache(self): + handler, layer = LinearLRPHandler(), nn.Linear(2, 2) + _run_forward(handler, layer, torch.randn(1, 2)) + handler.clear_cache() + self.assertEqual(handler.activations_cache, {}) + + +class TestLinearHandler(unittest.TestCase): + + def setUp(self): + torch.manual_seed(0) + self.handler = LinearLRPHandler() + + def test_epsilon_conserves_relevance_without_bias(self): + layer = nn.Linear(6, 3, bias=False) + x = torch.randn(2, 6) + out = _run_forward(self.handler, layer, x) + r_in = self.handler.backward_relevance(layer, out, rule="epsilon", epsilon=1e-6) + self.assertTrue(torch.allclose(r_in.sum(dim=1), out.sum(dim=1), atol=1e-3)) + + def test_flattens_higher_dim_input(self): + layer = nn.Linear(12, 2) + x = torch.randn(2, 3, 4) + handler = self.handler + handler.forward_hook(layer, (x,), layer(x.view(2, -1))) + for rule in ("epsilon", "alphabeta"): + r = handler.backward_relevance(layer, torch.ones(2, 2), rule=rule) + self.assertEqual(r.shape, (2, 12)) + + def test_input_width_mismatch_is_padded_and_trimmed(self): + # The cached input is narrower than the weight matrix (e.g. a model + # that concatenates extra columns); relevance comes back at input width. + layer = nn.Linear(5, 2) + self.handler.forward_hook(layer, (torch.randn(1, 3),), torch.randn(1, 2)) + for rule in ("epsilon", "alphabeta"): + r = self.handler.backward_relevance(layer, torch.ones(1, 2), rule=rule) + self.assertEqual(r.shape, (1, 3)) + + def test_alphabeta_without_bias(self): + layer = nn.Linear(4, 2, bias=False) + out = _run_forward(self.handler, layer, torch.randn(1, 4)) + r = self.handler.backward_relevance(layer, out, rule="alphabeta", alpha=2.0, beta=1.0) + self.assertTrue(torch.isfinite(r).all()) + + def test_unsupported_rule_raises(self): + layer = nn.Linear(4, 2) + _run_forward(self.handler, layer, torch.randn(1, 4)) + with self.assertRaises(ValueError): + self.handler.backward_relevance(layer, torch.ones(1, 2), rule="gamma") + + +class TestConv2dHandler(unittest.TestCase): + + def setUp(self): + torch.manual_seed(0) + self.handler = Conv2dLRPHandler() + + def test_rules_preserve_input_shape_with_stride(self): + layer = nn.Conv2d(2, 3, kernel_size=3, stride=2, padding=1) + x = torch.randn(1, 2, 7, 7) + out = _run_forward(self.handler, layer, x) + for rule in ("epsilon", "alphabeta"): + r = self.handler.backward_relevance(layer, out, rule=rule) + self.assertEqual(r.shape, x.shape) + self.assertTrue(torch.isfinite(r).all()) + + def test_alphabeta_without_bias(self): + layer = nn.Conv2d(1, 2, kernel_size=3, padding=1, bias=False) + x = torch.randn(1, 1, 5, 5) + out = _run_forward(self.handler, layer, x) + r = self.handler.backward_relevance(layer, out, rule="alphabeta", alpha=2.0, beta=1.0) + self.assertEqual(r.shape, x.shape) + + def test_unsupported_rule_raises(self): + layer = nn.Conv2d(1, 1, 3) + _run_forward(self.handler, layer, torch.randn(1, 1, 5, 5)) + with self.assertRaises(ValueError): + self.handler.backward_relevance(layer, torch.ones(1, 1, 3, 3), rule="gamma") + + +class TestPoolingHandlers(unittest.TestCase): + + def test_maxpool_routes_to_winners(self): + handler, layer = MaxPool2dLRPHandler(), nn.MaxPool2d(2, 2) + x = torch.randn(1, 2, 4, 4) + out = _run_forward(handler, layer, x) + r = handler.backward_relevance(layer, torch.ones_like(out)) + self.assertEqual(r.shape, x.shape) + # Exactly one winner per 2x2 window + self.assertEqual(r.sum().item(), out.numel()) + self.assertEqual(int((r != 0).sum()), out.numel()) + + def test_maxpool_falls_back_to_interpolation(self): + handler, layer = MaxPool2dLRPHandler(), nn.MaxPool2d(2, 2) + x = torch.randn(1, 1, 4, 4) + _run_forward(handler, layer, x) + # Channel count inconsistent with the cached indices -> unpool raises + # RuntimeError and relevance is resized to the input's spatial dims. + r = handler.backward_relevance(layer, torch.ones(1, 2, 2, 2)) + self.assertEqual(r.shape[2:], x.shape[2:]) + + def test_avgpool_distributes_uniformly(self): + for layer in (nn.AvgPool2d(2, 2), nn.AvgPool2d((2, 2), (2, 2), (0, 0))): + handler = AvgPool2dLRPHandler() + x = torch.randn(1, 2, 4, 4) + out = _run_forward(handler, layer, x) + r = handler.backward_relevance(layer, torch.ones_like(out)) + self.assertEqual(r.shape, x.shape) + self.assertAlmostEqual(r.sum().item(), out.numel(), places=5) + + def test_adaptive_avgpool_global(self): + handler, layer = AdaptiveAvgPool2dLRPHandler(), nn.AdaptiveAvgPool2d(1) + x = torch.randn(2, 3, 4, 4) + _run_forward(handler, layer, x) + # Flattened relevance (as after nn.Flatten) is reshaped back first + r = handler.backward_relevance(layer, torch.ones(2, 3)) + self.assertEqual(r.shape, x.shape) + self.assertAlmostEqual(r.sum().item(), 6.0, places=5) + + def test_adaptive_avgpool_regions(self): + handler, layer = AdaptiveAvgPool2dLRPHandler(), nn.AdaptiveAvgPool2d((2, 2)) + x = torch.randn(1, 1, 4, 4) + out = _run_forward(handler, layer, x) + r = handler.backward_relevance(layer, torch.ones_like(out)) + self.assertEqual(r.shape, x.shape) + self.assertTrue(torch.allclose(r, torch.full_like(x, 0.25))) + + +class TestPassThroughHandlers(unittest.TestCase): + + def test_identity_handlers(self): + relevance = torch.randn(1, 3, 4, 4) + for handler, layer in ( + (ReLULRPHandler(), nn.ReLU()), + (BatchNorm2dLRPHandler(), nn.BatchNorm2d(3)), + (DropoutLRPHandler(), nn.Dropout()), + ): + self.assertTrue(handler.supports(layer)) + self.assertIs(handler.backward_relevance(layer, relevance), relevance) + + def test_embedding_handler(self): + handler, layer = EmbeddingLRPHandler(), nn.Embedding(10, 4) + idx = torch.tensor([[1, 2, 3]]) + _run_forward(handler, layer, idx) + self.assertTrue(torch.equal(handler.activations_cache[id(layer)]["indices"], idx)) + self.assertEqual(handler.backward_relevance(layer, torch.ones(1, 3, 4)).shape, (1, 3)) + r2 = torch.ones(1, 3) + self.assertIs(handler.backward_relevance(layer, r2), r2) + + def test_flatten_handler(self): + handler, layer = FlattenLRPHandler(), nn.Flatten() + x = torch.randn(2, 3, 2, 2) + out = _run_forward(handler, layer, x) + self.assertEqual(handler.backward_relevance(layer, out).shape, x.shape) + + def test_rnn_handler(self): + handler = RNNLRPHandler() + for layer in (nn.LSTM(4, 3, batch_first=True), nn.GRU(4, 3, batch_first=True)): + x = torch.randn(2, 5, 4) + out, _ = layer(x) + handler.forward_hook(layer, (x,), out) + r = handler.backward_relevance(layer, torch.ones(2, 3)) + self.assertEqual(r.shape, (2, 5, 3)) + # Spreading over timesteps conserves the total + self.assertAlmostEqual(r.sum().item(), 6.0, places=5) + + def test_rnn_handler_non_sequence_input(self): + handler, layer = RNNLRPHandler(), nn.GRU(4, 3) + x = torch.randn(5, 4) # unbatched input + out, _ = layer(x) + handler.forward_hook(layer, (x,), out) + r = torch.ones(5, 3) + self.assertIs(handler.backward_relevance(layer, r), r) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/core/test_lrp_cnn.py b/tests/core/test_lrp_cnn.py new file mode 100644 index 0000000000..17e48baf8b --- /dev/null +++ b/tests/core/test_lrp_cnn.py @@ -0,0 +1,264 @@ +"""Tests for LRP on continuous (image) inputs with use_embeddings=False. + +Covers the CNN layer path, residual blocks (torchvision BasicBlock with and +without a projection shortcut), logit extraction fallbacks, and the shape / +feature-splitting utilities on LayerwiseRelevancePropagation. +""" + +import unittest + +import matplotlib +matplotlib.use("Agg") # Use non-interactive backend for testing +import matplotlib.pyplot as plt +import torch +from torch import nn +from torchvision.models.resnet import BasicBlock + +from pyhealth.interpret.methods import LayerwiseRelevancePropagation + + +class TinyCNN(nn.Module): + """Small CNN touching every supported image layer type.""" + + def __init__(self, num_classes=3, return_logit=True): + super().__init__() + self.return_logit = return_logit + self.features = nn.Sequential( + nn.Conv2d(1, 4, kernel_size=3, padding=1), + nn.BatchNorm2d(4), + nn.ReLU(), + nn.MaxPool2d(2), + nn.Conv2d(4, 4, kernel_size=3, padding=1), + nn.ReLU(), + nn.AvgPool2d(2), + nn.AdaptiveAvgPool2d((2, 2)), + nn.Flatten(), + nn.Dropout(0.1), + ) + self.head = nn.Linear(16, num_classes) + + def forward(self, image, **kwargs): + logit = self.head(self.features(image)) + y_prob = torch.softmax(logit, dim=-1) + if self.return_logit: + return {"logit": logit, "y_prob": y_prob} + return {"y_prob": y_prob} + + +class TinyResNet(nn.Module): + """Two residual blocks: identity shortcut, then projection shortcut.""" + + def __init__(self, num_classes=2): + super().__init__() + self.stem = nn.Conv2d(1, 4, kernel_size=3, padding=1) + self.layer1 = BasicBlock(4, 4) + self.layer2 = BasicBlock( + 4, 8, stride=2, + downsample=nn.Sequential(nn.Conv2d(4, 8, 1, stride=2), nn.BatchNorm2d(8)), + ) + self.pool = nn.AdaptiveAvgPool2d(1) + self.flatten = nn.Flatten() + self.fc = nn.Linear(8, num_classes) + + def forward(self, image, **kwargs): + x = self.layer2(self.layer1(self.stem(image))) + return {"logit": self.fc(self.flatten(self.pool(x)))} + + +class NoLinearCNN(nn.Module): + """Model with no Linear layer that only reports probabilities.""" + + def __init__(self): + super().__init__() + self.conv = nn.Conv2d(1, 2, kernel_size=3, padding=1) + self.pool = nn.AdaptiveAvgPool2d(1) + self.flatten = nn.Flatten() + + def forward(self, image, **kwargs): + return {"y_prob": torch.softmax(self.flatten(self.pool(self.conv(image))), dim=-1)} + + +class BinaryCNN(nn.Module): + """Single-logit binary classifier.""" + + def __init__(self): + super().__init__() + self.flatten = nn.Flatten() + self.fc = nn.Linear(16, 1) + + def forward(self, image, **kwargs): + return {"logit": self.fc(self.flatten(image))} + + +class BadOutputModel(nn.Module): + def __init__(self): + super().__init__() + self.conv = nn.Conv2d(1, 1, 1) + + def forward(self, image, **kwargs): + return {"embedding": self.conv(image)} + + +def _lrp(model, **kwargs): + model.eval() + return LayerwiseRelevancePropagation(model, use_embeddings=False, **kwargs) + + +class TestLRPInputValidation(unittest.TestCase): + + def test_use_embeddings_requires_embedding_interface(self): + with self.assertRaises(ValueError): + LayerwiseRelevancePropagation(TinyCNN(), use_embeddings=True) + + +class TestLRPCNN(unittest.TestCase): + + def setUp(self): + torch.manual_seed(0) + self.model = TinyCNN() + self.image = torch.randn(2, 1, 8, 8) + + def test_attribution_shape_both_rules(self): + for rule in ("epsilon", "alphabeta"): + attr = _lrp(self.model, rule=rule).attribute(image=self.image) + self.assertEqual(set(attr), {"image"}) + self.assertEqual(attr["image"].shape, self.image.shape) + self.assertTrue(torch.isfinite(attr["image"]).all()) + + def test_target_class_changes_attribution(self): + lrp = _lrp(self.model) + a0 = lrp.attribute(target_class_idx=0, image=self.image)["image"] + a1 = lrp.attribute(target_class_idx=1, image=self.image)["image"] + self.assertFalse(torch.allclose(a0, a1)) + + def test_hooks_are_removed_after_attribute(self): + _lrp(self.model).attribute(image=self.image) + for module in self.model.modules(): + self.assertEqual(len(module._forward_hooks), 0) + + def test_extra_feature_keys_and_list_labels(self): + # Declared feature keys missing from the batch are skipped, and + # non-tensor label values are converted before being forwarded. + self.model.feature_keys = ["image", "absent"] + self.model.label_keys = ["label"] + attr = _lrp(self.model).attribute(image=self.image, label=[0, 1]) + self.assertEqual(set(attr), {"image"}) + + def test_logits_from_last_linear_when_missing_logit_key(self): + model = TinyCNN(return_logit=False) + attr = _lrp(model).attribute(image=self.image)["image"] + self.assertEqual(attr.shape, self.image.shape) + self.assertGreater(attr.abs().sum().item(), 0.0) + + def test_y_prob_fallback_without_linear(self): + attr = _lrp(NoLinearCNN()).attribute(image=self.image)["image"] + self.assertEqual(attr.shape, self.image.shape) + + def test_missing_logit_and_y_prob_raises(self): + with self.assertRaises(KeyError): + _lrp(BadOutputModel()).attribute(image=self.image) + + def test_visualize(self): + lrp = _lrp(self.model) + attr = lrp.attribute(image=self.image)["image"] + lrp.visualize(plt, self.image[0], attr[0], show=False) + self.assertIn("epsilon", plt.gca().get_title()) + plt.close("all") + + +class TestLRPBinaryTarget(unittest.TestCase): + + def test_negative_class_negates_epsilon_relevance(self): + torch.manual_seed(0) + lrp = _lrp(BinaryCNN()) + image = torch.randn(2, 1, 4, 4) + pos = lrp.attribute(image=image)["image"] + neg = lrp.attribute(target_class_idx=0, image=image)["image"] + self.assertTrue(torch.allclose(neg, -pos, atol=1e-6)) + + +class TestLRPResidualBlocks(unittest.TestCase): + + def setUp(self): + torch.manual_seed(0) + self.model = TinyResNet() + self.image = torch.randn(2, 1, 8, 8) + + def test_both_rules_produce_finite_input_relevance(self): + for rule in ("epsilon", "alphabeta"): + attr = _lrp(self.model, rule=rule, beta=0.5, alpha=1.5).attribute(image=self.image) + self.assertEqual(attr["image"].shape, self.image.shape) + self.assertTrue(torch.isfinite(attr["image"]).all(), rule) + self.assertGreater(attr["image"].abs().sum().item(), 0.0, rule) + + def test_residual_blocks_are_tracked(self): + from pyhealth.interpret.methods.lrp import _LRPHookContext + + with _LRPHookContext(self.model) as ctx: + with torch.no_grad(): + self.model(image=self.image) + self.assertEqual(set(ctx.residual_blocks), {"layer1", "layer2"}) + self.assertFalse(ctx.residual_blocks["layer1"]["has_downsample"]) + self.assertTrue(ctx.residual_blocks["layer2"]["has_downsample"]) + lrp = _lrp(self.model) + self.assertEqual(lrp._get_block_for_layer("layer2.conv1", ctx), "layer2") + self.assertIsNone(lrp._get_block_for_layer("fc", ctx)) + self.assertEqual(ctx.residual_blocks, {}) + + +class TestLRPShapeUtilities(unittest.TestCase): + + def setUp(self): + self.lrp = _lrp(TinyCNN()) + + def test_match_shapes(self): + m = self.lrp._match_shapes + r = torch.ones(2, 3, 4, 4) + self.assertIs(m(r, r.shape), r) + # 2D -> 4D: exact reshape, or spread the total uniformly + self.assertEqual(m(torch.ones(2, 48), (2, 3, 4, 4)).shape, (2, 3, 4, 4)) + spread = m(torch.ones(2, 5), (2, 3, 4, 4)) + self.assertEqual(spread.shape, (2, 3, 4, 4)) + self.assertAlmostEqual(spread[0].sum().item(), 5.0, places=5) + # 4D -> 4D: channel and spatial mismatch + self.assertEqual(m(torch.ones(2, 1, 2, 2), (2, 3, 4, 4)).shape, (2, 3, 4, 4)) + # 3D -> 4D + self.assertEqual(m(torch.ones(2, 4, 4), (2, 3, 4, 4)).shape, (2, 3, 4, 4)) + self.assertEqual(m(torch.ones(2, 2, 2), (2, 3, 4, 4)).shape, (2, 3, 4, 4)) + # Unhandled combination is returned unchanged + odd = torch.ones(2, 3) + self.assertIs(m(odd, (2, 3, 4)), odd) + + def test_unhandled_layer_passes_relevance_through(self): + r = torch.ones(1, 3) + self.assertIs(self.lrp._propagate_through_layer(nn.Tanh(), {}, r), r) + + def test_split_pre_split_relevance(self): + emb = {"a": torch.zeros(2, 3, 4)} + # Extra trailing columns (e.g. StageNet's time interval) are dropped and + # pooled relevance is spread evenly across timesteps. + out = self.lrp._split_relevance_to_features( + {"a": torch.ones(2, 5), "not_an_input": torch.ones(2, 1)}, emb + ) + self.assertEqual(set(out), {"a"}) + self.assertEqual(out["a"].shape, (2, 3, 4)) + self.assertTrue(torch.allclose(out["a"].sum(dim=(1, 2)), torch.full((2,), 4.0))) + + def test_split_concatenated_relevance(self): + self.lrp.model.feature_keys = ["a", "b", "missing"] + emb = {"a": torch.zeros(2, 3, 4), "b": torch.zeros(2, 2)} + relevance = torch.arange(12.0).view(2, 6) + out = self.lrp._split_relevance_to_features(relevance, emb) + self.assertEqual(out["a"].shape, (2, 3, 4)) + self.assertTrue(torch.equal(out["a"][:, 0], relevance[:, :4])) + self.assertTrue(torch.equal(out["b"], relevance[:, 4:])) + + def test_split_falls_back_to_even_distribution(self): + emb = {"a": torch.zeros(2, 4), "b": torch.zeros(2, 1, 2, 2)} + out = self.lrp._split_relevance_to_features(torch.ones(2, 3), emb) + for key in emb: + self.assertTrue(torch.allclose(out[key], torch.full((2, 3), 0.5))) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/core/test_saliency_visualization.py b/tests/core/test_saliency_visualization.py new file mode 100644 index 0000000000..5b691a0fd3 --- /dev/null +++ b/tests/core/test_saliency_visualization.py @@ -0,0 +1,171 @@ +"""Tests for SaliencyVisualizer and visualize_attribution.""" + +import os +import shutil +import tempfile +import unittest + +import matplotlib +matplotlib.use("Agg") # Use non-interactive backend for testing +import matplotlib.pyplot as plt +import numpy as np +import torch + +from pyhealth.interpret.methods.saliency_visualization import ( + SaliencyVisualizer, + visualize_attribution, +) + + +class TestSaliencyVisualizerHelpers(unittest.TestCase): + """Tensor conversion, shape processing and normalization helpers.""" + + def setUp(self): + self.viz = SaliencyVisualizer() + + def test_to_numpy_accepts_tensor_and_array_like(self): + t = torch.ones(2, 2, requires_grad=True) + self.assertIsInstance(self.viz._to_numpy(t), np.ndarray) + out = self.viz._to_numpy([[1.0, 2.0]]) + self.assertIsInstance(out, np.ndarray) + self.assertEqual(out.shape, (1, 2)) + + def test_process_image_shapes(self): + # Batched RGB CHW -> HWC + self.assertEqual(self.viz._process_image(np.random.rand(1, 3, 8, 8)).shape, (8, 8, 3)) + # Single-channel CHW -> HW + self.assertEqual(self.viz._process_image(np.random.rand(1, 8, 8)).shape, (8, 8)) + # Already HWC with one channel -> HW + self.assertEqual(self.viz._process_image(np.random.rand(8, 8, 1)).shape, (8, 8)) + # Grayscale stays 2-D + self.assertEqual(self.viz._process_image(np.random.rand(8, 8)).shape, (8, 8)) + + def test_process_image_rescales_uint8_range(self): + img = np.full((4, 4), 255.0) + self.assertAlmostEqual(self.viz._process_image(img).max(), 1.0) + + def test_process_saliency_shapes(self): + self.assertEqual(self.viz._process_saliency(np.random.rand(1, 3, 8, 8)).shape, (8, 8)) + self.assertEqual(self.viz._process_saliency(np.random.rand(3, 8, 8)).shape, (8, 8)) + self.assertEqual(self.viz._process_saliency(np.random.rand(8, 8)).shape, (8, 8)) + + def test_process_saliency_aggregates_channel_magnitudes(self): + sal = np.stack([np.ones((2, 2)), -np.ones((2, 2))]) + np.testing.assert_allclose(self.viz._process_saliency(sal), np.full((2, 2), 2.0)) + + def test_normalize_range(self): + out = self.viz._normalize_saliency(np.random.rand(16, 16)) + self.assertGreaterEqual(out.min(), 0.0) + self.assertLessEqual(out.max(), 1.0) + self.assertAlmostEqual(out.max(), 1.0) + + def test_normalize_constant_returns_zeros(self): + out = self.viz._normalize_saliency(np.full((4, 4), 3.0)) + np.testing.assert_array_equal(out, np.zeros((4, 4))) + + def test_normalize_signed_uses_magnitude(self): + # Strongly negative and strongly positive pixels should both be bright. + sal = np.zeros((4, 4)) + sal[0, 0] = 5.0 + sal[3, 3] = -5.0 + out = self.viz._normalize_saliency(sal, percentile_clip=0) + self.assertAlmostEqual(out[0, 0], 1.0) + self.assertAlmostEqual(out[3, 3], 1.0) + self.assertAlmostEqual(out[1, 1], 0.0) + + def test_normalize_without_clipping_is_min_max(self): + sal = np.array([[0.0, 1.0], [2.0, 4.0]]) + out = self.viz._normalize_saliency(sal, percentile_clip=0) + np.testing.assert_allclose(out, sal / 4.0) + + +class TestSaliencyVisualizerPlots(unittest.TestCase): + """Smoke tests for each plotting method on the Agg backend.""" + + def setUp(self): + self.viz = SaliencyVisualizer(default_cmap="jet", default_alpha=0.5, figure_size=(4, 4)) + self.rgb = torch.rand(3, 8, 8) + self.gray = torch.rand(1, 8, 8) + self.saliency = torch.randn(8, 8) + self.temp_dir = tempfile.mkdtemp() + + def tearDown(self): + plt.close("all") + shutil.rmtree(self.temp_dir) + + def _path(self, name): + return os.path.join(self.temp_dir, name) + + def test_overlay_rgb_and_gray(self): + for img in (self.rgb, self.gray): + self.viz.plot_saliency_overlay(plt, img, self.saliency, title="t", show=False) + self.assertGreaterEqual(len(plt.get_fignums()), 2) + + def test_overlay_save_and_show(self): + path = self._path("overlay.png") + self.viz.plot_saliency_overlay( + plt, self.rgb.numpy(), self.saliency.numpy(), + alpha=0.2, cmap="hot", normalize=False, show=True, save_path=path, + ) + self.assertTrue(os.path.exists(path)) + + def test_multiple_attributions(self): + attributions = {"grad": torch.randn(8, 8), "lrp": torch.randn(3, 8, 8)} + path = self._path("multi.png") + self.viz.plot_multiple_attributions( + plt, self.rgb, attributions, + method_names={"grad": "Gradient"}, save_path=path, + ) + self.assertTrue(os.path.exists(path)) + # One panel for the image plus one per method (colorbars add more axes) + self.assertGreaterEqual(len(plt.gcf().axes), 3) + + def test_multiple_attributions_gray_unnormalized(self): + self.viz.plot_multiple_attributions( + plt, self.gray, {"grad": self.saliency}, normalize=False, + ) + self.assertGreaterEqual(len(plt.gcf().axes), 2) + + def test_heatmap(self): + path = self._path("heatmap.png") + self.viz.plot_saliency_heatmap(plt, self.saliency, title="Heatmap", save_path=path) + self.assertTrue(os.path.exists(path)) + self.viz.plot_saliency_heatmap(plt, self.saliency, cmap="viridis", normalize=False, show=False) + + def test_attribution_distribution(self): + path = self._path("hist.png") + self.viz.plot_attribution_distribution(plt, self.saliency, title="Dist", bins=10, save_path=path) + self.assertTrue(os.path.exists(path)) + self.viz.plot_attribution_distribution(plt, self.saliency.numpy(), show=False) + self.assertEqual(plt.gca().get_title(), "Attribution Value Distribution") + + def test_top_k_features(self): + path = self._path("topk.png") + self.viz.plot_top_k_features(plt, self.rgb, self.saliency, k=5, title="Top", save_path=path) + self.assertTrue(os.path.exists(path)) + self.viz.plot_top_k_features(plt, self.gray, self.saliency, k=3, show=False) + + +class TestVisualizeAttribution(unittest.TestCase): + """The visualize_attribution convenience dispatcher.""" + + def setUp(self): + self.image = torch.rand(3, 8, 8) + self.attr = torch.randn(8, 8) + + def tearDown(self): + plt.close("all") + + def test_dispatches_each_method(self): + visualize_attribution(plt, self.image, self.attr, title="o", method="overlay", show=False) + visualize_attribution(plt, self.image, self.attr, title="h", method="heatmap", show=False) + visualize_attribution(plt, self.image, self.attr, title="k", method="top_k", k=4, show=False) + self.assertGreaterEqual(len(plt.get_fignums()), 3) + + def test_unknown_method_raises(self): + with self.assertRaises(ValueError): + visualize_attribution(plt, self.image, self.attr, method="bogus") + + +if __name__ == "__main__": + unittest.main()