Astaxanthin commited on
Commit
fc1771f
·
verified ·
1 Parent(s): 8850d81

Upload README.md

Browse files
Files changed (1) hide show
  1. README.md +26 -141
README.md CHANGED
@@ -12,172 +12,57 @@ tags:
12
 
13
  # MOSAIC
14
 
15
- MOSAIC integrates histopathology, clinical information, and genomic alterations for survival prediction. It accepts **WSI patch features**, **structured clinical data**, **SNV/CNV gene lists**, or combinations of these inputs, and returns **overall survival (OS)** and **progression-free survival (PFS)** risk scores. When WSI features are supplied, it also returns a **768-dimensional WSI embedding**.
16
 
17
- This repository includes the trained language encoder, WSI aggregator, vision adaptors, multimodal fusion modules, survival heads, and tokenizer. Raw WSI processing and patch feature extraction are performed separately using [KEEP](https://huggingface.co/Astaxanthin/KEEP).
18
 
19
  ## Installation
20
 
21
  ```bash
22
- pip install "torch>=2.6" "transformers==4.57.1" "nystrom-attention==0.0.14" "safetensors>=0.4" "numpy>=1.26"
23
- # For reading the HDF5 feature files used below:
24
- pip install h5py
25
  ```
26
 
27
- ## Load the model
28
 
29
- Replace `Astaxanthin/MOSAIC` with this repository's Hugging Face ID, or a local directory containing the downloaded model files.
30
 
31
  ```python
 
32
  import torch
33
  from transformers import AutoModel
34
 
35
  device = "cuda" if torch.cuda.is_available() else "cpu"
36
  model = AutoModel.from_pretrained(
37
- "Astaxanthin/MOSAIC",
38
- trust_remote_code=True,
39
  ).to(device).eval()
40
- ```
41
-
42
- `trust_remote_code=True` loads the custom modeling code in this repository. The tokenizer is bundled and loaded automatically by `predict`; no separate KEEP checkpoint is needed at this stage.
43
 
44
- ## Quick start: clinical data
45
-
46
- No WSI features or genomic data are required for clinical-only inference.
47
-
48
- ```python
49
- clinical = {
50
- "age": 65,
51
- "sex": "Male",
52
- "stage": "II",
53
- "grade": "G2",
54
- "subtype": "Pancreatic Adenocarcinoma",
55
- }
56
 
57
  output = model.predict(
58
- cancer_type="Pancreatic Cancer",
59
- clinical=clinical,
 
 
 
60
  )
 
 
61
  print("OS risk:", output["os_risk"].item())
62
  print("PFS risk:", output["pfs_risk"].item())
63
- ```
64
-
65
- ## Compare four input combinations
66
-
67
- This example uses the same patient and clinical information for all four settings. The genomic input is a **TP53-only SNV panel**; CNV is left unknown. Set the SNV list to `[]` for a patient known to be TP53-negative in this panel, or `-1` if SNV status is unknown.
68
-
69
- ```python
70
- import h5py
71
-
72
- # KEEP patch features and spatial coordinates for one slide.
73
- with h5py.File("slide_features.h5", "r") as f:
74
- patch_features = f["features"][:] # [N, 768]
75
- patch_coords = f["coords"][:] # [N, 2], corresponding (x, y)
76
-
77
- metadata = {
78
- "cancer_type": "Pancreatic Cancer",
79
- "clinical": clinical,
80
- }
81
- vision = {
82
- "patch_features": patch_features,
83
- "patch_coords": patch_coords,
84
- }
85
- genomics = {"snv": ["TP53"], "cnv": -1}
86
-
87
- outputs = {
88
- "Clinical": model.predict(**metadata),
89
- "Clinical + vision": model.predict(**metadata, **vision),
90
- "Clinical + genomics": model.predict(**metadata, genomics=genomics),
91
- "Clinical + vision + genomics": model.predict(
92
- **metadata, **vision, genomics=genomics
93
- ),
94
- }
95
-
96
- for setting, result in outputs.items():
97
- print(
98
- f"{setting}: OS={result['os_risk'].item():.6f}, "
99
- f"PFS={result['pfs_risk'].item():.6f}"
100
- )
101
-
102
- result = outputs["Clinical + vision + genomics"]
103
- print("WSI embedding:", result["wsi_features"].shape) # [1, 768]
104
- print("Spatial views:", result["num_views"])
105
- ```
106
-
107
- The example illustrates inference, not C-index calculation: evaluation additionally requires observed survival times and event indicators for a cohort.
108
-
109
- ## Vision-only and genomics-only inputs
110
-
111
- The following examples reuse the model and slide features loaded above.
112
 
113
- ```python
114
- # WSI embedding and risks from the vision branch.
115
- vision_output = model.predict(
116
- patch_features=patch_features,
117
- patch_coords=patch_coords,
118
- )
119
-
120
- # Genomics without clinical covariates; cancer type supplies context.
121
- genomic_output = model.predict(
122
  cancer_type="Lung Adenocarcinoma",
123
- genomics={"snv": ["TP53"], "cnv": ["CDKN2A"]},
124
  )
125
- ```
126
-
127
- Supplying WSI together with clinical data, genomics, or cancer type selects multimodal fusion. To use the vision-only branch, omit all text inputs, including cancer type. Without WSI, inference uses the language branch.
128
-
129
- ## Input reference
130
-
131
- | Input | Format | Description |
132
- |---|---|---|
133
- | `patch_features` | NumPy array or tensor, `[N, 768]` | KEEP patch features for one slide; finite values, `N > 0`. |
134
- | `patch_coords` | NumPy array or tensor, `[N, 2]` | Integer spatial coordinates in the feature-extraction coordinate system, in the same order as the features. Required for spatial inference with `predict`. |
135
- | `cancer_type` | String | Cancer-type context, using the training naming convention. |
136
- | `clinical` | Dictionary | Supported keys: `age`, `sex`, `stage`, `grade`, `subtype`. Aliases: `diagnosis age`, `gender`, `tumor stage`. |
137
- | `genomics` | Dictionary | `snv` and `cnv` contain lists of qualifying gene names. These are not raw variants or numeric copy-number values. |
138
-
139
- Use the same feature extractor, clinical coding, and driver-gene filtering conventions as training. Other patch encoders are not interchangeable with KEEP merely because their output dimension is 768.
140
-
141
- **Missingness matters:** omitted genomic keys, `None`, and `-1` mean unknown. An empty list `[]` means no qualifying alteration in the evaluated gene set. For a selected panel, filter the observed gene list to that panel before calling the model; the API does not select a panel automatically. Do not encode unmeasured genomic data as `[]`.
142
-
143
- The interface processes one slide/patient input at a time. All output tensors are returned on the CPU.
144
 
145
- ## Spatial views and outputs
146
-
147
- `model.predict` reconstructs spatial layouts from coordinates, pads small slides, and covers larger slides with deterministic **80 × 80 patch-grid views**, preserving the evaluation preprocessing. Missing grid positions are zero-filled.
148
-
149
- **OS and PFS risks are independently max-pooled across views.** The WSI embedding is an elementwise maximum of the shared view embeddings; risks are not recalculated from this pooled embedding. For an already prepared spatial view, use `model.predict_view(...)` to bypass cropping.
150
-
151
- | Output | Meaning |
152
- |---|---|
153
- | `os_risk`, `pfs_risk` | One risk score per endpoint. Higher values indicate greater predicted risk. |
154
- | `wsi_features` | Shared WSI embedding, `[1, 768]`, before endpoint-specific vision adaptors; `None` without WSI. |
155
- | `view_wsi_features` | Shared embeddings for each spatial view, `[V, 768]`. |
156
- | `view_os_risk`, `view_pfs_risk` | Per-view risks, `[V]`. |
157
- | `num_views` | Number of spatial views, `V`. |
158
- | `branch` | Selected inference branch. |
159
-
160
- Per-view outputs and `num_views` are provided by `predict` when WSI is supplied. Multiple slides belonging to one patient are not aggregated automatically. To reproduce the HCMI evaluation below, take the **mean of the slide-level risks** for each patient, after max pooling within each slide.
161
-
162
- ## Inference verification
163
-
164
- The packaged model was checked against existing HCMI OS evaluation outputs using 69 slides from 35 patients with 15 observed events. The same patients were used in all settings, with TP53 SNV as the only genomic input.
165
-
166
- | Inputs | Patient-level OS C-index |
167
- |---|---:|
168
- | Clinical | 0.675214 |
169
- | Clinical + vision | 0.700855 |
170
- | Clinical + TP53 SNV | 0.689459 |
171
- | Clinical + vision + TP53 SNV | 0.723647 |
172
-
173
- All four C-indices and patient risk rankings matched the reference evaluation. Raw risk values showed small numerical differences (maximum absolute difference below 0.0003). This is a packaging reproducibility check on this cohort, not a comprehensive evaluation of model performance.
174
-
175
- ## Scope and attribution
176
-
177
- Risk scores are relative predictions, not calibrated survival probabilities or predicted survival times. Performance depends on cancer type, endpoint, available inputs, and cohort. This repository provides research inference code and does not establish suitability for clinical decision-making.
178
 
179
- The model combines separately pretrained clinical/genomic and pathology components. The language encoder and risk heads use cBioPortal pretraining; the vision aggregator uses SSL pretraining. KEEP supplies the patch-feature representation and tokenizer/configuration assets. See [KEEP](https://huggingface.co/Astaxanthin/KEEP) for its source and terms. The KEEP image encoder is not included here.
180
 
181
- <!-- Before public release: replace YOUR_ACCOUNT/MOSAIC above; add the paper,
182
- training-data/methods reference, author/contact information, and chosen license.
183
- Do not infer the MOSAIC license from the license of its dependencies. -->
 
12
 
13
  # MOSAIC
14
 
15
+ MOSAIC integrates histopathology, clinical information, and genomics for survival prediction. It accepts WSI patch features, clinical data, and/or SNV/CNV gene lists, and returns **OS and PFS risk scores**. When WSI features are provided, it also returns a **768-dimensional WSI embedding**.
16
 
17
+ For data preparation, treatment-response evaluation, and further documentation, see **[MAGIC-AI4Med/MOSAIC on GitHub](https://github.com/MAGIC-AI4Med/MOSAIC)**.
18
 
19
  ## Installation
20
 
21
  ```bash
22
+ pip install "torch>=2.6" "transformers==4.57.1" "nystrom-attention==0.0.14" "safetensors>=0.4" "numpy>=1.26" h5py
 
 
23
  ```
24
 
25
+ ## Usage
26
 
27
+ Replace `YOUR_ACCOUNT/MOSAIC` with the Hugging Face repository ID or a local model directory. WSI patch features should be extracted using [KEEP](https://huggingface.co/Astaxanthin/KEEP).
28
 
29
  ```python
30
+ import h5py
31
  import torch
32
  from transformers import AutoModel
33
 
34
  device = "cuda" if torch.cuda.is_available() else "cpu"
35
  model = AutoModel.from_pretrained(
36
+ "YOUR_ACCOUNT/MOSAIC", trust_remote_code=True,
 
37
  ).to(device).eval()
 
 
 
38
 
39
+ # One slide: KEEP patch features and matching spatial coordinates.
40
+ with h5py.File("slide_features.h5", "r") as f:
41
+ features = f["features"][:] # [N, 768]
42
+ coords = f["coords"][:] # [N, 2]
 
 
 
 
 
 
 
 
43
 
44
  output = model.predict(
45
+ patch_features=features,
46
+ patch_coords=coords,
47
+ cancer_type="Lung Adenocarcinoma",
48
+ clinical={"age": 65, "sex": "Male", "stage": "II"},
49
+ genomics={"snv": ["TP53"], "cnv": ["CDKN2A"]},
50
  )
51
+
52
+ print("WSI embedding:", output["wsi_features"].shape) # [1, 768]
53
  print("OS risk:", output["os_risk"].item())
54
  print("PFS risk:", output["pfs_risk"].item())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
 
56
+ # Clinical-only inference: omit WSI and genomic inputs.
57
+ clinical_output = model.predict(
 
 
 
 
 
 
 
58
  cancer_type="Lung Adenocarcinoma",
59
+ clinical={"age": 65, "sex": "Male", "stage": "II"},
60
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
+ # Vision-only inference: omit all text inputs.
63
+ vision_output = model.predict(patch_features=features, patch_coords=coords)
64
+ ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
 
66
+ `predict` handles spatial views automatically and independently max-pools OS/PFS risks across views. Higher scores indicate higher predicted risk, not calibrated survival probabilities. Without WSI, `wsi_features` is `None`.
67
 
68
+ For genomics, omitted fields or `-1` mean unknown; `[]` means no qualifying alteration in the evaluated gene set. See the [GitHub repository](https://github.com/MAGIC-AI4Med/MOSAIC) for input conventions and task-specific evaluation protocols.