Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
e816c96
Add MedMod in-hospital mortality dataset and task (MIMIC-IV v1.0 + CXR)
dhtrg Nov 17, 2026
53ec769
Add EHRCXREarlyFusion and ConVIRT models with tests and docs
Rainie-Hu Nov 17, 2026
024757e
Add variable-length EHR batching for MedMod ConVIRT pretraining
dhtrg Nov 19, 2026
82addfc
Fix PR-rule issues in MedMod data code (ruff + docstring examples)
dhtrg Nov 19, 2026
e0a8419
Merge remote-tracking branch 'origin/medmod-data' into feature/medmod…
Rainie-Hu Nov 19, 2026
b60d0d6
Pack variable-length EHR in ConVIRT; note frozen encoders' eval mode
Rainie-Hu Nov 19, 2026
751b996
Merge pull request #1 from Rainie-Hu/feature/medmod-reproduction
dhtrg Nov 19, 2026
4c7b94b
Let ConVIRT take precomputed image embeddings (MedSigLIP extension)
Rainie-Hu Nov 20, 2026
e1465c4
Merge branch 'medmod-data' into feature/medmod-reproduction
Rainie-Hu Nov 20, 2026
2102d24
Add the Early Fusion example for MedMod in-hospital mortality
Rainie-Hu Nov 20, 2026
786bef1
Add MedMod ConVIRT pretraining data and example
dhtrg Nov 20, 2026
9e72078
Add MedSigLIP image embeddings for the MedMod extension
dhtrg Nov 20, 2026
023cadc
Merge pull request #2 from Rainie-Hu/feature/medmod-reproduction
dhtrg Nov 20, 2026
9a8650d
Add MedSigLIP --embeddings option to the MedMod examples
dhtrg Nov 20, 2026
7c86e80
Default the ConVIRT example to CUDA, then CPU and MPS opt-in
dhtrg Nov 21, 2026
115b064
Address review: --device (MPS opt-in), pending results, embedding doc…
Rainie-Hu Nov 21, 2026
06b4a13
Merge branch 'medmod-data' of https://github.com/Rainie-Hu/PyHealth i…
Rainie-Hu Nov 21, 2026
82eb950
Reject cxr_feature_dim with a ResNet name in Early Fusion, as in ConVIRT
Rainie-Hu Nov 21, 2026
16de2ec
Merge pull request #3 from Rainie-Hu/feature/medmod-reproduction
dhtrg Nov 21, 2026
2fed08f
Add docstrings and type hints to the MedMod data code
dhtrg Nov 24, 2026
7264911
Add synthetic MedSigLIP embeddings and speed up the MedMod tests
dhtrg Nov 24, 2026
1326782
Download MedMod's item map on first use instead of bundling it
dhtrg Nov 24, 2026
2dff074
Update the MedMod examples with five-seed results and deviations
dhtrg Nov 24, 2026
340df96
Add the MedMod real-data runner scripts and their Colab notebook
dhtrg Nov 24, 2026
6f9f734
Add the MedMod in-hospital mortality results page
dhtrg Nov 24, 2026
6f0f303
Speed up the ConVIRT loss test: 5 training steps instead of 15
Rainie-Hu Nov 24, 2026
a94e9a7
Merge remote-tracking branch 'upstream/master' into feature/medmod-re…
Rainie-Hu Nov 24, 2026
4472fe2
Drop the Joint Fusion mention from the Early Fusion docstring
Rainie-Hu Nov 25, 2026
e2b2ee2
Rename the MedMod normalizer file: Windows does not allow colons
Rainie-Hu Nov 25, 2026
9bd214f
Fix outdated MedMod docstrings and results notes
dhtrg Nov 26, 2026
a3d7dc7
Merge master and update to the final code of the split PRs
dhtrg Nov 30, 2026
5636906
Update to the final code of the split PRs
dhtrg Nov 30, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/api/datasets.rst
Original file line number Diff line number Diff line change
Expand Up @@ -668,6 +668,7 @@ Available Datasets
datasets/pyhealth.datasets.MIMIC4EDDataset
datasets/pyhealth.datasets.KiTS23Dataset
datasets/pyhealth.datasets.MIMIC4ImaGenomeDataset
datasets/pyhealth.datasets.MedModMIMIC4Dataset
datasets/pyhealth.datasets.BrainTumorMRIDataset
datasets/pyhealth.datasets.FHIRDataset
datasets/pyhealth.datasets.MEDSDataset
Expand Down
59 changes: 59 additions & 0 deletions docs/api/datasets/pyhealth.datasets.MedModMIMIC4Dataset.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
pyhealth.datasets.MedModMIMIC4Dataset
=====================================

MIMIC-IV v1.0 and MIMIC-CXR-JPG 2.0.0 as used by MedMod (Elsharief et al.,
"MedMod: Multimodal Benchmark for Medical Prediction Tasks with Electronic
Health Records and Chest X-Ray Scans", CHIL 2025, PMLR 287;
`paper <https://proceedings.mlr.press/v287/elsharief25a.html>`__,
`code <https://github.com/nyuad-cai/MedMod>`__) for in-hospital mortality,
with MedMod's fixed train / val / test split. Use it with
:class:`~pyhealth.tasks.MedModInHospitalMortality`.

Access to `MIMIC-IV v1.0 <https://physionet.org/content/mimiciv/1.0/>`__
and `MIMIC-CXR-JPG 2.0.0 <https://physionet.org/content/mimic-cxr-jpg/2.0.0/>`__
needs PhysioNet credentialing.
Without it, ``pyhealth.datasets.medmod.synthetic.create_synthetic_samples``
builds synthetic samples with the same contract.

.. autoclass:: pyhealth.datasets.MedModMIMIC4Dataset
:members:
:undoc-members:
:show-inheritance:

.. autoclass:: pyhealth.datasets.MedModSplit
:members:
:undoc-members:
:show-inheritance:

.. autofunction:: pyhealth.datasets.split_by_medmod

MedSigLIP image embeddings
--------------------------

For the extension, :mod:`pyhealth.datasets.medmod.medsiglip` replaces the
ResNet-34 image features with those of a frozen ``google/medsiglip-448``
image encoder. Each image is embedded once and saved to one ``.npz`` file,
where the embeddings are looked up by image file name.

MedSigLIP (`google/medsiglip-448 <https://huggingface.co/google/medsiglip-448>`__)
is introduced in Sellergren et al., "MedGemma Technical Report", Nature
Medicine 32, 3695-3704 (2026), https://doi.org/10.1038/s41591-026-04626-w
(preprint arXiv:2507.05201). Its weights are downloaded from the Hugging Face Hub
under the `Health AI Developer Foundations terms of use
<https://developers.google.com/health-ai-developer-foundations/terms>`__.

.. automodule:: pyhealth.datasets.medmod.medsiglip
:members:

ConVIRT pretraining samples
---------------------------

ConVIRT is pretrained on MedMod's phenotyping train and validation stays, each
with its whole ICU stay of EHR and its latest AP chest X-ray.
:mod:`pyhealth.datasets.medmod.pretraining` builds these samples from the
output of MedMod's extraction scripts and the MIMIC-CXR-JPG metadata
(``load_pretraining_samples``) and turns them into a PyHealth dataset
(``create_pretraining_dataset``).

.. automodule:: pyhealth.datasets.medmod.pretraining
:members:
1 change: 1 addition & 0 deletions docs/api/tasks.rst
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,7 @@ Available Tasks
LabTOP Lab Value Prediction (HiRID) <tasks/pyhealth.tasks.labtop_hirid>
Length of Stay Prediction <tasks/pyhealth.tasks.length_of_stay_prediction>
Length of Stay Prediction (StageNet MIMIC-IV) <tasks/pyhealth.tasks.length_of_stay_stagenet_mimic4>
MedMod In-Hospital Mortality (MIMIC-IV + CXR) <tasks/pyhealth.tasks.MedModInHospitalMortality>
Medical Transcriptions Classification <tasks/pyhealth.tasks.MedicalTranscriptionsClassification>
MPF Clinical Prediction (FHIR) <tasks/pyhealth.tasks.mpf_clinical_prediction>
Mortality Prediction (Next Visit) <tasks/pyhealth.tasks.mortality_prediction>
Expand Down
89 changes: 89 additions & 0 deletions docs/api/tasks/pyhealth.tasks.MedModInHospitalMortality.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
pyhealth.tasks.MedModInHospitalMortality
========================================

In-hospital mortality from the first 48 hours of an ICU stay and the latest
chest X-ray in that window, reproducing MedMod (Elsharief et al., 2025) and its
released code: one sample per ICU stay with ``ehr`` (48 x 76), ``image_path``
and ``label``. Use it with :class:`~pyhealth.datasets.MedModMIMIC4Dataset`.

.. autoclass:: pyhealth.tasks.MedModInHospitalMortality
:members:
:undoc-members:
:show-inheritance:

.. autoclass:: pyhealth.processors.medmod_ehr_processor.MedModEHRProcessor
:members:
:undoc-members:
:show-inheritance:

Per-model settings
------------------

MedMod's models read their data through two code paths. Both use the same
cohort, labels and split. They differ in the EHR rows at Hours == 0, which the
task sets with ``hours_zero``, and in the image transform. The task returns
``image_path`` and applies no image transform: the "Image transform" column is
what the model's own image loader applies.

.. list-table::
:header-rows: 1

* - Model
- ``hours_zero``
- Image transform
- Why
* - Early Fusion
- ``"keep"``
- ``get_preset("early_fusion", ...)`` (ImageNet-normalized)
- MedMod's supervised ``fusion_main.py:13-16`` imports ``datasets.*`` and
``ehr_utils.*``, which exist only in MedFuse; MedFuse's
``datasets/ehr_dataset.py`` keeps every row and
``datasets/cxr_dataset.py`` normalizes.
* - ConVIRT (pretraining, linear evaluation)
- ``"drop"``
- ``get_preset("convirt", ...)`` (pixels in [0, 1])
- MedMod's ``src/data/datasets.py:137-163`` keeps 0 < t only; the ConVIRT
scripts pass ``--transforms_cxr simclrv2``.

``get_preset`` and ``load_cxr`` are in ``pyhealth.datasets.medmod.image_presets``;
``train=True`` adds the training augmentation.

Paper vs code
-------------

Where MedMod's paper and released code disagree, the task follows the code,
which produced the reported numbers. The bin width and the normalizer remain
settings of the task (``timestep``, ``normalizer``).

.. list-table::
:header-rows: 1

* - Rule
- MedMod paper
- Released code
- Default here
* - Bin width
- §3.2.2 "every two hours" (MedFuse §4.1.1 too)
- 1 h (``--timestep`` default 1.0, ``src/parser.py:30``)
- 1 h (``timestep``)
* - Normalizer
- §3.2.2 "task-specific", computed on the dataset
- the phenotyping file ``ph_ts1.0`` (an ``is`` comparison in ``ehr_funcs``)
- ``ph_ts1.0``; ``normalizer=None`` fits one on the train split
* - Split
- §3.2.4 random 70/10/20 by patient
- fixed subject lists
- the fixed lists, which reproduce Table 2

Two checks on the real data (image-paired test set, 1,241 stays):

- MedFuse's released EHR checkpoint (``checkpoints/mortality/uni_ehr_all``),
evaluated frozen: test AUROC 0.833 (95% CI 0.802-0.860) with 1 h +
``ph_ts1.0``, against 0.735 with 1 h + a normalizer fitted on the train split
and 0.719 with 2 h + fitted; MedFuse reports 0.825 (0.793-0.852). So a model
that uses MedFuse's encoders frozen needs the code's settings. MedFuse split
with the same subject lists, so its training data holds none of these test
patients.
- MedMod's EHR LSTM trained from scratch (5 seeds): 1 h vs 2 h with the same
normalizer makes no difference (Δ AUROC +0.000 ± 0.006); ``ph_ts1.0`` scores
0.009 higher than a fitted normalizer (0.816 vs 0.807; paper Table 3: 0.829).
2 changes: 2 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,8 @@ Older examples that no longer run, or that duplicated a maintained one, are in
| `patient_linkage_mimic3_medlink.py` | MedLink record linkage (needs `pytrec_eval`) |
| `physionet_deid_ner_transformer_deid.py` | Transformer de-identification (PhysioNet, credentialed) |
| `mimic4_mortality_medfuse.py` | MedFuse ablation (synthetic data) |
| `mimic4_medmod_ihm_early_fusion.py` | MedMod Early Fusion for in-hospital mortality |
| `mimic4_medmod_convirt.py` | MedMod ConVIRT pretraining + linear probe for in-hospital mortality |
| `mimic4_decompensation_daft.py` | DAFT on MedMod decompensation and mortality, with ablations (synthetic data by default) |
| `physionet2012_mortality_stepwise_embedding.py` | Step-wise embedding ablation (backbone, raw, direct, grouped and grouped_shared encoders) on PhysioNet 2012 mortality (synthetic data with `--synthetic`) |
| `support_survival_survival_mdn.py` (with `survival_mdn_data.py`, `survival_mdn_metrics.py`, results in `survival_mdn_results/`) | Survival mixture density network on SUPPORT |
Expand Down
125 changes: 125 additions & 0 deletions examples/medmod_runners/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
# MedMod runner scripts

These scripts produced the real-data results in
[`../mimic4_medmod_ihm_results.md`](../mimic4_medmod_ihm_results.md). They
train the same models with the same settings as the example scripts
`mimic4_medmod_ihm_early_fusion.py` and `mimic4_medmod_convirt.py`. They also
compute bootstrap confidence intervals, write a JSON report for every run and
save checkpoints, so that a run continues after a disconnect. The Colab
notebook [`../mimic4_medmod_ihm_colab_runs.ipynb`](../mimic4_medmod_ihm_colab_runs.ipynb)
runs all of them.

The runs need credentialed PhysioNet access to MIMIC-IV v1.0 and
MIMIC-CXR-JPG 2.0.0. Keep the data out of the code folder and out of git. The
scripts print only aggregates, such as counts, losses and scores.

| Script | What it does |
|---|---|
| `slim_events.py` | Writes the slim copy of the MIMIC-IV event tables (once) |
| `samples.py` | Builds and checks an in-hospital mortality sample set |
| `early_fusion_run.py` | Trains and tests Early Fusion |
| `pretrain_samples.py` | Builds the ConVIRT pretraining samples |
| `convirt_pretrain.py` | Pretrains ConVIRT |
| `convirt_probe.py` | Trains and tests the linear probe on a pretraining checkpoint |
| `colab_bundle.py` | Zips the code and data for Google Colab |
| `provenance.py` | Records the code version in every report and checkpoint |

Run each script from the repository root. This shows its options:
`python -m examples.medmod_runners.<script> --help`

## Data layout

Every script takes `--data-root` and finds the parts below in it. `samples.py`
can also take each part separately (`--ehr-root`, `--cxr-root`, `--cache-dir`,
`--image-dir`).

```
<data-root>/
mimiciv/1.0/ MIMIC-IV v1.0 (7 tables used)
core/ patients admissions hosp/ labevents diagnoses_icd d_icd_diagnoses
icu/ icustays chartevents (all .csv.gz)
mimiciv_medmod_slim/1.0/ written by slim_events.py, see below
mimic-cxr-jpg/2.0.0/
mimic-cxr-2.0.0-metadata.csv.gz (exactly this name, PyHealth reads it)
mimic-cxr-2.0.0-chexpert.csv.gz
files/p1x/p<subject>/s<study>/<dicom>.jpg original images
resized/<dicom>.jpg resized images, see below
pyhealth_cache/ PyHealth's processed copy (safe to delete, it rebuilds)
medmod_extracted/ MedMod's own extraction, for ConVIRT pretraining
cohorts/pretrain_cohort.csv the image of each pretraining stay, see below
```

PyHealth writes `mimic-cxr-2.0.0-metadata-pyhealth.csv` into the CXR folder,
so that folder must be writable.

## Preparing the data

**EHR tables.** The scripts read `mimiciv_medmod_slim/1.0`, a copy of MIMIC-IV
v1.0 with only the event rows MedMod can use. PyHealth sorts the whole event
table on disk when it builds its cache, and with the full chartevents table
this ran out of space with 25 to 30 GB free. Write the copy once (about 5
minutes):

```bash
python -m examples.medmod_runners.slim_events --data-root <data-root>
```

It keeps a chartevents or labevents row only if its item id is one of MedMod's
114 mapped item ids, its `hadm_id` and `value` are not empty, and its
`charttime` lies between 1 hour before and 49 hours after the start of an ICU
stay of the same patient. MedMod never uses the other rows, so the samples are
the same as with the full tables. The other tables are linked, not copied, and
the original files stay unchanged.

**Resized images.** The scripts read images resized the way MedFuse does
(width 512). To write them:

```python
from pyhealth.datasets.medmod.resize_cxr import paths_from_metadata, resize_cxr

root = "<data-root>/mimic-cxr-jpg/2.0.0"
print(resize_cxr(paths_from_metadata(root), f"{root}/resized"))
```

**ConVIRT pretraining data.** `medmod_extracted/` is the output of MedMod's
own extraction scripts (`mimic4extract` in https://github.com/nyuad-cai/MedMod,
run unchanged, including its phenotyping task). Pretraining reads
`medmod_extracted/root/all_stays.csv` and `medmod_extracted/phenotyping/`.
Write `cohorts/pretrain_cohort.csv` with:

```python
from pyhealth.datasets.medmod.pretraining import pretraining_cohort

cohort = pretraining_cohort("<data-root>/medmod_extracted",
"<data-root>/mimic-cxr-jpg/2.0.0")
cohort.to_csv("<data-root>/cohorts/pretrain_cohort.csv", index=False)
```

**MedSigLIP embeddings** (extension). `python -m pyhealth.datasets.medmod.medsiglip
--images <data-root>/mimic-cxr-jpg/2.0.0/resized --out medsiglip_448.npz`
writes them. Pass the file to the runners with `--embeddings`.

**MedFuse checkpoints** (Early Fusion). Download `uni_ehr_all` and
`cxr_rad_full` from https://github.com/nyuad-cai/MedFuse (Git LFS) and pass
them with `--ehr-weights` and `--cxr-weights`.

MedMod's item map and split lists are downloaded from MedMod's GitHub on first
use (`pyhealth.datasets.medmod.downloads`).

## Running

On Google Colab, follow the notebook
[`../mimic4_medmod_ihm_colab_runs.ipynb`](../mimic4_medmod_ihm_colab_runs.ipynb).
Its intro says which files to upload, and its "Jobs" cell has the command of
every run. On your own machine, the same commands work with
`--data-root <data-root>`:

1. `slim_events` writes the slim copy of the event tables (once).
2. `samples` builds and checks the sample set (about 15 minutes the first
time, then cached).
3. `early_fusion_run` trains Early Fusion, once per seed.
4. `convirt_pretrain` pretrains ConVIRT, once per seed (about 6 hours on a
GPU for the ResNet-34).
5. `convirt_probe` trains the probe on a pretraining checkpoint. The notebook
chooses the checkpoint by validation AUROC with quick `--no-augment` probes
on every 10th epoch.
13 changes: 13 additions & 0 deletions examples/medmod_runners/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
"""Scripts that produced the real-data results of the MedMod examples.

These are the training and evaluation scripts we ran on Google Colab, as shown
in ``examples/mimic4_medmod_ihm_colab_runs.ipynb``. They train the same models
with the same settings as the example scripts in ``examples/``. They add
bootstrap confidence intervals and a JSON report per run that records the code
version (the git commit, or the time the Colab code zip was made) and the
SHA-256 of the script files. Each runner saves checkpoints, the Early Fusion
and probe runners every 10 epochs and the ConVIRT pretraining runner after
every epoch. Running the same command again continues an interrupted run. The
results page
``examples/mimic4_medmod_ihm_results.md`` explains the settings and deviations.
"""
Loading
Loading