"""Interpretability: Grad-CAM for 2D CNN encoders and attention rollout for the slice-plane Transformer in TriFuse-AD. Qualitative only. We do NOT claim the model "detects the hippocampus" - we report that attended regions overlap with anatomy known to be relevant in AD (medial temporal lobe, ventricles, cortical atrophy). """ from __future__ import annotations from pathlib import Path import numpy as np import torch import torch.nn.functional as F class GradCAM: """Grad-CAM on a target conv layer of a 2D CNN. Usage: cam = GradCAM(model, target_layer) heat = cam(input_tensor, class_idx) # (H, W) in [0,1] cam.remove() """ def __init__(self, model: torch.nn.Module, target_layer: torch.nn.Module): self.model = model self.target_layer = target_layer self._acts: torch.Tensor | None = None self._grads: torch.Tensor | None = None self._fh = target_layer.register_forward_hook(self._fwd) self._bh = target_layer.register_full_backward_hook(self._bwd) def _fwd(self, _module, _inp, out): self._acts = out.detach() def _bwd(self, _module, _gin, gout): self._grads = gout[0].detach() def __call__(self, x: torch.Tensor, class_idx: int | None = None) -> np.ndarray: self.model.eval() logits = self.model(x) if isinstance(logits, dict): logits = logits["logits"] if class_idx is None: class_idx = int(logits.argmax(1)[0]) self.model.zero_grad(set_to_none=True) logits[0, class_idx].backward(retain_graph=True) # global-average-pool gradients -> channel weights weights = self._grads.mean(dim=(2, 3), keepdim=True) # (1,C,1,1) cam = (weights * self._acts).sum(dim=1) # (1,H',W') cam = F.relu(cam) cam = cam - cam.min() cam = cam / (cam.max() + 1e-8) cam = F.interpolate(cam.unsqueeze(1), size=x.shape[-2:], mode="bilinear", align_corners=False)[0, 0] return cam.cpu().numpy() def remove(self): self._fh.remove() self._bh.remove() @torch.no_grad() def attention_rollout(attn_maps: list[torch.Tensor]) -> np.ndarray: """Attention rollout (Abnar & Zuidema 2020) over stacked attention matrices. attn_maps: list of (heads, T, T) attention tensors from each Transformer layer. Returns the CLS->token attention (T-1,) after rollout, normalized to [0,1]. """ result = None for a in attn_maps: a = a.mean(0) # average heads -> (T,T) a = a + torch.eye(a.size(0), device=a.device) # add residual a = a / a.sum(dim=-1, keepdim=True) result = a if result is None else a @ result cls_to_tokens = result[0, 1:] # CLS row, drop CLS->CLS cls_to_tokens = cls_to_tokens - cls_to_tokens.min() cls_to_tokens = cls_to_tokens / (cls_to_tokens.max() + 1e-8) return cls_to_tokens.cpu().numpy() def overlay_heatmap(gray: np.ndarray, heat: np.ndarray, alpha: float = 0.45) -> np.ndarray: """Overlay a [0,1] heatmap on a grayscale slice (both HxW) -> RGB uint8.""" import matplotlib gray = (gray - gray.min()) / (np.ptp(gray) + 1e-8) rgb = np.stack([gray] * 3, axis=-1) cmap = matplotlib.colormaps["jet"](heat)[..., :3] out = (1 - alpha) * rgb + alpha * cmap return (np.clip(out, 0, 1) * 255).astype(np.uint8)