Skip to content
Merged
Show file tree
Hide file tree
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 Nov 5, 2026
f50e698
Add MEDS ICU admission, readmission and prolonged stay tasks
jhnwu3 Nov 5, 2026
91111c1
Merge feat/meds-outcome-tasks into feat/ethos-model
jhnwu3 Nov 5, 2026
c9757df
Add ETHOS generative timeline model with zero-shot risk estimation
jhnwu3 Nov 5, 2026
0eb6415
Keep EthosProcessor's vocabulary local instead of importing ConceptVocab
jhnwu3 Nov 10, 2026
101976b
Merge remote-tracking branch 'origin/master' into feat/ethos-tokenizer
jhnwu3 Nov 10, 2026
15aa1df
Drop quoted return annotation in EthosVocab
jhnwu3 Nov 10, 2026
02619cb
Keep the MEDS codes local and return input rows from the window helpers
jhnwu3 Nov 10, 2026
3de46e1
Merge remote-tracking branch 'origin/master' into feat/meds-outcome-t…
jhnwu3 Nov 10, 2026
7cc5214
Merge branch 'feat/ethos-tokenizer' into feat/ethos-model
jhnwu3 Nov 10, 2026
4e26f00
Merge branch 'feat/meds-outcome-tasks' into feat/ethos-model
jhnwu3 Nov 10, 2026
15b15af
Port ETHOS to the LabelProcessor API and keep its MEDS codes local
jhnwu3 Nov 10, 2026
5f3a65f
Say how HospitalReadmissionMEDS differs from ReadmissionPredictionMIMIC4
jhnwu3 Nov 10, 2026
1758129
Merge branch 'feat/meds-outcome-tasks' into feat/ethos-model
jhnwu3 Nov 10, 2026
79af6ea
Test EthosTimelineMEDS and EthosOutcomeMEDS through MEDSDataset.set_task
jhnwu3 Nov 10, 2026
95b20c3
Merge remote-tracking branch 'upstream/master' into upd-1397
solarsys Nov 14, 2026
7d24d29
ETHOS.estimate_risk: fail loudly on processors other than the model's
solarsys Nov 14, 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/models.rst
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,7 @@ API Reference
models/pyhealth.models.Deepr
models/pyhealth.models.EHRMamba
models/pyhealth.models.EHRMambaCEHR
models/pyhealth.models.ETHOS
models/pyhealth.models.JambaEHR
models/pyhealth.models.ContraWR
models/pyhealth.models.SparcNet
Expand Down
13 changes: 13 additions & 0 deletions docs/api/models/pyhealth.models.ETHOS.rst
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:
2 changes: 2 additions & 0 deletions docs/api/processors.rst
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ MLP and others) train on a field of that type.
- ``NestedMultiHotProcessor``: For nested categorical sequences as per-visit multi-hot vectors (e.g., generative EHR models)
- ``NestedFloatsProcessor``: For nested numerical sequences with optional forward-fill
- :doc:`EthosProcessor <processors/pyhealth.processors.EthosProcessor>`: Tokenizes MEDS patient timelines the way ETHOS does, with quantile tokens for numeric values and time-interval tokens (``"ethos"``, fitted on the training split)
- :doc:`EthosContextProcessor <processors/pyhealth.processors.EthosContextProcessor>`: Encodes a patient's demographics and birth date as the static context of an ETHOS timeline (``"ethos_context"``)

**Label Processors** (subclasses of ``LabelProcessor``, which also define the loss, activation, output size and metrics of the label):

Expand Down Expand Up @@ -607,6 +608,7 @@ API Reference
processors/pyhealth.processors.TextProcessor
processors/pyhealth.processors.TupleTimeTextProcessor
processors/pyhealth.processors.EthosProcessor
processors/pyhealth.processors.EthosContextProcessor
processors/pyhealth.processors.AudioProcessor
processors/pyhealth.processors.SignalProcessor
processors/pyhealth.processors.TimeseriesProcessor
Expand Down
11 changes: 11 additions & 0 deletions docs/api/processors/pyhealth.processors.EthosContextProcessor.rst
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:
2 changes: 2 additions & 0 deletions docs/api/tasks.rst
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,8 @@ Available Tasks
ICU Admission (MEDS) <tasks/pyhealth.tasks.ICUAdmissionMEDS>
Hospital Readmission (MEDS) <tasks/pyhealth.tasks.HospitalReadmissionMEDS>
Prolonged Length of Stay (MEDS) <tasks/pyhealth.tasks.ProlongedLengthOfStayMEDS>
ETHOS Timelines (MEDS) <tasks/pyhealth.tasks.EthosTimelineMEDS>
ETHOS Zero-Shot Outcomes (MEDS) <tasks/pyhealth.tasks.EthosOutcomeMEDS>
MIMIC-III ICD-9 Coding <tasks/pyhealth.tasks.MIMIC3ICD9Coding>
BMD-HS Disease Classification <tasks/pyhealth.tasks.bmd_hs_disease_classification>
Cardiology Detection <tasks/pyhealth.tasks.cardiology_detect>
Expand Down
12 changes: 12 additions & 0 deletions docs/api/tasks/pyhealth.tasks.EthosOutcomeMEDS.rst
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:
7 changes: 7 additions & 0 deletions docs/api/tasks/pyhealth.tasks.EthosTimelineMEDS.rst
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:
221 changes: 221 additions & 0 deletions examples/ethos_zero_shot.py
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.

Copy link
Copy Markdown

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".


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()
1 change: 1 addition & 0 deletions pyhealth/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@
)
from .apricotm import APRICOTM as APRICOTM
from .selective_ssm import SelectiveSSM as SelectiveSSM
from .ethos import ETHOS as ETHOS
from .heartlang import (
HeartLang as HeartLang,
HeartLangBackbone as HeartLangBackbone,
Expand Down
Loading
Loading