Repository navigation
Add ETHOS generative timeline model with zero-shot risk estimation #1397
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
992886f
Add EthosProcessor, the ETHOS timeline tokenizer for MEDS
jhnwu3 f50e698
Add MEDS ICU admission, readmission and prolonged stay tasks
jhnwu3 91111c1
Merge feat/meds-outcome-tasks into feat/ethos-model
jhnwu3 c9757df
Add ETHOS generative timeline model with zero-shot risk estimation
jhnwu3 0eb6415
Keep EthosProcessor's vocabulary local instead of importing ConceptVocab
jhnwu3 101976b
Merge remote-tracking branch 'origin/master' into feat/ethos-tokenizer
jhnwu3 15aa1df
Drop quoted return annotation in EthosVocab
jhnwu3 02619cb
Keep the MEDS codes local and return input rows from the window helpers
jhnwu3 3de46e1
Merge remote-tracking branch 'origin/master' into feat/meds-outcome-t…
jhnwu3 7cc5214
Merge branch 'feat/ethos-tokenizer' into feat/ethos-model
jhnwu3 4e26f00
Merge branch 'feat/meds-outcome-tasks' into feat/ethos-model
jhnwu3 15b15af
Port ETHOS to the LabelProcessor API and keep its MEDS codes local
jhnwu3 5f3a65f
Say how HospitalReadmissionMEDS differs from ReadmissionPredictionMIMIC4
jhnwu3 1758129
Merge branch 'feat/meds-outcome-tasks' into feat/ethos-model
jhnwu3 79af6ea
Test EthosTimelineMEDS and EthosOutcomeMEDS through MEDSDataset.set_task
jhnwu3 95b20c3
Merge remote-tracking branch 'upstream/master' into upd-1397
solarsys 7d24d29
ETHOS.estimate_risk: fail loudly on processors other than the model's
solarsys File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| pyhealth.models.ETHOS | ||
| =================================== | ||
|
|
||
| ETHOS: a GPT-style generative model of tokenized patient timelines, with | ||
| zero-shot risk estimation by sampling future timelines | ||
| (`Renc et al., 2025 <https://arxiv.org/abs/2502.06124>`_). Train it on | ||
| :class:`~pyhealth.tasks.EthosTimelineMEDS`, then estimate risks on | ||
| :class:`~pyhealth.tasks.EthosOutcomeMEDS`. | ||
|
|
||
| .. autoclass:: pyhealth.models.ETHOS | ||
| :members: | ||
| :undoc-members: | ||
| :show-inheritance: |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
11 changes: 11 additions & 0 deletions
11
docs/api/processors/pyhealth.processors.EthosContextProcessor.rst
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| pyhealth.processors.EthosContextProcessor | ||
| ========================================= | ||
|
|
||
| Encodes the static patient context that opens an ETHOS timeline: one token per | ||
| demographic attribute, plus the patient's age at the start of the timeline. | ||
| Registered as ``"ethos_context"``. | ||
|
|
||
| .. autoclass:: pyhealth.processors.EthosContextProcessor | ||
| :members: | ||
| :undoc-members: | ||
| :show-inheritance: |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| pyhealth.tasks.EthosOutcomeMEDS | ||
| =============================== | ||
|
|
||
| .. autoclass:: pyhealth.tasks.ethos_tasks.EthosOutcomeMEDS | ||
| :members: | ||
| :undoc-members: | ||
| :show-inheritance: | ||
|
|
||
| .. autoclass:: pyhealth.tasks.ethos_tasks.EthosRolloutRule | ||
| :members: | ||
| :undoc-members: | ||
| :show-inheritance: |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| pyhealth.tasks.EthosTimelineMEDS | ||
| ================================ | ||
|
|
||
| .. autoclass:: pyhealth.tasks.ethos_tasks.EthosTimelineMEDS | ||
| :members: | ||
| :undoc-members: | ||
| :show-inheritance: |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,221 @@ | ||
| """Train a tiny ETHOS and estimate risks by sampling future timelines. | ||
|
|
||
| Smoke test on synthetic data: this writes a small MEDS directory to a temporary | ||
| folder, so it needs no credentials and no download. The numbers mean nothing | ||
| clinically, and nothing here reproduces a result from the paper. Sixty made-up | ||
| patients and a tiny model cannot, whatever the AUROCs below happen to be. | ||
|
|
||
| For reference, Renc et al. (arXiv:2502.06124, Table S1) report these test | ||
| AUROCs for the full model, with 100 rollouts per sample, on all of MIMIC-IV 2.2: | ||
| ICU admission 0.932 and prolonged stay 0.853. Those runs also use ETHOS's MIMIC | ||
| preprocessing (ICD and ATC mapping, the top-200 lab filter, blood pressure and | ||
| BMI rewrites), which PyHealth does not have, so vocabularies will not match the | ||
| paper's on MIMIC-IV. | ||
|
|
||
| To use a real MEDS dataset, such as MIMIC-IV after MEDS extraction (credentialed | ||
| access required), pass ``--root``, and raise the sizes to the paper's: | ||
|
|
||
| python examples/ethos_zero_shot.py --root /path/to/meds \\ | ||
| --n-layer 6 --n-head 12 --n-embd 768 --n-positions 2048 \\ | ||
| --dropout 0.3 --lr 6e-4 --epochs 20 --rollouts 100 | ||
|
|
||
| Usage: | ||
| python examples/ethos_zero_shot.py | ||
| """ | ||
|
|
||
| import argparse | ||
| import random | ||
| import tempfile | ||
| from datetime import datetime, timedelta | ||
| from pathlib import Path | ||
|
|
||
| import polars as pl | ||
| import torch | ||
| from sklearn.metrics import roc_auc_score | ||
|
|
||
| import pyhealth.datasets.configs as meds_configs | ||
| from pyhealth.datasets import MEDSDataset, PatientSplit, get_dataloader | ||
| from pyhealth.models import ETHOS | ||
| from pyhealth.tasks import ( | ||
| EthosOutcomeMEDS, | ||
| EthosTimelineMEDS, | ||
| HospitalReadmissionMEDS, | ||
| ICUAdmissionMEDS, | ||
| ProlongedLengthOfStayMEDS, | ||
| ) | ||
| from pyhealth.trainer import Trainer | ||
|
|
||
| ADMIT = "HOSPITAL_ADMISSION//EW EMER.//ER" | ||
| SICK_LAB = "LAB//50813//mmol/L" | ||
| ROUTINE_LAB = "LAB//51221//%" | ||
|
|
||
|
|
||
| def write_synthetic_meds(root: Path, n_subjects: int = 60, seed: int = 0) -> None: | ||
| """Writes synthetic stays where age and past labs foreshadow the outcome. | ||
|
|
||
| Args: | ||
| root: Output directory. | ||
| n_subjects: Number of synthetic subjects. | ||
| seed: Random seed. | ||
| """ | ||
| rng = random.Random(seed) | ||
| rows = [] | ||
| for subject in range(1, n_subjects + 1): | ||
| now = datetime.fromisoformat("2024-01-01T08:00:00") # MEDS times are naive | ||
| now += timedelta(days=rng.randint(0, 60)) | ||
| birth = datetime.fromisoformat(f"{rng.randint(1940, 2000)}-01-01") | ||
| frail = birth.year < 1970 # Stays of older patients go worse. | ||
| rows.append((subject, None, f"GENDER//{rng.choice('FM')}", None, None)) | ||
| rows.append((subject, birth, "MEDS_BIRTH", None, None)) | ||
| for stay in range(rng.randint(1, 3)): | ||
| hadm = subject * 100 + stay | ||
| sick = rng.random() < (0.9 if frail else 0.1) | ||
| length = timedelta(days=rng.uniform(11, 16) if sick else rng.uniform(1, 6)) | ||
| rows.append((subject, now, ADMIT, hadm, None)) | ||
| for hours in (1, 2, 6, 24): | ||
| value = rng.gauss(8.0 if sick else 1.5, 0.5) | ||
| rows.append( | ||
| (subject, now + timedelta(hours=hours), SICK_LAB, hadm, value) | ||
| ) | ||
| value = rng.gauss(30.0, 3.0) | ||
| rows.append( | ||
| (subject, now + timedelta(hours=hours), ROUTINE_LAB, hadm, value) | ||
| ) | ||
| if sick: | ||
| icu = now + timedelta(hours=30) | ||
| rows.append((subject, icu, "ICU_ADMISSION//MICU", hadm, None)) | ||
| rows.append( | ||
| (subject, icu + timedelta(hours=40), "ICU_DISCHARGE//MICU", hadm, None) | ||
| ) | ||
| discharge = now + length | ||
| rows.append((subject, discharge, "HOSPITAL_DISCHARGE//HOME", hadm, None)) | ||
| now = discharge + timedelta(days=rng.choice([10, 20, 90])) | ||
|
|
||
| (root / "data").mkdir(parents=True) | ||
| pl.DataFrame( | ||
| { | ||
| "subject_id": pl.Series([r[0] for r in rows], dtype=pl.Int64), | ||
| "time": pl.Series([r[1] for r in rows], dtype=pl.Datetime("us")), | ||
| "code": pl.Series([r[2] for r in rows], dtype=pl.String), | ||
| "hadm_id": pl.Series([r[3] for r in rows], dtype=pl.Int64), | ||
| "numeric_value": pl.Series([r[4] for r in rows], dtype=pl.Float32), | ||
| } | ||
| ).write_parquet(root / "data" / "0.parquet") | ||
|
|
||
|
|
||
| def evaluate(dataset, model, test_patients, task, args) -> None: | ||
| """Prints zero-shot risks for one outcome on the test patients. | ||
|
|
||
| Args: | ||
| dataset: The MEDS dataset. | ||
| model: The trained model. | ||
| test_patients: Patient ids held out of training. | ||
| task: An :class:`EthosOutcomeMEDS`. | ||
| args: Command-line arguments. | ||
| """ | ||
| samples = dataset.set_task( | ||
| task, num_workers=1, input_processors=model.dataset.input_processors | ||
| ) | ||
| held_out = [ | ||
| index | ||
| for patient, indices in samples.patient_to_index.items() | ||
| if patient in test_patients | ||
| for index in indices | ||
| ] | ||
| label_key = next(iter(task.output_schema)) | ||
| risk = model.estimate_risk( | ||
| get_dataloader(samples.subset(held_out), batch_size=8), | ||
| task.rule, | ||
| num_rollouts=args.rollouts, | ||
| max_new_tokens=args.max_new_tokens, | ||
| label_key=label_key, | ||
| seed=0, | ||
| ) | ||
| scored = ~risk["y_prob"].isnan() | ||
| y_true, y_prob = risk["y_true"][scored], risk["y_prob"][scored] | ||
| kept = risk["num_kept"].float().mean().item() | ||
| print( | ||
| f"{task.task_name}: samples={len(held_out)} scored={int(scored.sum())} " | ||
| f"mean rollouts kept={kept:.1f}/{args.rollouts} " | ||
| f"true rate={y_true.mean().item():.3f} mean risk={y_prob.mean().item():.3f}" | ||
| ) | ||
| if len(set(y_true.tolist())) == 2: | ||
| auroc = roc_auc_score(y_true.numpy(), y_prob.numpy()) | ||
| print(f" AUROC on these few samples (smoke test only): {auroc:.3f}") | ||
|
|
||
|
|
||
| def main() -> None: | ||
| parser = argparse.ArgumentParser(description=__doc__) | ||
| parser.add_argument("--root", default=None, help="MEDS root; omit for synthetic.") | ||
| parser.add_argument("--n-layer", type=int, default=2) | ||
| parser.add_argument("--n-head", type=int, default=2) | ||
| parser.add_argument("--n-embd", type=int, default=32) | ||
| parser.add_argument("--n-positions", type=int, default=256) | ||
| parser.add_argument("--dropout", type=float, default=0.0) | ||
| parser.add_argument("--epochs", type=int, default=60) | ||
| parser.add_argument("--lr", type=float, default=3e-3) | ||
| parser.add_argument("--rollouts", type=int, default=20) | ||
| parser.add_argument("--max-new-tokens", type=int, default=256) | ||
| args = parser.parse_args() | ||
|
|
||
| config = Path(meds_configs.__file__).parent / "meds_with_hadm.yaml" | ||
| with tempfile.TemporaryDirectory() as tmp: | ||
| tmp_path = Path(tmp) | ||
| if args.root is None: | ||
| print("Using synthetic MEDS data: a smoke test, not a result.") | ||
| root = tmp_path / "synthetic_meds" | ||
| write_synthetic_meds(root) | ||
| else: | ||
| root = Path(args.root) | ||
|
|
||
| dataset = MEDSDataset( | ||
| root=str(root), | ||
| config_path=str(config), | ||
| cache_dir=tmp_path / "cache", | ||
| num_workers=1, | ||
| ) | ||
| # The split fits the vocabulary and quantile breaks on training patients. | ||
| train, test = dataset.set_task( | ||
| EthosTimelineMEDS(), | ||
| split=PatientSplit(ratios=(0.7, 0.3), seed=0), | ||
| num_workers=1, | ||
| ) | ||
| print("training and held-out patients:", len(train), len(test)) | ||
|
|
||
| model = ETHOS( | ||
| train, | ||
| n_layer=args.n_layer, | ||
| n_head=args.n_head, | ||
| n_embd=args.n_embd, | ||
| n_positions=args.n_positions, | ||
| dropout=args.dropout, | ||
| ) | ||
| trainer = Trainer(model=model, enable_logging=False) | ||
| trainer.train( | ||
| train_dataloader=get_dataloader(train, batch_size=8, shuffle=True), | ||
| epochs=args.epochs, | ||
| optimizer_class=torch.optim.AdamW, | ||
| optimizer_params={"lr": args.lr, "betas": (0.9, 0.95)}, | ||
| weight_decay=0.1, | ||
| max_grad_norm=1.0, | ||
| ) | ||
| held_out = trainer.evaluate(get_dataloader(test, batch_size=8)) | ||
| print("loss on held-out timelines:", held_out["loss"]) | ||
|
|
||
| checkpoint = str(tmp_path / "ethos.ckpt") | ||
| trainer.save_ckpt(checkpoint) | ||
| trainer.load_ckpt(checkpoint) | ||
| print("checkpoint reloaded") | ||
|
|
||
| test_patients = set(test.patient_to_index) | ||
| tasks = [ | ||
| EthosOutcomeMEDS(ICUAdmissionMEDS, death_as_positive=False), | ||
| EthosOutcomeMEDS(ProlongedLengthOfStayMEDS), | ||
| EthosOutcomeMEDS(HospitalReadmissionMEDS), | ||
| ] | ||
| for task in tasks: | ||
| evaluate(dataset, model, test_patients, task, args) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[low] Docstring refers to AUROCs that the file never shows
"whatever the AUROCs below happen to be" points at nothing in the file; the AUROCs are only printed when the script runs. Rephrase, for example "whatever AUROC the script prints".