"""Model-independent inference engine for WS6.""" from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Any, Protocol import torch from capstone.data.label_space import N_POSITIONS, load_label_space from capstone.inference.domain_inference import DomainPrediction, infer_domain from capstone.inference.image_io import ImageInput, PreprocessingSpec, prepare_image from capstone.inference.source import SourceSnapshot from capstone.models import load_classifier class Classifier(Protocol): """Minimum model surface WS6 needs from the WS2 classifier.""" def __call__(self, inputs: torch.Tensor) -> torch.Tensor: ... @dataclass(frozen=True) class Finding: index: int qualified_name: str display_name: str domain: str probability: float @dataclass(frozen=True) class PredictionResult: probabilities: tuple[float, ...] labels: tuple[str, ...] inferred_domain: DomainPrediction preprocessing: PreprocessingSpec findings: tuple[Finding, ...] domain_metadata: dict[str, Any] label_source: str source: SourceSnapshot | None = None penultimate_features: tuple[float, ...] | None = None def positive_findings(self, threshold: float = 0.5) -> tuple[Finding, ...]: """Return findings at or above ``threshold``. ``0.5`` is a provisional Week 1 placeholder. WS6 Week 3 selects per-label thresholds from validation data. No result computed with this default may be reported. These are independent threshold candidates for every domain, including multi-class domains. They are not a final task-aware decision policy. """ return tuple(finding for finding in self.findings if finding.probability >= threshold) class InferenceEngine: """Run a supplied classifier without assuming a WS2 checkpoint format.""" def __init__( self, model: Classifier, *, preprocessing: PreprocessingSpec, outputs_are_logits: bool = False, device: str | torch.device = "cpu", ) -> None: """Construct an inference engine around a callable classifier. ``outputs_are_logits=False`` matches the WS2 checkpoint contract (``output_activation == "sigmoid"``). A caller passing a model which returns raw logits must set this to ``True`` explicitly. """ self.model = model self.preprocessing = preprocessing self.outputs_are_logits = outputs_are_logits self.device = torch.device(device) ( self.label_positions, self.domain_metadata, self.label_source, ) = _resolve_label_metadata(model) to_method = getattr(model, "to", None) if callable(to_method): to_method(self.device) eval_method = getattr(model, "eval", None) if callable(eval_method): eval_method() @classmethod def from_checkpoint( cls, checkpoint: str | Path, *, device: str | torch.device = "cpu", ) -> InferenceEngine: """Load a WS2 bundle and derive inference settings from its model card.""" model = load_classifier(checkpoint, device=device) card = model.model_card return cls( model, preprocessing=PreprocessingSpec.from_model_card(card), outputs_are_logits=card["output_activation"] != "sigmoid", device=device, ) def predict(self, image: ImageInput, *, capture_features: bool = False) -> PredictionResult: prepared = prepare_image(image, self.preprocessing) inputs = prepared.tensor.unsqueeze(0).to(self.device) source = ( SourceSnapshot.capture(self.model, prepared) if isinstance(self.model, torch.nn.Module) else None ) features: list[torch.Tensor] = [] handle = None if capture_features: backbone = getattr(self.model, "backbone", None) layer = getattr(backbone, "fc", None) if not isinstance(layer, torch.nn.Linear) or layer.in_features != 512: raise ValueError("centroid guard requires the 512-dimensional backbone.fc input") def capture(_module, arguments): if len(arguments) != 1 or not isinstance(arguments[0], torch.Tensor): raise ValueError("unexpected penultimate feature input") features.append(arguments[0].detach().clone()) handle = layer.register_forward_pre_hook(capture) try: with torch.inference_mode(): outputs = self.model(inputs) finally: if handle is not None: handle.remove() penultimate = None if capture_features: if len(features) != 1 or features[0].shape != (1, 512): raise ValueError("classifier did not produce exactly one 512-dimensional feature") penultimate = tuple(float(value) for value in features[0][0].cpu().tolist()) if not isinstance(outputs, torch.Tensor): raise TypeError("classifier must return a torch.Tensor") if outputs.shape == (1, N_POSITIONS): outputs = outputs[0] if outputs.shape != (N_POSITIONS,): raise ValueError( f"classifier must return shape (35,) or (1, 35), received {tuple(outputs.shape)}" ) probabilities_tensor = torch.sigmoid(outputs) if self.outputs_are_logits else outputs probabilities = tuple(float(value) for value in probabilities_tensor.cpu().tolist()) inferred_domain = infer_domain(probabilities) findings = _findings_for_domain( self.label_positions, probabilities, inferred_domain.domain, ) winning_domain = next( record for record in self.domain_metadata if record["name"] == inferred_domain.domain ) return PredictionResult( probabilities=probabilities, labels=tuple(position["qualified_name"] for position in self.label_positions), inferred_domain=inferred_domain, preprocessing=prepared.preprocessing, findings=findings, domain_metadata=dict(winning_domain), label_source=self.label_source, source=source, penultimate_features=penultimate, ) def _resolve_label_metadata( model: Classifier, ) -> tuple[tuple[dict[str, Any], ...], tuple[dict[str, Any], ...], str]: card = getattr(model, "model_card", None) if ( isinstance(card, dict) and isinstance(card.get("ordered_labels"), list) and isinstance(card.get("domains"), list) ): return ( tuple(card["ordered_labels"]), tuple(card["domains"]), "model_card", ) label_space = load_label_space() return ( tuple(label_space["positions"]), tuple(label_space["domains"]), "label_space_package", ) def _findings_for_domain( label_positions: tuple[dict[str, Any], ...], probabilities: tuple[float, ...], domain: str, ) -> tuple[Finding, ...]: findings = [ Finding( index=int(position["index"]), qualified_name=str(position["qualified_name"]), display_name=str(position["display_name"]), domain=str(position["domain"]), probability=probabilities[int(position["index"])], ) for position in label_positions if position["domain"] == domain ] findings.sort(key=lambda finding: finding.probability, reverse=True) return tuple(findings)