"""Single-slide inference with spatial views and independent max-risk pooling.""" import torch from transformers import AutoModel, AutoTokenizer from .model import MOSAIC2DBM from .spatial import SpatialViews class MOSAICPredictor: def __init__(self, model): self.model = model.eval() @classmethod def from_pretrained(cls, checkpoint, encoder_path, *, feats_dim, task_id, device="cpu", trans_num=3, trust_remote_code=False, **model_kwargs): """Architecture arguments must match training. Load a state_dict only.""" encoder = AutoModel.from_pretrained(encoder_path, trust_remote_code=trust_remote_code) tokenizer = AutoTokenizer.from_pretrained(encoder_path, trust_remote_code=trust_remote_code) model = MOSAIC2DBM(encoder, tokenizer, feats_dim, trans_num, task_id, [1.0, 0.0], device, **model_kwargs) state = torch.load(checkpoint, map_location="cpu", weights_only=True) for key in ("state_dict", "model_state_dict", "model"): if key in state and isinstance(state[key], dict): state = state[key] break state = {k.removeprefix("module."): v for k, v in state.items()} model.load_state_dict(state, strict=True) return cls(model.to(device)) @torch.inference_mode() def predict_view(self, *, patch_features=None, patch_coords=None, cancer_type=None, clinical=None, genomics=None): """Return CPU tensors for one patient/view. Missing WSI -> wsi_features=None.""" if patch_features is None and clinical is None and genomics is None: raise ValueError("Provide at least one modality.") if patch_coords is not None and patch_features is None: raise ValueError("Coordinates require patch_features.") device = next(self.model.parameters()).device if patch_features is not None: patch_features = torch.as_tensor(patch_features, dtype=torch.float32, device=device) if patch_features.ndim != 2 or patch_features.shape[0] == 0 or patch_features.shape[1] != self.model.feats_dim: raise ValueError("patch_features must have shape [N, feats_dim], N > 0.") if not torch.isfinite(patch_features).all(): raise ValueError("Patch features must be finite.") if patch_coords is not None: patch_coords = torch.as_tensor(patch_coords, device=device) if patch_coords.shape != (patch_features.shape[0], 2) or not torch.isfinite(patch_coords).all(): raise ValueError("patch_coords must be finite [N, 2].") patch_coords = patch_coords.unsqueeze(0) patch_features = patch_features.unsqueeze(0) has_text = clinical is not None or genomics is not None or cancer_type is not None clinical = dict(clinical or {}) allowed = {"age", "sex", "stage", "grade", "subtype", "diagnosis age", "gender", "tumor stage"} if set(clinical) - allowed: raise ValueError(f"Unknown clinical keys: {set(clinical) - allowed}") g = dict(genomics or {}) if set(g) - {"snv", "cnv"}: raise ValueError("genomics supports snv and cnv only.") prior = {"mutation": g.get("snv", -1), "cnv": g.get("cnv", -1), "grade": clinical.pop("grade", -1), "subtype": clinical.pop("subtype", -1)} # Select the trained branch explicitly; never fabricate absent genomic negatives. branch = "text" if patch_features is None else ("both" if has_text else "vision") result = self.model(cancer_type=[cancer_type or "unknown"], slide_treatments=[-1], tile_features=patch_features, surv_prior=[prior], gene_des={}, slide_clinical=[clinical], project_id=[""], mode="test", test_type=branch, patch_coords=patch_coords, test_random_mask=False, test_mask_fields=None) keys = {"wsi_features": "vision_feats", "os_risk": "selected_os_risk", "pfs_risk": "selected_pfs_risk"} output = {name: None if result[key] is None else result[key].detach().cpu() for name, key in keys.items()} output["branch"] = result["selected_branch"] return output @torch.inference_mode() def predict(self, *, patch_features=None, patch_coords=None, cancer_type=None, clinical=None, genomics=None): """Crop a WSI spatially, infer each view, then max-pool risks independently. Matches eval_risk_pool='risk', eval_view_pool='max'. Features are elementwise-max pooled separately; risks are NOT recomputed from them. Use predict_view explicitly for already prepared crops. """ metadata = dict(cancer_type=cancer_type, clinical=clinical, genomics=genomics) if patch_features is None: if patch_coords is not None: raise ValueError("Coordinates require patch_features.") return self.predict_view(**metadata) if patch_coords is None: raise ValueError("Spatial cropping requires patch_coords [N,2]. " "For preprocessed inputs use predict_view().") features = torch.as_tensor(patch_features).detach().cpu() coords = torch.as_tensor(patch_coords).detach().cpu() if features.ndim != 2 or features.shape[0] == 0 or features.shape[1] != self.model.feats_dim: raise ValueError("patch_features must be nonempty [N, feats_dim].") if coords.shape != (features.shape[0], 2): raise ValueError("patch_coords must have shape [N,2].") if not torch.isfinite(features).all() or not torch.isfinite(coords).all(): raise ValueError("Features and coordinates must be finite.") if not torch.equal(coords, coords.round()): raise ValueError("Use integer patch coordinates in the original coordinate system.") features, coords = SpatialViews()._prepare_eval_2d_features( features.float().numpy(), coords.numpy()) if features.ndim == 2: features, coords = features[None], coords[None] outputs = [self.predict_view(patch_features=f, patch_coords=c, **metadata) for f, c in zip(features, coords)] view_feats = torch.cat([o["wsi_features"] for o in outputs], dim=0) os_risks = torch.cat([o["os_risk"].reshape(-1) for o in outputs]) pfs_risks = torch.cat([o["pfs_risk"].reshape(-1) for o in outputs]) return { "wsi_features": view_feats.max(dim=0, keepdim=True).values, "os_risk": os_risks.max().reshape(1), "pfs_risk": pfs_risks.max().reshape(1), "view_wsi_features": view_feats, "view_os_risk": os_risks, "view_pfs_risk": pfs_risks, "num_views": len(outputs), "branch": outputs[0]["branch"], }