Feature Extraction
Transformers
Safetensors
English
mosaic
computational-pathology
multimodal
survival-analysis
custom_code
Instructions to use Astaxanthin/MOSAIC with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Astaxanthin/MOSAIC with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("feature-extraction", model="Astaxanthin/MOSAIC", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("Astaxanthin/MOSAIC", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Download predictor.py from Astaxanthin/MOSAIC: direct link, hf CLI and curl.
- Browser
- Download file 7.19 kB
-
https://huggingface.co/Astaxanthin/MOSAIC/resolve/main/predictor.py
- Command line
-
hf download hf://Astaxanthin/MOSAIC/predictor.py
-
curl -L -o predictor.py https://huggingface.co/Astaxanthin/MOSAIC/resolve/main/predictor.py
7.19 kB
| """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() | |
| 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)) | |
| 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 | |
| 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"], | |
| } | |