Spaces:
Sleeping
Sleeping
Download src/capstone/inference/explainability.py from cs32-2/report-demo: direct link, hf CLI and curl.
- Browser
- Download file 12.4 kB
-
https://huggingface.co/spaces/cs32-2/report-demo/resolve/main/src/capstone/inference/explainability.py
- Command line
-
hf download hf://spaces/cs32-2/report-demo/src/capstone/inference/explainability.py
-
curl -L -o explainability.py https://huggingface.co/spaces/cs32-2/report-demo/resolve/main/src/capstone/inference/explainability.py
12.4 kB
| """Grad-CAM explanations for the WS2 unified classifier. | |
| ``explain()`` returns the max-scaled positive ``[0, 1]`` heatmap, a single-panel blended | |
| composite of the colourised map over the source, and a side-by-side artefact | |
| (original | blended) required by the development plan. | |
| """ | |
| from __future__ import annotations | |
| from dataclasses import dataclass | |
| from typing import TYPE_CHECKING, Literal, Protocol | |
| import matplotlib | |
| import numpy as np | |
| import torch | |
| from PIL import Image | |
| from torch import nn | |
| from torch.nn import functional as F | |
| from capstone.data.label_space import N_POSITIONS | |
| from capstone.inference.image_io import ( | |
| ImageInput, | |
| PreparedImage, | |
| PreprocessingSpec, | |
| prepare_image, | |
| ) | |
| from capstone.inference.source import SourceSnapshot, tensor_digest | |
| from capstone.models import UnifiedClassifier, gradcam_target_layer | |
| if TYPE_CHECKING: | |
| from capstone.inference.engine import PredictionResult | |
| _GUTTER_PX = 8 | |
| class DifferentiatedScore: | |
| method: Literal["forward", "forward_logits"] | |
| kind: Literal["logit", "probability"] | |
| value: float | |
| class ExplanationResult: | |
| target_label: int | |
| heatmap: torch.Tensor | |
| blended: Image.Image | |
| side_by_side: Image.Image | |
| scores_are_logits: bool | |
| label_name: str | None = None | |
| differentiated_score: DifferentiatedScore | None = None | |
| source: SourceSnapshot | None = None | |
| heatmap_sha256: str | None = None | |
| class Explainer(Protocol): | |
| def explain(self, image: ImageInput, target_label: int) -> ExplanationResult: ... | |
| class GradCamExplainer: | |
| """Generate Grad-CAM on pre-sigmoid logits at the registered target layer. | |
| Grad-CAM differentiates the target class score with respect to the target | |
| layer's activations. Differentiating a post-sigmoid probability multiplies | |
| every gradient by ``p*(1-p)``, which goes to exactly zero when float32 | |
| sigmoid saturates. The concrete UnifiedClassifier defaults to its known | |
| pre-sigmoid path. Custom models must explicitly declare a method and kind; | |
| method names are never treated as evidence of score semantics. | |
| The returned artefact is a side-by-side RGB image (original | blended), not | |
| a single blended panel alone. | |
| """ | |
| def __init__( | |
| self, | |
| model: nn.Module, | |
| *, | |
| preprocessing: PreprocessingSpec | None = None, | |
| target_layer: nn.Module | None = None, | |
| device: str | torch.device | None = None, | |
| overlay_alpha: float = 0.45, | |
| score_method: Literal["forward", "forward_logits"] | None = None, | |
| score_kind: Literal["logit", "probability"] | None = None, | |
| ) -> None: | |
| if not 0.0 <= overlay_alpha <= 1.0: | |
| raise ValueError("overlay_alpha must be between 0 and 1") | |
| self.model = model | |
| self.preprocessing = preprocessing or _preprocessing_from_model(model) | |
| # Only the concrete supported implementation has a known default. | |
| # Subclasses/custom models must declare both the method and scalar kind. | |
| if type(model) is UnifiedClassifier and score_method is None and score_kind is None: | |
| score_method, score_kind = "forward_logits", "logit" | |
| if score_method not in ("forward", "forward_logits") or score_kind not in ( | |
| "logit", | |
| "probability", | |
| ): | |
| raise ValueError("declare score_method and score_kind explicitly for custom models") | |
| if not callable(getattr(model, score_method, None)): | |
| raise TypeError(f"model has no callable {score_method}") | |
| if type(model) is UnifiedClassifier and (score_method, score_kind) not in ( | |
| ("forward_logits", "logit"), | |
| ("forward", "probability"), | |
| ): | |
| raise ValueError("score declaration disagrees with UnifiedClassifier semantics") | |
| self.score_method = score_method | |
| self.score_kind = score_kind | |
| self.scores_are_logits = score_kind == "logit" | |
| self.target_layer = target_layer or gradcam_target_layer(model) | |
| self.overlay_alpha = overlay_alpha | |
| if device is None: | |
| self.device = next(model.parameters()).device | |
| else: | |
| self.device = torch.device(device) | |
| self.model.to(self.device) | |
| self.model.eval() | |
| def explain(self, image: ImageInput, target_label: int) -> ExplanationResult: | |
| if not 0 <= target_label < N_POSITIONS: | |
| raise ValueError(f"target_label must be between 0 and {N_POSITIONS - 1}") | |
| prepared = prepare_image(image, self.preprocessing) | |
| return self._explain_prepared( | |
| prepared, | |
| target_label, | |
| label_name=None, | |
| source=SourceSnapshot.capture(self.model, prepared), | |
| ) | |
| def explain_positives( | |
| self, | |
| image: ImageInput, | |
| prediction: PredictionResult, | |
| *, | |
| threshold: float = 0.5, | |
| max_labels: int | None = None, | |
| ) -> tuple[ExplanationResult, ...]: | |
| """Generate one Grad-CAM result per predicted-positive label. | |
| ``threshold=0.5`` is the same provisional Week 1 placeholder as | |
| ``PredictionResult.positive_findings``. WS6 Week 3 replaces it with | |
| per-label thresholds selected on validation data. | |
| Returns an empty tuple when nothing clears the threshold. Abstention | |
| behaviour is a Week 3 deliverable and is not pre-empted here. | |
| """ | |
| positives = prediction.positive_findings(threshold) | |
| if max_labels is not None: | |
| positives = positives[:max_labels] | |
| if not positives: | |
| return () | |
| prepared = prepare_image(image, self.preprocessing) | |
| source = SourceSnapshot.capture(self.model, prepared) | |
| if prediction.source is not None and source != prediction.source: | |
| raise ValueError( | |
| "prediction/explanation source mismatch: image, model, card or preprocessing" | |
| ) | |
| return tuple( | |
| self._explain_prepared( | |
| prepared, | |
| finding.index, | |
| label_name=finding.qualified_name, | |
| source=source, | |
| expected_probability=( | |
| prediction.probabilities[finding.index] | |
| if prediction.source is not None | |
| else None | |
| ), | |
| ) | |
| for finding in positives | |
| ) | |
| def _explain_prepared( | |
| self, | |
| prepared: PreparedImage, | |
| target_label: int, | |
| *, | |
| label_name: str | None, | |
| source: SourceSnapshot, | |
| expected_probability: float | None = None, | |
| ) -> ExplanationResult: | |
| inputs = prepared.tensor.unsqueeze(0).to(self.device) | |
| activations: torch.Tensor | None = None | |
| gradients: torch.Tensor | None = None | |
| def capture_activation(_module: nn.Module, _args: tuple, output: torch.Tensor) -> None: | |
| nonlocal activations, gradients | |
| activations = output | |
| output.register_hook(lambda value: _store_gradient(value)) | |
| def _store_gradient(value: torch.Tensor) -> None: | |
| nonlocal gradients | |
| gradients = value | |
| forward_handle = self.target_layer.register_forward_hook(capture_activation) | |
| try: | |
| self.model.zero_grad(set_to_none=True) | |
| outputs = getattr(self.model, self.score_method)(inputs) | |
| if not isinstance(outputs, torch.Tensor): | |
| raise TypeError("Grad-CAM score method must return a tensor") | |
| if outputs.shape != (1, N_POSITIONS): | |
| raise ValueError( | |
| f"classifier must return shape (1, 35), received {tuple(outputs.shape)}" | |
| ) | |
| if not torch.isfinite(outputs).all(): | |
| raise ValueError("Grad-CAM scores must be finite") | |
| if self.score_kind == "probability" and ((outputs < 0) | (outputs > 1)).any(): | |
| raise ValueError("declared probability scores must be between 0 and 1") | |
| scalar = outputs[0, target_label] | |
| probability = scalar.sigmoid() if self.scores_are_logits else scalar | |
| if expected_probability is not None and not torch.isclose( | |
| probability.detach(), | |
| probability.new_tensor(expected_probability), | |
| atol=1e-6, | |
| rtol=1e-5, | |
| ): | |
| raise ValueError("differentiated score disagrees with exported probability") | |
| scalar_value = float(scalar.detach().cpu()) | |
| scalar.backward() | |
| finally: | |
| forward_handle.remove() | |
| if activations is None or gradients is None: | |
| raise RuntimeError("Grad-CAM hooks did not capture activations and gradients") | |
| if not torch.isfinite(activations).all() or not torch.isfinite(gradients).all(): | |
| raise ValueError("Grad-CAM activations and gradients must be finite") | |
| if gradients.abs().max() == 0: | |
| raise RuntimeError( | |
| "the target produced no gradient signal at the Grad-CAM layer; " | |
| "this usually means the score saturated" | |
| ) | |
| weights = gradients.mean(dim=(2, 3), keepdim=True) | |
| cam = torch.relu((weights * activations).sum(dim=1, keepdim=True)) | |
| cam = F.interpolate( | |
| cam, | |
| size=(prepared.rgb.height, prepared.rgb.width), | |
| mode="bilinear", | |
| align_corners=False, | |
| )[0, 0] | |
| cam = _normalise_heatmap(cam).detach().cpu() | |
| blended = _blend(prepared.rgb, cam, self.overlay_alpha) | |
| return ExplanationResult( | |
| target_label=target_label, | |
| heatmap=cam, | |
| blended=blended, | |
| side_by_side=_side_by_side(prepared.rgb, blended), | |
| scores_are_logits=self.scores_are_logits, | |
| label_name=label_name, | |
| differentiated_score=DifferentiatedScore( | |
| self.score_method, self.score_kind, scalar_value | |
| ), | |
| source=source, | |
| heatmap_sha256=tensor_digest(cam), | |
| ) | |
| def _preprocessing_from_model(model: nn.Module) -> PreprocessingSpec: | |
| card = getattr(model, "model_card", None) | |
| if not isinstance(card, dict) or not isinstance(card.get("preprocessing"), dict): | |
| raise ValueError( # noqa: TRY004 | |
| "a preprocessing spec has to be passed explicitly for models without a WS2 model card" | |
| ) | |
| return PreprocessingSpec.from_model_card(card) | |
| def _normalise_heatmap(heatmap: torch.Tensor) -> torch.Tensor: | |
| """ReLU then divide by the positive maximum; never subtract a baseline. | |
| Positive mass ratios are preserved. A constant positive map becomes ones, | |
| and only a map with no positive values becomes zeros. | |
| """ | |
| if heatmap.numel() == 0 or not torch.isfinite(heatmap).all(): | |
| raise ValueError("CAM must be nonempty and finite") | |
| heatmap = heatmap.clamp_min(0) | |
| maximum = heatmap.max() | |
| if maximum > 0: | |
| heatmap = heatmap / maximum | |
| return heatmap | |
| def _colourise(heatmap: torch.Tensor) -> Image.Image: | |
| """Map a ``[0, 1]`` heatmap through the inferno colormap to an RGB image.""" | |
| values = heatmap.detach().cpu().clamp(0, 1).numpy() | |
| rgba = matplotlib.colormaps["inferno"](values) | |
| rgb = (np.asarray(rgba[..., :3]) * 255.0).astype(np.uint8) | |
| return Image.fromarray(rgb, mode="RGB") | |
| def _blend(image: Image.Image, heatmap: torch.Tensor, alpha: float) -> Image.Image: | |
| """Composite the colourised heatmap over ``image``; zero activations keep the source.""" | |
| source = image.convert("RGB") | |
| coloured = _colourise(heatmap) | |
| mask_values = (heatmap.detach().cpu().clamp(0, 1) * alpha * 255.0).to(torch.uint8).numpy() | |
| mask = Image.fromarray(mask_values, mode="L") | |
| return Image.composite(coloured, source, mask) | |
| def _side_by_side(original: Image.Image, blended: Image.Image) -> Image.Image: | |
| """Place unmodified original left of blended, separated by an 8-pixel white gutter.""" | |
| original_rgb = original.convert("RGB") | |
| blended_rgb = blended.convert("RGB") | |
| width, height = original_rgb.size | |
| canvas = Image.new("RGB", (2 * width + _GUTTER_PX, height), color=(255, 255, 255)) | |
| canvas.paste(original_rgb, (0, 0)) | |
| canvas.paste(blended_rgb, (width + _GUTTER_PX, 0)) | |
| return canvas | |