import os from pathlib import Path from typing import List, Tuple, Dict, Any, Optional import numpy as np import torch import torch.nn as nn from PIL import Image from huggingface_hub import login, hf_hub_download from model_architectures import build_model, infer_with_attention PHIKON_MODEL_ID = "owkin/phikon-v2" HF_WEIGHTS_REPO = os.getenv("HF_WEIGHTS_REPO", "LOP3Zs/Cancer") # Perform Hub authentication at startup if token is available in Space Secrets HF_TOKEN = os.getenv("HF_TOKEN") if HF_TOKEN: try: login(token=HF_TOKEN) print("[Auth] Successfully authenticated with Hugging Face Hub.") except Exception as exc: print(f"[Auth] Hub authentication notice: {exc}") def get_current_device() -> torch.device: """Dynamically get CUDA device if inside @spaces.GPU or CPU otherwise.""" return torch.device("cuda" if torch.cuda.is_available() else "cpu") class PhikonFeatureExtractor: """Singleton for Phikon-v2 ViT foundation feature extractor.""" _instance = None def __init__(self): self.processor = None self.model = None self.is_loaded = False @classmethod def get_instance(cls): if cls._instance is None: cls._instance = cls() return cls._instance def load(self): if self.is_loaded: return from transformers import AutoImageProcessor, AutoModel token = os.getenv("HF_TOKEN") print(f"[Phikon] Initializing {PHIKON_MODEL_ID} processor & weights...") self.processor = AutoImageProcessor.from_pretrained(PHIKON_MODEL_ID, token=token) self.model = AutoModel.from_pretrained(PHIKON_MODEL_ID, token=token).eval() self.is_loaded = True print("[Phikon] Foundation model loaded successfully.") def extract_features(self, images: List[Image.Image], batch_size: int = 16) -> torch.Tensor: """Extract [N, 1024] Phikon-v2 CLS features for a list of RGB tiles.""" if not self.is_loaded: self.load() if not images: return torch.empty((0, 1024), dtype=torch.float32) device = get_current_device() self.model.to(device) feature_chunks = [] with torch.inference_mode(): for i in range(0, len(images), batch_size): batch_imgs = images[i : i + batch_size] inputs = self.processor(images=batch_imgs, return_tensors="pt").to(device) outputs = self.model(**inputs) feats = outputs.last_hidden_state[:, 0, :].detach().cpu().float() feature_chunks.append(feats) return torch.cat(feature_chunks, dim=0) class ModelManager: """Manages downloading, local caching and inference for all 5 MIL architectures.""" _instance = None def __init__(self): self.loaded_models: Dict[str, nn.Module] = {} base_dir = Path(__file__).resolve().parent self.local_dirs = [ base_dir / "weights", base_dir / "weights" / "cohorts", base_dir / "cohorts", Path("./weights"), Path("./cohorts"), Path("../hf_downloaded_models"), Path("./hf_downloaded_models"), ] @classmethod def get_instance(cls): if cls._instance is None: cls._instance = cls() return cls._instance def _normalize_model_name(self, model_type: str) -> str: m = model_type.lower().replace("-", "_").strip() if m in ("clam", "clam_sb", "clamsb"): return "clam" elif m in ("mamba", "mambamil"): return "mamba" return m def _find_or_download_checkpoint(self, cohort: str, target: str, model_type: str, fold: int) -> str: """Locate checkpoint locally or download from Hugging Face Hub.""" c = cohort.lower().strip() t = target.lower().strip() m = self._normalize_model_name(model_type) filename = f"phase2_{t}_{m}_fold{fold}.pt" rel_subpath = f"cohorts/{c}/models/{filename}" # 1. Search local bundled weights for base in self.local_dirs: candidate1 = base / rel_subpath if candidate1.exists(): return str(candidate1) candidate2 = base / c / "models" / filename if candidate2.exists(): return str(candidate2) candidate3 = base / filename if candidate3.exists(): return str(candidate3) # 2. Download from Hugging Face Hub with authenticated token token = os.getenv("HF_TOKEN") print(f"[ModelManager] Fetching checkpoint {rel_subpath} from {HF_WEIGHTS_REPO}...") try: local_path = hf_hub_download( repo_id=HF_WEIGHTS_REPO, filename=rel_subpath, token=token, cache_dir=os.getenv("HF_HOME", "/tmp/hf_cache"), ) return local_path except Exception as exc: msg = str(exc) if "401" in msg or "gated" in msg.lower() or "restricted" in msg.lower(): raise PermissionError( f"Authentication error downloading checkpoint from {HF_WEIGHTS_REPO}. " "Ensure HF_TOKEN is correctly configured in Space Secrets with read access to the repository." ) from exc raise RuntimeError(f"Failed to fetch model checkpoint: {exc}") from exc def load_model(self, cohort: str, target: str, model_type: str, fold: int) -> nn.Module: norm_name = self._normalize_model_name(model_type) cache_key = f"{cohort}_{target}_{norm_name}_{fold}".lower() if cache_key in self.loaded_models: return self.loaded_models[cache_key] ckpt_path = self._find_or_download_checkpoint(cohort, target, model_type, fold) model = build_model(model_type, d=1024, proj=512) checkpoint = torch.load(ckpt_path, map_location="cpu", weights_only=False) state_dict = checkpoint.get("state_dict", checkpoint.get("model_state_dict", checkpoint)) model.load_state_dict(state_dict, strict=True) model.eval() self.loaded_models[cache_key] = model return model def run_inference( self, features: torch.Tensor, cohort: str, target: str, model_type: str, fold_selection: str = "ensemble" ) -> Tuple[float, Optional[np.ndarray]]: """ Run inference across chosen fold or 5-fold ensemble: Returns: probability (float): predicted probability of High Risk attention_scores (Optional[np.ndarray]): 1D array of length N, or None for models like TransMIL. """ if features.shape[0] == 0: return 0.5, None device = get_current_device() if fold_selection.lower() in ( "ensemble", "all", "5-fold", "ensemble (5 folds)", "5-fold ensemble (recommended)" ): probs = [] attns = [] for fold in range(1, 6): m = self.load_model(cohort, target, model_type, fold) m.to(device) p, a = infer_with_attention(m, model_type, features, device) probs.append(p) attns.append(a) mean_prob = float(np.mean(probs)) if all(a is not None for a in attns): mean_attn = np.mean(attns, axis=0) else: mean_attn = None return mean_prob, mean_attn else: fold_num = int("".join(filter(str.isdigit, fold_selection)) or 1) fold_num = max(1, min(5, fold_num)) m = self.load_model(cohort, target, model_type, fold_num) m.to(device) p, a = infer_with_attention(m, model_type, features, device) return float(p), a