diff --git a/docs/api/models.rst b/docs/api/models.rst index 918b083959..71899fb386 100644 --- a/docs/api/models.rst +++ b/docs/api/models.rst @@ -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 diff --git a/docs/api/models/pyhealth.models.ETHOS.rst b/docs/api/models/pyhealth.models.ETHOS.rst new file mode 100644 index 0000000000..b041a2327e --- /dev/null +++ b/docs/api/models/pyhealth.models.ETHOS.rst @@ -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 `_). Train it on +:class:`~pyhealth.tasks.EthosTimelineMEDS`, then estimate risks on +:class:`~pyhealth.tasks.EthosOutcomeMEDS`. + +.. autoclass:: pyhealth.models.ETHOS + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/processors.rst b/docs/api/processors.rst index c7e7f7c38a..7d422e7e62 100644 --- a/docs/api/processors.rst +++ b/docs/api/processors.rst @@ -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 `: 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 `: 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): @@ -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 diff --git a/docs/api/processors/pyhealth.processors.EthosContextProcessor.rst b/docs/api/processors/pyhealth.processors.EthosContextProcessor.rst new file mode 100644 index 0000000000..c84b4fc87b --- /dev/null +++ b/docs/api/processors/pyhealth.processors.EthosContextProcessor.rst @@ -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: diff --git a/docs/api/tasks.rst b/docs/api/tasks.rst index f945be7ff4..b49f37dd77 100644 --- a/docs/api/tasks.rst +++ b/docs/api/tasks.rst @@ -216,6 +216,8 @@ Available Tasks ICU Admission (MEDS) Hospital Readmission (MEDS) Prolonged Length of Stay (MEDS) + ETHOS Timelines (MEDS) + ETHOS Zero-Shot Outcomes (MEDS) MIMIC-III ICD-9 Coding BMD-HS Disease Classification Cardiology Detection diff --git a/docs/api/tasks/pyhealth.tasks.EthosOutcomeMEDS.rst b/docs/api/tasks/pyhealth.tasks.EthosOutcomeMEDS.rst new file mode 100644 index 0000000000..edeefb1a9f --- /dev/null +++ b/docs/api/tasks/pyhealth.tasks.EthosOutcomeMEDS.rst @@ -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: diff --git a/docs/api/tasks/pyhealth.tasks.EthosTimelineMEDS.rst b/docs/api/tasks/pyhealth.tasks.EthosTimelineMEDS.rst new file mode 100644 index 0000000000..487671f76d --- /dev/null +++ b/docs/api/tasks/pyhealth.tasks.EthosTimelineMEDS.rst @@ -0,0 +1,7 @@ +pyhealth.tasks.EthosTimelineMEDS +================================ + +.. autoclass:: pyhealth.tasks.ethos_tasks.EthosTimelineMEDS + :members: + :undoc-members: + :show-inheritance: diff --git a/examples/ethos_zero_shot.py b/examples/ethos_zero_shot.py new file mode 100644 index 0000000000..432105e949 --- /dev/null +++ b/examples/ethos_zero_shot.py @@ -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() diff --git a/pyhealth/models/__init__.py b/pyhealth/models/__init__.py index ead0015515..028fa71ec1 100644 --- a/pyhealth/models/__init__.py +++ b/pyhealth/models/__init__.py @@ -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, diff --git a/pyhealth/models/ethos.py b/pyhealth/models/ethos.py new file mode 100644 index 0000000000..91998db44d --- /dev/null +++ b/pyhealth/models/ethos.py @@ -0,0 +1,629 @@ +"""ETHOS: a generative model of patient timelines, with zero-shot risk estimates. + +ETHOS is a GPT-style decoder trained to predict the next token of a tokenized +patient timeline. It needs no labels: to estimate a risk it samples many future +timelines from the prediction time and counts how often the outcome happens. + +Paper: + Renc et al. Foundation Model of Electronic Medical Records for Adaptive + Risk Estimation. https://arxiv.org/abs/2502.06124 + +Adapted from ethos-ares (commit 2d54383), ``src/ethos/model.py`` and +``src/ethos/inference/{inference,utils}.py``: +https://github.com/ipolharvard/ethos-ares + +MIT License. Copyright (c) 2024 Paweł Renc. +""" + +from __future__ import annotations + +import math +from collections.abc import Iterable +from typing import Any + +import torch +import torch.nn.functional as F +from torch import nn + +from pyhealth.datasets import SampleDataset +from pyhealth.processors import EthosContextProcessor, EthosProcessor +from pyhealth.processors.ethos_processor import TIMELINE_END_TOKEN +from pyhealth.tasks.ethos_tasks import ( + INVALID_TOKEN, + STOP_TOKEN, + TIME_LIMIT, + TOKEN_LIMIT, + EthosRolloutRule, +) + +from .base_model import BaseModel + +HOURS_PER_YEAR = 24 * 365.25 +IGNORE_INDEX = -100 + + +class _CausalSelfAttention(nn.Module): + """Multi-head causal self-attention without bias terms.""" + + def __init__(self, n_embd: int, n_head: int, dropout: float) -> None: + super().__init__() + self.c_attn = nn.Linear(n_embd, 3 * n_embd, bias=False) + self.c_proj = nn.Linear(n_embd, n_embd, bias=False) + self.resid_dropout = nn.Dropout(dropout) + self.n_head = n_head + self.dropout = dropout + + def forward(self, x: torch.Tensor) -> torch.Tensor: + batch, length, width = x.size() + q, k, v = ( + part.view(batch, length, self.n_head, width // self.n_head).transpose(1, 2) + for part in self.c_attn(x).split(width, dim=2) + ) + y = F.scaled_dot_product_attention( + q, + k, + v, + dropout_p=self.dropout if self.training else 0.0, + is_causal=True, + ) + y = y.transpose(1, 2).contiguous().view(batch, length, width) + return self.resid_dropout(self.c_proj(y)) + + +class _MLP(nn.Module): + """The feed-forward part of a transformer block.""" + + def __init__(self, n_embd: int, dropout: float) -> None: + super().__init__() + self.c_fc = nn.Linear(n_embd, 4 * n_embd, bias=False) + self.activation = nn.GELU() + self.c_proj = nn.Linear(4 * n_embd, n_embd, bias=False) + self.dropout = nn.Dropout(dropout) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.dropout(self.c_proj(self.activation(self.c_fc(x)))) + + +class _Block(nn.Module): + """A pre-norm transformer block.""" + + def __init__(self, n_embd: int, n_head: int, dropout: float) -> None: + super().__init__() + self.ln_1 = nn.LayerNorm(n_embd, bias=False) + self.attn = _CausalSelfAttention(n_embd, n_head, dropout) + self.ln_2 = nn.LayerNorm(n_embd, bias=False) + self.mlp = _MLP(n_embd, dropout) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = x + self.attn(self.ln_1(x)) + return x + self.mlp(self.ln_2(x)) + + +def _age_quantiles( + age_years: torch.Tensor, num_quantiles: int +) -> tuple[torch.Tensor, torch.Tensor]: + """Writes ages as two digits in base ``num_quantiles``, as ETHOS does. + + With 10 quantiles, age 46 is ``(4, 6)``: the tokens ``Q5`` and ``Q7``. + + Args: + age_years: Ages in years. + num_quantiles: Number of quantile tokens. + + Returns: + Both digits, from 0, as ``long`` tensors. ``nan`` gives ``-1``. + """ + scaled = (age_years * num_quantiles**2 / 100).clamp(0, num_quantiles**2 - 1) + high = torch.div(scaled, num_quantiles, rounding_mode="floor") + low = torch.round(scaled - high * num_quantiles) + carry = low == num_quantiles + high, low = high + carry, low.masked_fill(carry, 0) + missing = age_years.isnan() + return ( + high.nan_to_num(0).long().masked_fill(missing, -1), + low.nan_to_num(0).long().masked_fill(missing, -1), + ) + + +class ETHOS(BaseModel): + """ETHOS generative timeline model with zero-shot risk estimation. + + :meth:`forward` is the next-token loss, so the model trains with + :class:`~pyhealth.trainer.Trainer` on + :class:`~pyhealth.tasks.EthosTimelineMEDS`, with no labels. Its dataset has + no label processor, so ``mode`` is ``None`` and there is no ``y_prob``. Risks come from :meth:`estimate_risk`, + which samples timelines forward from each sample of + :class:`~pyhealth.tasks.EthosOutcomeMEDS`. + + The input is the static context followed by the timeline, as in ETHOS. A + timeline that does not fit in ``n_positions`` gives a random window in + training and its last tokens otherwise, and the age tokens state the age + where that window starts. Demographics keep their value at the start of the + whole timeline. + + The defaults are the paper's final model. Layer names match ``ethos-ares``. + Reload a checkpoint only with the fitted processors it was trained on: the + token ids mean nothing without them. + + Args: + dataset: A dataset with an ``"ethos"`` field named ``timeline`` and an + ``"ethos_context"`` field named ``context``. + n_layer: Number of transformer blocks. + n_head: Number of attention heads. + n_embd: Embedding size. + n_positions: Context size, including the static context. + dropout: Dropout rate. + + Raises: + ValueError: If ``dataset`` lacks those fields or has a label, or the + sizes do not fit. + + Examples: + >>> from datetime import datetime, timedelta + >>> from pyhealth.datasets import create_sample_dataset, get_dataloader + >>> from pyhealth.models import ETHOS + >>> from pyhealth.tasks import EthosRolloutRule + >>> start = datetime(2024, 1, 1) + >>> codes = ["HOSPITAL_ADMISSION//ER", "LAB//A", "MEDS_DEATH"] + >>> samples = [ + ... { + ... "patient_id": f"p{i}", + ... "timeline": { + ... "time": [start + timedelta(hours=h) for h in (0, 1, 2)], + ... "code": codes, + ... "numeric_value": [None, 1.0 + i, None], + ... }, + ... "context": { + ... "time": [datetime(1980, 1, 1)], + ... "code": ["MEDS_BIRTH"], + ... "start": start, + ... }, + ... } + ... for i in range(3) + ... ] + >>> dataset = create_sample_dataset( + ... samples, + ... input_schema={"timeline": "ethos", "context": "ethos_context"}, + ... output_schema={}, + ... ) + >>> model = ETHOS(dataset, n_layer=1, n_head=2, n_embd=8, n_positions=32) + >>> batch = next(iter(get_dataloader(dataset, batch_size=3))) + >>> model(**batch)["loss"].backward() + >>> rule = EthosRolloutRule(("MEDS_DEATH", "TIMELINE_END"), ("MEDS_DEATH",)) + >>> risk = model.estimate_risk( + ... [batch], rule, num_rollouts=4, max_new_tokens=8, seed=0 + ... ) + >>> risk["y_prob"].shape + torch.Size([3]) + """ + + def __init__( + self, + dataset: SampleDataset, + n_layer: int = 6, + n_head: int = 12, + n_embd: int = 768, + n_positions: int = 2048, + dropout: float = 0.3, + ) -> None: + super().__init__(dataset=dataset) + if self.label_processors: + raise ValueError( + "ETHOS trains without labels, so its dataset needs an empty " + f"output_schema, not {sorted(self.label_processors)}; see " + "EthosTimelineMEDS. Score labels with estimate_risk." + ) + + processors = dataset.input_processors + timeline = processors.get("timeline") + context = processors.get("context") + has_fields = isinstance(timeline, EthosProcessor) and isinstance( + context, EthosContextProcessor + ) + if not has_fields: + raise ValueError( + "ETHOS needs a 'timeline' field of type 'ethos' and a 'context' " + "field of type 'ethos_context'; see EthosTimelineMEDS." + ) + if n_embd % n_head != 0: + raise ValueError(f"n_embd {n_embd} must divide by n_head {n_head}.") + if n_positions <= context.context_size: + raise ValueError( + f"n_positions {n_positions} leaves no room after the " + f"{context.context_size} context tokens." + ) + self.timeline_processor = timeline + self.context_processor = context + self.n_positions = n_positions + self.context_size = context.context_size + self.timeline_size = n_positions - context.context_size + + # Context tokens sit after the timeline's. The vocabulary is rounded up + # to a multiple of 64, as in ETHOS, so it can have ids that are not + # tokens; sampling one is an invalid token. + self.timeline_vocab_size = timeline.size() + self.vocab_size = math.ceil((timeline.size() + context.size()) / 64) * 64 + + self.transformer = nn.ModuleDict( + { + "wte": nn.Embedding(self.vocab_size, n_embd), + "wpe": nn.Embedding(n_positions, n_embd), + "drop": nn.Dropout(dropout), + "h": nn.ModuleList( + [_Block(n_embd, n_head, dropout) for _ in range(n_layer)] + ), + "ln_f": nn.LayerNorm(n_embd, bias=False), + } + ) + self.lm_head = nn.Linear(n_embd, self.vocab_size, bias=False) + self.transformer["wte"].weight = self.lm_head.weight + + self.apply(self._init_weights) + for name, parameter in self.named_parameters(): + if name.endswith("c_proj.weight"): + nn.init.normal_(parameter, mean=0.0, std=0.02 / math.sqrt(2 * n_layer)) + + vocab = timeline.vocab + self.register_buffer( + "quantile_ids", + torch.tensor( + [vocab[f"Q{k + 1}"] for k in range(timeline.num_quantiles)], + dtype=torch.long, + ), + persistent=False, + ) + # On the CPU in float64: not every device has that type. + self._interval_hours = torch.zeros(self.vocab_size, dtype=torch.float64) + for label, hours in timeline.interval_estimates.items(): + self._interval_hours[vocab[label]] = hours + self._is_token = torch.zeros(self.vocab_size, dtype=torch.bool) + self._is_token[: self.timeline_vocab_size] = True + self._is_token[[vocab.pad_id, vocab.unk_id]] = False + self._id_to_token = {i: token for token, i in vocab.token_to_id.items()} + + @staticmethod + def _init_weights(module: nn.Module) -> None: + if isinstance(module, (nn.Linear, nn.Embedding)): + nn.init.normal_(module.weight, mean=0.0, std=0.02) + + def _logits(self, ids: torch.Tensor) -> torch.Tensor: + """Returns next-token logits for token ids of shape ``[B, L]``.""" + positions = torch.arange(ids.size(1), device=ids.device) + x = self.transformer["wte"](ids) + self.transformer["wpe"](positions) + x = self.transformer["drop"](x) + for block in self.transformer["h"]: + x = block(x) + return self.lm_head(self.transformer["ln_f"](x)) + + def _context_ids(self, static: torch.Tensor, age: torch.Tensor) -> torch.Tensor: + """Builds model ids of the static context. + + Args: + static: Output tokens of the context processor, ``[B, C]``. + age: Age in years where the timeline window starts, ``[B]``. + + Returns: + Context ids in the model's vocabulary, ``[B, C]``. + """ + ids = static + self.timeline_vocab_size + unknown = self.timeline_processor.vocab.unk_id + position = self.context_processor.age_position + digits = _age_quantiles(age, self.timeline_processor.num_quantiles) + for offset, digit in enumerate(digits): + tokens = self.quantile_ids[digit.clamp(min=0)] + ids[:, position + offset] = tokens.masked_fill(digit < 0, unknown) + return ids + + def forward(self, **kwargs: Any) -> dict[str, torch.Tensor]: + """Computes the next-token loss. + + Args: + **kwargs: A batch, with ``timeline`` and ``context``. + + Returns: + A dictionary with ``loss``, ``logit`` of shape ``[B, L, V]`` and + ``y_true``, the target ids, with ``-100`` where there is none. + """ + time, tokens = kwargs["timeline"] + age, static = kwargs["context"] + tokens = tokens.to(self.device) + time = time.to(self.device, dtype=torch.float32) + static = static.to(self.device) + age = age.to(self.device, dtype=torch.float32).view(-1) + if tokens.size(1) == 0: + tokens = tokens.new_zeros(len(tokens), 1) + time = time.new_zeros(len(time), 1) + + pad_id = self.timeline_processor.vocab.pad_id + lengths = (tokens != pad_id).sum(dim=1) + spare = (lengths - self.timeline_size - 1).clamp(min=0) + if self.training: + starts = (torch.rand_like(spare, dtype=torch.float32) * (spare + 1)).long() + else: + starts = spare + width = min(tokens.size(1), self.timeline_size + 1) + indices = starts[:, None] + torch.arange(width, device=self.device) + window = tokens.gather(1, indices.clamp(max=tokens.size(1) - 1)) + window = window.masked_fill(indices >= lengths[:, None], pad_id) + + age = age + time.gather(1, starts[:, None]).squeeze(1) / HOURS_PER_YEAR + context = self._context_ids(static, age) + ids = torch.cat([context, window[:, :-1]], dim=1) + labels = torch.cat( + [ + torch.full_like(context, IGNORE_INDEX), + window[:, 1:].masked_fill(window[:, 1:] == pad_id, IGNORE_INDEX), + ], + dim=1, + ) + + logits = self._logits(ids) + if (labels != IGNORE_INDEX).any(): + loss = F.cross_entropy( + logits.view(-1, logits.size(-1)), + labels.view(-1), + ignore_index=IGNORE_INDEX, + ) + else: + # No timeline has a next token. A zero that keeps the graph, instead + # of the NaN mean of nothing. + loss = logits.sum() * 0.0 + return {"loss": loss, "logit": logits, "y_true": labels} + + def _token_mask(self, prefixes: Iterable[str]) -> torch.Tensor: + """Marks the vocabulary's tokens that start with one of ``prefixes``.""" + prefixes = tuple(prefixes) + mask = torch.zeros(self.vocab_size, dtype=torch.bool) + for index, token in self._id_to_token.items(): + mask[index] = token.startswith(prefixes) + return mask + + def _prompt( + self, + time: torch.Tensor, + tokens: torch.Tensor, + age: torch.Tensor, + static: torch.Tensor, + ) -> torch.Tensor: + """Builds the ids that a rollout starts from, ``[1, L]``. + + Args: + time: One sample's hours per token, ``[L]``. + tokens: One sample's tokens, ``[L]``, possibly padded. + age: The sample's age in years. + static: The sample's context tokens, ``[C]``. + + Returns: + The context, then the last tokens that fit. A closing + ``TIMELINE_END`` is left out, since the timeline continues here. + """ + vocab = self.timeline_processor.vocab + kept = tokens != vocab.pad_id + time, tokens = time[kept], tokens[kept].to(self.device) + if len(tokens) and tokens[-1] == vocab[TIMELINE_END_TOKEN]: + time, tokens = time[:-1], tokens[:-1] + start = max(len(tokens) - self.timeline_size, 0) + elapsed = time[start].item() if len(time) else 0.0 + age_at_start = age.to(self.device, dtype=torch.float32).view(-1) + age_at_start = age_at_start + elapsed / HOURS_PER_YEAR + context = self._context_ids(static.to(self.device).view(1, -1), age_at_start) + return torch.cat([context, tokens[start:].view(1, -1)], dim=1) + + @torch.no_grad() + def rollout( + self, + timeline: tuple[torch.Tensor, torch.Tensor], + context: tuple[torch.Tensor, torch.Tensor], + rule: EthosRolloutRule, + num_rollouts: int = 100, + temperature: float = 1.0, + max_new_tokens: int = 8192, + generator: torch.Generator | None = None, + ) -> dict[str, list]: + """Samples future timelines for one sample. + + Each rollout samples one token at a time, adding up the mean duration + of each interval token, until ``rule`` stops it, it passes the time + limit, it samples an id that is not a timeline token, or it reaches + ``max_new_tokens``. + + Args: + timeline: ``(time, tokens)`` of one sample, both ``[L]``. + context: ``(age, tokens)`` of one sample. + rule: When to stop. + num_rollouts: Number of timelines to sample. + temperature: Softmax temperature. + max_new_tokens: Limit on generated tokens per rollout. ETHOS has + none, but a poorly trained model may never advance the clock. + generator: Source of randomness, on this model's device. + + Returns: + A dictionary of lists, one element per rollout: ``tokens`` (the + generated ids), ``actual`` (the last token, or ``None`` if invalid), + ``reason`` (why it stopped) and ``days`` (simulated days). + """ + was_training = self.training + self.eval() + prompt = self._prompt(*timeline, *context) + ids = prompt.repeat(num_rollouts, 1) + stops = self._token_mask(rule.stop_prefixes) + limit = rule.time_limit_days * 24.0 + + alive = torch.arange(num_rollouts) + hours = torch.zeros(num_rollouts, dtype=torch.float64) + generated: list[list[int]] = [[] for _ in range(num_rollouts)] + reasons = [TOKEN_LIMIT] * num_rollouts + for _ in range(max_new_tokens): + logits = self._logits(ids)[:, -1, :] / temperature + probs = F.softmax(logits, dim=-1) + next_ids = torch.multinomial(probs, num_samples=1, generator=generator) + + if ids.size(1) == self.n_positions: + ids = torch.cat( + [ids[:, : self.context_size], ids[:, self.context_size + 1 :]], + dim=1, + ) + ids = torch.cat([ids, next_ids], dim=1) + + drawn = next_ids.view(-1).cpu() + hours[alive] += self._interval_hours[drawn] + for index, token in zip(alive.tolist(), drawn.tolist()): + generated[index].append(token) + + invalid = ~self._is_token[drawn] + late = hours[alive] > limit + done = invalid | late | stops[drawn] + for row in done.nonzero().view(-1).tolist(): + reason = STOP_TOKEN + if late[row]: + reason = TIME_LIMIT + if invalid[row]: + reason = INVALID_TOKEN + reasons[alive[row]] = reason + + alive, ids = alive[~done], ids[~done.to(ids.device)] + if len(alive) == 0: + break + + self.train(was_training) + return { + "tokens": generated, + "actual": [ + self._id_to_token[tokens[-1]] + if tokens and self._is_token[tokens[-1]] + else None + for tokens in generated + ], + "reason": reasons, + "days": (hours / 24.0).tolist(), + } + + def _check_processors(self, dataset: Any) -> None: + """Raises if ``dataset`` encodes with other processors than the model's.""" + processors = getattr(dataset, "input_processors", None) + if not processors: + return + ours = {"timeline": self.timeline_processor, "context": self.context_processor} + for key, mine in ours.items(): + theirs = processors.get(key) + if theirs is mine: + continue + same = ( + theirs is not None + and type(theirs) is type(mine) + and theirs.vocab is not None + and theirs.vocab.to_json() == mine.vocab.to_json() + and getattr(theirs, "quantiles", None) == getattr(mine, "quantiles", None) + and getattr(theirs, "interval_estimates", None) + == getattr(mine, "interval_estimates", None) + ) + if not same: + raise ValueError( + f"The dataset's {key!r} processor is not the one this model " + "was trained with, so its token ids mean something else. " + "Build the outcome dataset with " + "input_processors=model.dataset.input_processors." + ) + + def _check_ids(self, tokens: torch.Tensor, static: torch.Tensor) -> None: + """Raises if a batch has ids outside the model's vocabularies.""" + if tokens.numel() and int(tokens.max()) >= self.timeline_vocab_size: + raise ValueError( + "A timeline token id is outside this model's vocabulary; the " + "batch was encoded with other processors. Build the outcome " + "dataset with input_processors=model.dataset.input_processors." + ) + if static.numel() and int(static.max()) >= self.context_processor.size(): + raise ValueError( + "A context token id is outside this model's vocabulary; build " + "the outcome dataset with " + "input_processors=model.dataset.input_processors." + ) + + def estimate_risk( + self, + dataloader: Iterable[dict[str, Any]], + rule: EthosRolloutRule, + num_rollouts: int = 100, + temperature: float = 1.0, + max_new_tokens: int = 8192, + label_key: str | None = None, + seed: int | None = None, + ) -> dict[str, Any]: + """Estimates each sample's risk from sampled timelines. + + The risk is the share of positive rollouts among those ``rule`` keeps. + The paper uses 100 rollouts per sample. + + The batches must be encoded with this model's processors: build the + outcome dataset with ``input_processors=model.dataset.input_processors`` + (see :class:`~pyhealth.tasks.EthosOutcomeMEDS`). Processors fitted on + the outcome samples give token ids that mean something else, so this + raises ``ValueError`` when the dataloader's dataset has other + processors, or when a token id falls outside the model's vocabulary. + + Rollouts have no key-value cache: each new token re-runs the model over + the whole sequence so far. That is fine for small models and short + rollouts, but it will be slow at the paper's scale (2048-token context, + 100 rollouts per sample). + + Args: + dataloader: Batches with ``timeline`` and ``context``. + rule: How rollouts stop and count, such as + :attr:`pyhealth.tasks.EthosOutcomeMEDS.rule`. + num_rollouts: Rollouts per sample. + temperature: Softmax temperature. + max_new_tokens: Limit on generated tokens per rollout. + label_key: A label to return as ``y_true``. + seed: Seed for reproducible rollouts. + + Returns: + A dictionary with ``y_prob`` (``nan`` if every rollout was dropped), + ``num_kept`` (rollouts behind each risk), ``patient_id`` (if the + batches have it) and ``y_true`` (with ``label_key``). + """ + self._check_processors(getattr(dataloader, "dataset", None)) + generator = None + if seed is not None: + generator = torch.Generator(device=self.device).manual_seed(seed) + + risks: list[float] = [] + kept_counts: list[int] = [] + patient_ids: list[Any] = [] + labels: list[torch.Tensor] = [] + for batch in dataloader: + time, tokens = batch["timeline"] + age, static = batch["context"] + self._check_ids(tokens, static) + for i in range(len(tokens)): + result = self.rollout( + (time[i], tokens[i]), + (age[i], static[i]), + rule, + num_rollouts=num_rollouts, + temperature=temperature, + max_new_tokens=max_new_tokens, + generator=generator, + ) + scores = [ + rule.score(actual, reason, days) + for actual, reason, days in zip( + result["actual"], result["reason"], result["days"] + ) + ] + kept = [score for score in scores if score is not None] + risks.append(sum(kept) / len(kept) if kept else math.nan) + kept_counts.append(len(kept)) + patient_ids.extend(batch.get("patient_id", [])) + if label_key is not None: + labels.append(batch[label_key].view(-1).cpu()) + + output: dict[str, Any] = { + "y_prob": torch.tensor(risks, dtype=torch.float32), + "num_kept": torch.tensor(kept_counts, dtype=torch.long), + } + if patient_ids: + output["patient_id"] = patient_ids + if label_key is not None: + output["y_true"] = torch.cat(labels) + return output diff --git a/pyhealth/processors/__init__.py b/pyhealth/processors/__init__.py index c11e30ef28..c79b9b4857 100644 --- a/pyhealth/processors/__init__.py +++ b/pyhealth/processors/__init__.py @@ -79,6 +79,7 @@ def get_processor(name: str): from .tuple_time_text_processor import TupleTimeTextProcessor from .cehr_processor import CehrProcessor, ConceptVocab from .ethos_processor import EthosProcessor +from .ethos_context_processor import EthosContextProcessor from .unified_bridge import ( BridgeDataset, UnifiedBridge, @@ -146,4 +147,5 @@ def get_processor(name: str): "CehrProcessor", "ConceptVocab", "EthosProcessor", + "EthosContextProcessor", ] diff --git a/pyhealth/processors/ethos_context_processor.py b/pyhealth/processors/ethos_context_processor.py new file mode 100644 index 0000000000..488992f4c9 --- /dev/null +++ b/pyhealth/processors/ethos_context_processor.py @@ -0,0 +1,243 @@ +"""Static patient context for ETHOS timelines. + +ETHOS opens every timeline with tokens for the patient's demographics and age. +:class:`~pyhealth.processors.EthosProcessor` keeps those codes out of the +timeline itself; this processor encodes them. + +Paper: + Renc et al. Foundation Model of Electronic Medical Records for Adaptive + Risk Estimation. https://arxiv.org/abs/2502.06124 + +Adapted from ethos-ares (commit 2d54383), ``src/ethos/datasets/base.py`` and +``src/ethos/tokenize/common/basic.py``: +https://github.com/ipolharvard/ethos-ares + +MIT License. Copyright (c) 2024 Paweł Renc. +""" + +from __future__ import annotations + +from collections.abc import Iterable, Sequence +from datetime import datetime +from pathlib import Path +from typing import Any + +import orjson +import torch + +from . import register_processor +from .base_processor import FeatureProcessor +from .ethos_processor import STATIC_CODE_PREFIXES, EthosVocab + +BIRTH_CODE = "MEDS_BIRTH" +UNKNOWN_SUFFIX = "//UNKNOWN" +DAYS_PER_YEAR = 365.25 + + +def _value_at_start( + rows: list[tuple[datetime | None, str]], + attribute: str, + start: datetime | None, +) -> str: + """Returns the code of one attribute at the start of a timeline. + + An attribute with a single value keeps it whenever it was recorded. With + several values, the latest one recorded by ``start`` applies, as ETHOS does. + + Args: + rows: ``(time, code)`` rows of this attribute in time order. A row + without a time counts as known from the beginning. + attribute: The attribute's prefix. + start: Start of the timeline. + + Returns: + The code, or ``//UNKNOWN`` if nothing applies yet. + """ + if len(rows) == 1: + return rows[0][1] + known = [ + code for time, code in rows if time is None or start is None or time <= start + ] + return known[-1] if known else attribute + UNKNOWN_SUFFIX + + +@register_processor("ethos_context") +class EthosContextProcessor(FeatureProcessor): + """Encodes the static context that opens an ETHOS timeline. + + The input is one patient's static rows: + + * ``time``: a timestamp or ``None`` per row. + * ``code``: a string per row, such as ``GENDER//F`` or ``MEDS_BIRTH``. + * ``start``: when the timeline starts. + + The output has a fixed length. Attributes are sorted by name, so with the + default prefixes it reads ``GENDER``, ``MARITAL``, the two age tokens, + ``RACE``. A patient with no value gets ``//UNKNOWN``, and a value + unseen in :meth:`fit` gets ````. The age tokens hold ```` here: + their quantile tokens belong to the timeline vocabulary and depend on where + a window of the timeline starts, so :class:`~pyhealth.models.ETHOS` fills + them in from the returned age. + + Args: + prefixes: Static code prefixes, including ``MEDS_BIRTH``. Use the same + ones as ``exclude_prefixes`` of + :class:`~pyhealth.processors.EthosProcessor`. + + Raises: + ValueError: If ``prefixes`` leaves out ``MEDS_BIRTH``. + + Examples: + >>> from datetime import datetime + >>> from pyhealth.processors import EthosContextProcessor + >>> static = { + ... "time": [datetime(1980, 1, 1), None], + ... "code": ["MEDS_BIRTH", "GENDER//F"], + ... "start": datetime(2024, 1, 1), + ... } + >>> processor = EthosContextProcessor() + >>> processor.fit([{"context": static}], "context") + >>> age, tokens = processor.process(static) + >>> round(age.item(), 1) + 44.0 + >>> processor.decode(tokens) + ['GENDER//F', 'MARITAL//UNKNOWN', '', '', 'RACE//UNKNOWN'] + """ + + stores_tensor = True + + def __init__(self, prefixes: Sequence[str] = STATIC_CODE_PREFIXES) -> None: + if BIRTH_CODE not in prefixes: + raise ValueError(f"prefixes must include {BIRTH_CODE}, got {prefixes}.") + self.prefixes = tuple(sorted(prefixes)) + self.vocab: EthosVocab | None = None + + @property + def age_position(self) -> int: + """Index of the first of the two age tokens in the output.""" + return self.prefixes.index(BIRTH_CODE) + + @property + def context_size(self) -> int: + """Length of the output: one per attribute, and two for age.""" + return len(self.prefixes) + 1 + + def fit(self, samples: Iterable[dict[str, Any]], field: str) -> None: + """Learns the vocabulary of attribute values. + + Args: + samples: Sample dictionaries. + field: Key of the static rows in each sample. + """ + self.vocab = EthosVocab() + for prefix in self.prefixes: + if prefix != BIRTH_CODE: + self.vocab.add_token(prefix + UNKNOWN_SUFFIX) + for sample in samples: + for code in sorted(sample[field]["code"]): + if code.startswith(self.prefixes) and code != BIRTH_CODE: + self.vocab.add_token(code) + + def process(self, value: dict[str, Any]) -> tuple[torch.Tensor, torch.Tensor]: + """Encodes one patient's static rows. + + Args: + value: Static rows, as in the class docstring. + + Returns: + ``(age, tokens)``. ``age`` has one ``float64`` element, the age in + years at ``start``, or ``nan`` without a usable birth date. + ``tokens`` is ``long`` and has :attr:`context_size` elements. + + Raises: + RuntimeError: If called before :meth:`fit` or :meth:`load`. + """ + if self.vocab is None: + raise RuntimeError("EthosContextProcessor must be fitted or loaded first.") + + start = value["start"] + pairs = list(zip(value["time"], value["code"])) + rows = [row for row in pairs if row[0] is None] + rows += sorted((row for row in pairs if row[0] is not None), key=lambda r: r[0]) + tokens: list[int] = [] + age = float("nan") + for prefix in self.prefixes: + matching = [row for row in rows if row[1].startswith(prefix)] + if prefix == BIRTH_CODE: + if matching and matching[0][0] is not None and start is not None: + age = (start - matching[0][0]).days / DAYS_PER_YEAR + tokens += [self.vocab.pad_id, self.vocab.pad_id] + elif matching: + tokens.append(self.vocab[_value_at_start(matching, prefix, start)]) + else: + tokens.append(self.vocab[prefix + UNKNOWN_SUFFIX]) + return ( + torch.tensor([age], dtype=torch.float64), + torch.tensor(tokens, dtype=torch.long), + ) + + def decode(self, tokens: torch.Tensor | Iterable[int]) -> list[str]: + """Maps token ids back to token strings. + + Args: + tokens: Token ids, such as the output of :meth:`process`. + + Returns: + The token strings. + + Examples: + >>> from pyhealth.processors import EthosContextProcessor + >>> processor = EthosContextProcessor() + >>> processor.fit([], "context") + >>> processor.decode([0, 1]) + ['', ''] + """ + by_id = {index: token for token, index in self.vocab.token_to_id.items()} + return [by_id[int(token)] for token in tokens] + + def save(self, path: str) -> None: + """Saves the configuration and fitted state as JSON. + + Args: + path: File to write. + """ + state = { + "prefixes": self.prefixes, + "vocab": None if self.vocab is None else self.vocab.to_json(), + } + Path(path).parent.mkdir(parents=True, exist_ok=True) + Path(path).write_bytes(orjson.dumps(state, option=orjson.OPT_SORT_KEYS)) + + def load(self, path: str) -> None: + """Restores what :meth:`save` wrote, replacing the current state. + + Args: + path: File to read. + """ + state = orjson.loads(Path(path).read_bytes()) + self.prefixes = tuple(state["prefixes"]) + vocab = state["vocab"] + self.vocab = None if vocab is None else EthosVocab.from_json(vocab) + + def size(self) -> int: + """Returns the vocabulary size.""" + return 0 if self.vocab is None else self.vocab.vocab_size + + def is_token(self) -> bool: + """Output tokens are discrete indices.""" + return True + + def schema(self) -> tuple[str, ...]: + return ("age", "value") + + def dim(self) -> tuple[int, ...]: + return (1, 1) + + def spatial(self) -> tuple[bool, ...]: + return (False,) + + def __repr__(self) -> str: + return ( + f"EthosContextProcessor(prefixes={self.prefixes}, " + f"vocab_size={self.size()})" + ) diff --git a/pyhealth/processors/ethos_processor.py b/pyhealth/processors/ethos_processor.py index 53613d3a0d..46e0723573 100644 --- a/pyhealth/processors/ethos_processor.py +++ b/pyhealth/processors/ethos_processor.py @@ -249,6 +249,12 @@ class EthosProcessor(FeatureProcessor): An unseen code becomes ```` with no quantile token. All quantile and interval tokens are in the vocabulary, whether or not training saw them. + :meth:`fit` also learns ``interval_estimates``: each interval token's mean + duration in hours, as ETHOS's ``IntervalEstimator`` does, so that a + generated timeline can be converted back to elapsed time. Repeats of + ``=6mt`` split their gap evenly. A token that training never saw falls + back to its lower bound. + Args: num_quantiles: Number of bins per code. ETHOS uses 10. quantize_prefixes: Quantize only codes with one of these prefixes. By @@ -296,6 +302,7 @@ def __init__( self.add_timeline_end = add_timeline_end self.vocab: EthosVocab | None = None self.quantiles: dict[str, list[float]] = {} + self.interval_estimates: dict[str, float] = {} def _read( self, timeline: dict[str, Any] | None @@ -354,9 +361,16 @@ def fit(self, samples: Iterable[dict[str, Any]], field: str) -> None: """ observed: dict[str, list[float]] = defaultdict(list) codes: set[str] = set() + spans: dict[str, float] = defaultdict(float) + counts: dict[str, int] = defaultdict(int) for sample in samples: - _, sample_codes, values = self._read(sample.get(field)) + stamps, sample_codes, values = self._read(sample.get(field)) codes.update(sample_codes) + for gap in np.diff(stamps).tolist(): + labels = _interval_tokens(gap) + for label in labels: + spans[label] += gap / len(labels) + counts[label] += 1 for code, value in zip(sample_codes, values.tolist()): if math.isnan(value): continue @@ -369,6 +383,11 @@ def fit(self, samples: Iterable[dict[str, Any]], field: str) -> None: code: _quantile_breaks(values, self.num_quantiles) for code, values in observed.items() } + self.interval_estimates = { + label: (spans[label] / counts[label] if counts[label] else bound) + / _MICROSECONDS_PER_HOUR + for label, bound in zip(_INTERVAL_LABELS, _INTERVAL_BOUNDS) + } self.vocab = EthosVocab() for k in range(1, self.num_quantiles + 1): self.vocab.add_token(f"Q{k}") @@ -456,6 +475,7 @@ def save(self, path: str) -> None: "add_timeline_end": self.add_timeline_end, "vocab": None if self.vocab is None else self.vocab.to_json(), "quantiles": self.quantiles, + "interval_estimates": self.interval_estimates, } Path(path).parent.mkdir(parents=True, exist_ok=True) Path(path).write_bytes(orjson.dumps(state, option=orjson.OPT_SORT_KEYS)) @@ -475,6 +495,7 @@ def load(self, path: str) -> None: vocab = state["vocab"] self.vocab = None if vocab is None else EthosVocab.from_json(vocab) self.quantiles = state["quantiles"] + self.interval_estimates = state["interval_estimates"] def size(self) -> int: """Returns the vocabulary size.""" diff --git a/pyhealth/tasks/__init__.py b/pyhealth/tasks/__init__.py index b1e1445610..5f6ff93c58 100644 --- a/pyhealth/tasks/__init__.py +++ b/pyhealth/tasks/__init__.py @@ -85,6 +85,11 @@ ICUAdmissionMEDS as ICUAdmissionMEDS, ProlongedLengthOfStayMEDS as ProlongedLengthOfStayMEDS, ) +from .ethos_tasks import ( + EthosOutcomeMEDS as EthosOutcomeMEDS, + EthosRolloutRule as EthosRolloutRule, + EthosTimelineMEDS as EthosTimelineMEDS, +) from .msd_segmentation import MSDSegmentationTask as MSDSegmentationTask from .next_visit_diagnosis_prediction import ( NextVisitDiagnosisPredictionMIMIC3 as NextVisitDiagnosisPredictionMIMIC3, diff --git a/pyhealth/tasks/ethos_tasks.py b/pyhealth/tasks/ethos_tasks.py new file mode 100644 index 0000000000..03457a3acb --- /dev/null +++ b/pyhealth/tasks/ethos_tasks.py @@ -0,0 +1,328 @@ +"""MEDS timelines for the ETHOS generative model, and its zero-shot outcomes. + +ETHOS is trained without labels, on whole patient timelines, and then predicts +an outcome by sampling future timelines from the prediction time: + +* :class:`EthosTimelineMEDS` gives the training timelines. +* :class:`EthosOutcomeMEDS` runs an outcome task from + :mod:`~pyhealth.tasks.meds_outcome_tasks`, keeps its cohort and labels, and + swaps its code list for the same rows in the form ETHOS tokenizes, cut at the + same prediction time. +* :class:`EthosRolloutRule` says when a sampled timeline stops and how it counts + toward the risk. ``EthosOutcomeMEDS`` builds the matching one. + +Rollout rules follow the ETHOS-ARES code that produced the paper's Table S1 +(``src/ethos/datasets/{mimic_icu,readmission,hospital_mortality}.py`` and +``notebooks/{figures,hosp_readmission}.ipynb``, commit 2d54383). MIT License. +Copyright (c) 2024 Paweł Renc. + +References: + Renc P., Grzeszczyk M. K., Oufattole N., et al. Foundation Model of + Electronic Medical Records for Adaptive Risk Estimation. arXiv:2502.06124. + https://arxiv.org/abs/2502.06124 + + Source code: https://github.com/ipolharvard/ethos-ares +""" + +from dataclasses import dataclass +from typing import Any, ClassVar + +import polars as pl + +from ..processors.ethos_processor import STATIC_CODE_PREFIXES, TIMELINE_END_TOKEN +from .base_task import BaseTask +from .meds_outcome_tasks import ( + ICU_ADMISSION_PREFIX, + HospitalReadmissionMEDS, + ICUAdmissionMEDS, + ProlongedLengthOfStayMEDS, + _completed_stays, + _load_events, + _rows_at_admission, + _rows_at_discharge, +) + +# MEDS codes, the same as in in_hospital_mortality_meds.py and +# meds_outcome_tasks.py, kept here so this module does not import them. +ADMISSION_PREFIX = "HOSPITAL_ADMISSION" +DISCHARGE_PREFIX = "HOSPITAL_DISCHARGE" +DIED_CODE = "HOSPITAL_DISCHARGE//DIED" +DEATH_CODE = "MEDS_DEATH" + +#: Why a rollout stopped. The first three are ETHOS's. +STOP_TOKEN = "token_of_interest" +TIME_LIMIT = "time_limit" +INVALID_TOKEN = "key_error" +TOKEN_LIMIT = "token_limit" + +#: ETHOS's default limit on simulated time. +DEFAULT_TIME_LIMIT_DAYS = 365.25 * 2 + + +@dataclass(frozen=True) +class EthosRolloutRule: + """When a sampled timeline stops, and how it counts toward a risk. + + The risk of a sample is the share of positive rollouts among those not + dropped, as in ETHOS's ``preprocess_inference_results``. Rollouts stopped by + an invalid token or by ``max_new_tokens`` are always dropped. + + Args: + stop_prefixes: Code prefixes that end a rollout. + positive_prefixes: A rollout stopped by one of these is positive. + time_limit_days: Simulated time at which a rollout gives up. + min_days: A rollout stopped at least this long after the prediction + time is positive, whatever stopped it. + drop_prefixes: Rollouts stopped by one of these are dropped. + keep_time_limited: Count rollouts that reach the time limit as + negative. By default they are dropped. + + Examples: + >>> from pyhealth.tasks import EthosRolloutRule + >>> rule = EthosRolloutRule( + ... stop_prefixes=("HOSPITAL_DISCHARGE", "MEDS_DEATH", "TIMELINE_END"), + ... positive_prefixes=("HOSPITAL_DISCHARGE//DIED", "MEDS_DEATH"), + ... drop_prefixes=("TIMELINE_END",), + ... ) + >>> rule.score("MEDS_DEATH", "token_of_interest", days=3.0) + True + >>> rule.score("HOSPITAL_DISCHARGE//HOME", "token_of_interest", days=3.0) + False + >>> rule.score("TIMELINE_END", "token_of_interest", days=3.0) is None + True + """ + + stop_prefixes: tuple[str, ...] + positive_prefixes: tuple[str, ...] = () + time_limit_days: float = DEFAULT_TIME_LIMIT_DAYS + min_days: float | None = None + drop_prefixes: tuple[str, ...] = () + keep_time_limited: bool = False + + def score(self, code: str | None, reason: str, days: float) -> bool | None: + """Scores one rollout. + + Args: + code: The last generated token. + reason: Why the rollout stopped. + days: Simulated days since the prediction time. + + Returns: + Whether the rollout is positive, or ``None`` if it is dropped. + """ + if reason == TIME_LIMIT: + return False if self.keep_time_limited else None + if reason != STOP_TOKEN or code.startswith(self.drop_prefixes): + return None + if code.startswith(self.positive_prefixes): + return True + return self.min_days is not None and days >= self.min_days + + +def _rollout_rule(task: BaseTask) -> EthosRolloutRule: + """Returns the rollout rule that matches an outcome task's label. + + Args: + task: An outcome task from :mod:`.meds_outcome_tasks`. + + Returns: + The rule, using the task's ``death_as_positive``, ``window_days`` or + ``threshold_days``. + """ + if isinstance(task, ICUAdmissionMEDS): + deaths = (DEATH_CODE, DIED_CODE) if task.death_as_positive else () + return EthosRolloutRule( + stop_prefixes=( + ICU_ADMISSION_PREFIX, + DISCHARGE_PREFIX, + DEATH_CODE, + TIMELINE_END_TOKEN, + ), + positive_prefixes=(ICU_ADMISSION_PREFIX, *deaths), + drop_prefixes=(TIMELINE_END_TOKEN,), + ) + if isinstance(task, HospitalReadmissionMEDS): + return EthosRolloutRule( + stop_prefixes=(ADMISSION_PREFIX, DEATH_CODE, TIMELINE_END_TOKEN), + positive_prefixes=(ADMISSION_PREFIX, DEATH_CODE), + time_limit_days=task.window_days, + keep_time_limited=True, + ) + return EthosRolloutRule( + stop_prefixes=(DISCHARGE_PREFIX, DEATH_CODE, TIMELINE_END_TOKEN), + min_days=task.threshold_days, + drop_prefixes=(TIMELINE_END_TOKEN,), + ) + + +def _timeline_fields( + rows: pl.DataFrame, + prefixes: tuple[str, ...] = STATIC_CODE_PREFIXES, +) -> dict[str, dict[str, Any]] | None: + """Splits MEDS rows into the ``timeline`` and ``context`` sample fields. + + Args: + rows: MEDS events, with ``timestamp``, ``meds/code`` and + ``meds/numeric_value``. + prefixes: Static code prefixes. + + Returns: + The two fields, or ``None`` if no row is left for the timeline. + """ + code = pl.col("meds/code") + is_static = code.str.starts_with(prefixes[0]) + for prefix in prefixes[1:]: + is_static = is_static | code.str.starts_with(prefix) + static = rows.filter(is_static) + timeline = rows.filter(~is_static & pl.col("timestamp").is_not_null()) + if timeline.height == 0: + return None + return { + "timeline": { + "time": timeline["timestamp"].to_list(), + "code": timeline["meds/code"].to_list(), + "numeric_value": timeline["meds/numeric_value"].to_list(), + }, + "context": { + "time": static["timestamp"].to_list(), + "code": static["meds/code"].to_list(), + "start": timeline["timestamp"].min(), + }, + } + + +class EthosTimelineMEDS(BaseTask): + """One whole MEDS timeline per patient, for training ETHOS. + + There is no label: :class:`~pyhealth.models.ETHOS` learns to predict the + next token. Fit on the training patients only, with + ``set_task(EthosTimelineMEDS(), split=PatientSplit(...))``. + + Attributes: + task_name (str): The name of the task. + input_schema (Dict[str, str]): ``timeline``, the tokenized events, and + ``context``, the static patient context. + output_schema (Dict[str, str]): Empty. + + Examples: + >>> from pyhealth.datasets import MEDSDataset, PatientSplit + >>> from pyhealth.tasks import EthosTimelineMEDS + >>> dataset = MEDSDataset(root="/path/to/meds") # doctest: +SKIP + >>> train, test = dataset.set_task( # doctest: +SKIP + ... EthosTimelineMEDS(), split=PatientSplit(ratios=(0.9, 0.1), seed=0) + ... ) + """ + + task_name: str = "EthosTimelineMEDS" + input_schema: ClassVar[dict[str, str]] = { + "timeline": "ethos", + "context": "ethos_context", + } + output_schema: ClassVar[dict[str, str]] = {} + + def pre_filter(self, df: pl.LazyFrame) -> pl.LazyFrame: + """Restricts the global scan to MEDS events.""" + return df.filter(pl.col("event_type") == "meds") + + def __call__(self, patient: Any) -> list[dict[str, Any]]: + fields = _timeline_fields(patient.get_events(event_type="meds", return_df=True)) + if fields is None: + return [] + return [{"patient_id": patient.patient_id, **fields}] + + +class EthosOutcomeMEDS(BaseTask): + """An outcome task's cohort and labels, as ETHOS timelines. + + Runs ``outcome_task(**options)`` and replaces each sample's ``codes`` with + the same rows, so that the cohort, the label and every leakage exclusion + stay the outcome task's own. The timeline ends at the prediction time, and + :attr:`rule` says how rollouts from there become a risk: + + * :class:`~pyhealth.tasks.ICUAdmissionMEDS`, at admission: stop at ICU + admission, discharge, death or the end of the timeline. An ICU admission + is positive, and so is a death if ``death_as_positive`` is on, including + a discharge coded ``HOSPITAL_DISCHARGE//DIED``. ETHOS's Table S1 uses the + ICU-only label, ``death_as_positive=False``. The two-year time limit and + ``TIMELINE_END`` drop a rollout. + * :class:`~pyhealth.tasks.ProlongedLengthOfStayMEDS`, at admission: stop at + discharge, death or the end of the timeline. A rollout is positive if it + stops at least ``threshold_days`` after admission, inclusive. The + two-year time limit and ``TIMELINE_END`` drop a rollout. + * :class:`~pyhealth.tasks.HospitalReadmissionMEDS`, at discharge: stop at + admission, death or the end of the timeline. An admission or a death is + positive. A rollout that passes ``window_days``, or reaches + ``TIMELINE_END``, is negative. ``require_full_followup`` only changes the + cohort, not the rollout. + + Pass the fitted processors of :class:`EthosTimelineMEDS` as + ``input_processors``, so that both tasks share one vocabulary. + + Args: + outcome_task (type[BaseTask]): One of the three task classes above. + **options: Keyword arguments for ``outcome_task``. + + Attributes: + task_name (str): ``Ethos`` and the outcome task's name. + input_schema (Dict[str, str]): Same as :class:`EthosTimelineMEDS`. + output_schema (Dict[str, str]): The outcome task's. + rule (EthosRolloutRule): How rollouts become a risk. + + Raises: + ValueError: If ``outcome_task`` is not one of the three. + + Examples: + >>> from pyhealth.tasks import EthosOutcomeMEDS, ICUAdmissionMEDS + >>> task = EthosOutcomeMEDS(ICUAdmissionMEDS, death_as_positive=False) + >>> task.task_name + 'EthosICUAdmissionMEDS' + >>> task.output_schema + {'icu_admission': 'binary'} + >>> task.rule.positive_prefixes + ('ICU_ADMISSION',) + """ + + input_schema: ClassVar[dict[str, str]] = EthosTimelineMEDS.input_schema + + def __init__(self, outcome_task: type[BaseTask], **options: Any) -> None: + if outcome_task not in ( + ICUAdmissionMEDS, + HospitalReadmissionMEDS, + ProlongedLengthOfStayMEDS, + ): + raise ValueError( + "outcome_task must be ICUAdmissionMEDS, HospitalReadmissionMEDS " + f"or ProlongedLengthOfStayMEDS, got {outcome_task}." + ) + super().__init__() + # The class and options rather than an instance: dataset caches hash + # this object's attributes, and an instance's text form changes per run. + self.outcome_task = outcome_task + self.options = options + self.task_name = f"Ethos{outcome_task.task_name}" + self.output_schema = dict(outcome_task.output_schema) + self.rule = _rollout_rule(outcome_task(**options)) + + def pre_filter(self, df: pl.LazyFrame) -> pl.LazyFrame: + """Restricts the global scan to MEDS events.""" + return df.filter(pl.col("event_type") == "meds") + + def __call__(self, patient: Any) -> list[dict[str, Any]]: + outcomes = self.outcome_task(**self.options)(patient) + if not outcomes: + return [] + + events = _load_events(patient) + stays = {stay["hadm_id"]: stay for stay in _completed_stays(events)} + cut = ( + _rows_at_discharge + if self.outcome_task is HospitalReadmissionMEDS + else _rows_at_admission + ) + samples = [] + for outcome in outcomes: + fields = _timeline_fields(cut(events, stays[outcome["hadm_id"]])) + if fields is not None: + kept = {key: val for key, val in outcome.items() if key != "codes"} + samples.append({**kept, **fields}) + return samples diff --git a/tests/core/test_ethos.py b/tests/core/test_ethos.py new file mode 100644 index 0000000000..6b67ef599f --- /dev/null +++ b/tests/core/test_ethos.py @@ -0,0 +1,487 @@ +"""Tests for the ETHOS model. Tiny models on synthetic timelines only.""" + +import inspect +import math +import tempfile +import unittest +from datetime import datetime, timedelta +from pathlib import Path + +import torch +import torch.nn.functional as F + +from pyhealth.datasets import create_sample_dataset, get_dataloader +from pyhealth.models import ETHOS +from pyhealth.models.ethos import _age_quantiles +from pyhealth.tasks import EthosRolloutRule +from pyhealth.trainer import Trainer + +START = datetime.fromisoformat("2024-01-01") +BIRTH = datetime.fromisoformat("1980-01-01") +ADMIT = "HOSPITAL_ADMISSION//ER" +HOME = "HOSPITAL_DISCHARGE//HOME" +DEATH = "MEDS_DEATH" +LAB = "LAB//A" +RULE = EthosRolloutRule( + stop_prefixes=(HOME, DEATH, "TIMELINE_END"), + positive_prefixes=(DEATH,), + time_limit_days=1.0, +) + + +def sample(index, rows): + """Rows are ``(hours, code, value)``.""" + return { + "patient_id": f"p{index}", + "timeline": { + "time": [START + timedelta(hours=r[0]) for r in rows], + "code": [r[1] for r in rows], + "numeric_value": [r[2] for r in rows], + }, + "context": { + "time": [BIRTH, None], + "code": ["MEDS_BIRTH", "GENDER//F" if index % 2 else "GENDER//M"], + "start": START, + }, + } + + +def tiny_dataset(extra=()): + samples = [ + sample( + i, + [ + (0.0, ADMIT, None), + (1.0, LAB, 1.0 + i), + (30.0, HOME if i else DEATH, None), + ], + ) + for i in range(3) + ] + samples.extend(extra) + return create_sample_dataset( + samples, + input_schema={"timeline": "ethos", "context": "ethos_context"}, + output_schema={}, + ) + + +def tiny_model(dataset, **kwargs): + options = {"n_layer": 1, "n_head": 2, "n_embd": 8, "n_positions": 32, "dropout": 0.0} + return ETHOS(dataset, **{**options, **kwargs}) + + +def batch_of(dataset, size=3): + return next(iter(get_dataloader(dataset, batch_size=size))) + + +def script(model, *tokens): + """Makes the model sample these tokens in turn, then keep to the last.""" + ids = [model.timeline_processor.vocab[token] for token in tokens] + steps = iter(ids) + + def logits(prompt): + token = next(steps, ids[-1]) + forced = F.one_hot(torch.tensor(token), model.vocab_size).float() * 1e4 + return forced.expand(*prompt.shape, -1) + + model._logits = logits + + +def one_sample(batch): + time, tokens = batch["timeline"] + age, static = batch["context"] + return (time[0], tokens[0]), (age[0], static[0]) + + +class TestArchitecture(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.dataset = tiny_dataset() + cls.batch = batch_of(cls.dataset) + + def setUp(self): + torch.manual_seed(0) + self.model = tiny_model(self.dataset) + + def test_defaults_are_the_papers_final_model(self): + parameters = inspect.signature(ETHOS).parameters + defaults = { + name: parameters[name].default + for name in ("n_layer", "n_head", "n_embd", "n_positions", "dropout") + } + self.assertEqual( + defaults, + { + "n_layer": 6, + "n_head": 12, + "n_embd": 768, + "n_positions": 2048, + "dropout": 0.3, + }, + ) + + def test_vocabulary_is_a_multiple_of_64(self): + model = self.model + self.assertEqual(model.vocab_size % 64, 0) + self.assertGreaterEqual( + model.vocab_size, + model.timeline_processor.size() + model.context_processor.size(), + ) + + def test_weights_are_tied_and_have_no_bias(self): + self.assertIs(self.model.transformer["wte"].weight, self.model.lm_head.weight) + self.assertFalse([n for n, _ in self.model.named_parameters() if "bias" in n]) + + def test_forward_pass(self): + output = self.model(**self.batch) + self.assertTrue(torch.isfinite(output["loss"])) + logits, labels = output["logit"], output["y_true"] + self.assertEqual(logits.shape[:2], labels.shape) + self.assertEqual(logits.size(-1), self.model.vocab_size) + self.assertIsNone(self.model.mode) + + def test_labels_shift_and_skip_the_context_and_padding(self): + labels = self.model(**self.batch)["y_true"] + tokens = self.batch["timeline"][1] + size = self.model.context_size + self.assertTrue((labels[:, :size] == -100).all()) + self.assertTrue(torch.equal(labels[:, size:], tokens[:, 1:])) + + short = sample(9, [(0.0, ADMIT, None)]) + dataset = tiny_dataset(extra=[short]) + batch = batch_of(dataset, size=4) + model = tiny_model(dataset) + labels = model(**batch)["y_true"] + self.assertTrue((labels[3, size + 2 :] == -100).all()) + + def test_gradients_reach_every_parameter(self): + self.model(**self.batch)["loss"].backward() + for name, parameter in self.model.named_parameters(): + if name != "_dummy_param": + self.assertIsNotNone(parameter.grad, name) + self.assertGreater(parameter.grad.abs().sum().item(), 0, name) + + def test_attention_is_causal(self): + ids = torch.randint(2, 10, (1, 8)) + changed = ids.clone() + changed[0, -1] = 11 + self.model.eval() + before, after = self.model._logits(ids), self.model._logits(changed) + self.assertTrue(torch.allclose(before[0, :-1], after[0, :-1])) + self.assertFalse(torch.allclose(before[0, -1], after[0, -1])) + + def test_batch_without_any_target_has_zero_loss(self): + time, tokens = self.batch["timeline"] + empty = { + "timeline": (time[:, :0], tokens[:, :0]), + "context": self.batch["context"], + } + loss = self.model(**empty)["loss"] + self.assertEqual(loss.item(), 0.0) + loss.backward() + + def test_rejects_datasets_without_ethos_fields(self): + dataset = create_sample_dataset( + [{"patient_id": "p", "codes": ["a"]}], + input_schema={"codes": "sequence"}, + output_schema={}, + ) + with self.assertRaises(ValueError): + tiny_model(dataset) + + def test_has_no_mode_and_rejects_labels(self): + self.assertIsNone(self.model.mode) + samples = [ + {**sample(i, [(0.0, ADMIT, None), (1.0, LAB, 1.0)]), "label": i % 2} + for i in range(2) + ] + dataset = create_sample_dataset( + samples, + input_schema={"timeline": "ethos", "context": "ethos_context"}, + output_schema={"label": "binary"}, + ) + with self.assertRaises(ValueError): + tiny_model(dataset) + + def test_rejects_sizes_that_do_not_fit(self): + with self.assertRaises(ValueError): + tiny_model(self.dataset, n_head=3) + with self.assertRaises(ValueError): + tiny_model(self.dataset, n_positions=5) + + +class TestContext(unittest.TestCase): + def test_age_digits(self): + age = torch.tensor([46.0, 0.0, 99.0, 150.0, -3.0, 45.97, math.nan]) + high, low = _age_quantiles(age, 10) + self.assertEqual(high.tolist(), [4, 0, 9, 9, 0, 4, -1]) + self.assertEqual(low.tolist(), [6, 0, 9, 9, 0, 6, -1]) + + def test_age_digits_carry(self): + high, low = _age_quantiles(torch.tensor([49.7]), 10) + self.assertEqual((high.item(), low.item()), (5, 0)) + + def test_context_ids(self): + dataset = tiny_dataset() + model = tiny_model(dataset) + batch = batch_of(dataset) + _, static = batch["context"] + ids = model._context_ids(static, torch.tensor([46.0, 46.0, math.nan])) + vocab = model.timeline_processor.vocab + position = model.context_processor.age_position + self.assertEqual(ids[0, position].item(), vocab["Q5"]) + self.assertEqual(ids[0, position + 1].item(), vocab["Q7"]) + self.assertEqual(ids[2, position].item(), vocab.unk_id) + others = ids[0, : position] + self.assertTrue((others >= model.timeline_vocab_size).all()) + + def test_long_timeline_uses_a_window_and_the_age_where_it_starts(self): + rows = [(float(i * 24 * 365), LAB, None) for i in range(40)] + dataset = tiny_dataset(extra=[sample(5, rows)]) + model = tiny_model(dataset) + batch = batch_of(dataset, size=4) + model.eval() + window = model.timeline_size + output = model(**batch) + self.assertEqual(output["logit"].size(1), model.n_positions) + + captured = {} + original = model._context_ids + + def spy(static, age): + captured["age"] = age + return original(static, age) + + model._context_ids = spy + model(**batch) + time, tokens = batch["timeline"] + start = (tokens[3] != 0).sum() - (window + 1) + self.assertGreater(start.item(), 0) + expected = (START - BIRTH).days / 365.25 + expected += time[3, start].item() / (24 * 365.25) + self.assertAlmostEqual(captured["age"][3].item(), expected, places=3) + + def test_training_windows_are_random_and_stay_in_the_timeline(self): + rows = [(float(i), LAB, 1.0) for i in range(60)] + dataset = tiny_dataset(extra=[sample(5, rows)]) + model = tiny_model(dataset) + batch = batch_of(dataset, size=4) + model.train() + ages = set() + original = model._context_ids + + def spy(static, age): + ages.add(round(age[3].item(), 6)) + return original(static, age) + + model._context_ids = spy + for _ in range(8): + self.assertTrue(torch.isfinite(model(**batch)["loss"])) + self.assertGreater(len(ages), 1) + + +class TestRollout(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.dataset = tiny_dataset() + cls.batch = batch_of(cls.dataset) + + def setUp(self): + torch.manual_seed(0) + self.model = tiny_model(self.dataset) + + def rollout(self, **kwargs): + options = {"num_rollouts": 2, "max_new_tokens": 6, **kwargs} + return self.model.rollout(*one_sample(self.batch), RULE, **options) + + def test_seeded_rollout_is_reproducible(self): + def run(seed): + generator = torch.Generator().manual_seed(seed) + return self.rollout(generator=generator, num_rollouts=8) + + first, second, other = run(1), run(1), run(2) + self.assertEqual(first, second) + self.assertNotEqual(first["tokens"], other["tokens"]) + + def test_stops_on_a_stop_token(self): + script(self.model, LAB, DEATH) + result = self.rollout() + self.assertEqual(result["reason"], ["token_of_interest"] * 2) + self.assertEqual(result["actual"], [DEATH] * 2) + self.assertEqual(len(result["tokens"][0]), 2) + + def test_interval_tokens_advance_the_clock_up_to_the_limit(self): + script(self.model, "12h-18h") + hours = self.model.timeline_processor.interval_estimates["12h-18h"] + result = self.rollout(max_new_tokens=8) + self.assertEqual(result["reason"], ["time_limit"] * 2) + steps = len(result["tokens"][0]) + self.assertEqual(steps, math.floor(24.0 / hours) + 1) + self.assertAlmostEqual(result["days"][0], steps * hours / 24.0) + + def test_tokens_that_are_not_timeline_tokens_are_invalid(self): + self.model._logits = lambda ids: ( + F.one_hot( + torch.tensor(self.model.vocab_size - 1), self.model.vocab_size + ).float() + * 1e4 + ).expand(*ids.shape, -1) + result = self.rollout() + self.assertEqual(result["reason"], ["key_error"] * 2) + self.assertEqual(result["actual"], [None] * 2) + + def test_gives_up_after_max_new_tokens(self): + script(self.model, LAB) + result = self.rollout(max_new_tokens=3) + self.assertEqual(result["reason"], ["token_limit"] * 2) + self.assertEqual(len(result["tokens"][0]), 3) + + def test_rollouts_stop_separately(self): + vocab = self.model.timeline_processor.vocab + calls = iter([[LAB, DEATH], [HOME]]) + + def logits(ids): + tokens = next(calls) + forced = torch.zeros(len(tokens), 1, self.model.vocab_size) + for row, token in enumerate(tokens): + forced[row, 0, vocab[token]] = 1e4 + return forced + + self.model._logits = logits + result = self.rollout() + self.assertEqual(result["actual"], [HOME, DEATH]) + self.assertEqual([len(t) for t in result["tokens"]], [2, 1]) + + def test_a_full_context_slides_and_keeps_the_static_tokens(self): + seen = [] + + def logits(ids): + seen.append(ids.clone()) + forced = torch.zeros(*ids.shape, self.model.vocab_size) + forced[..., self.model.timeline_processor.vocab[LAB]] = 1e4 + return forced + + self.model._logits = logits + self.rollout(max_new_tokens=40, num_rollouts=1) + size = self.model.context_size + self.assertEqual(max(ids.size(1) for ids in seen), self.model.n_positions) + self.assertTrue(torch.equal(seen[-1][:, :size], seen[0][:, :size])) + + def test_prompt_leaves_out_timeline_end(self): + (time, tokens), (age, static) = one_sample(self.batch) + vocab = self.model.timeline_processor.vocab + self.assertEqual(tokens[tokens != 0][-1].item(), vocab["TIMELINE_END"]) + prompt = self.model._prompt(time, tokens, age, static) + self.assertNotEqual(prompt[0, -1].item(), vocab["TIMELINE_END"]) + + def test_restores_training_mode(self): + self.model.train() + self.rollout() + self.assertTrue(self.model.training) + + +class TestEstimateRisk(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.dataset = tiny_dataset() + cls.batch = batch_of(cls.dataset) + + def setUp(self): + torch.manual_seed(0) + self.model = tiny_model(self.dataset) + + def test_outcome_data_must_use_the_models_processors(self): + script(self.model, DEATH) + new_codes = [(0.5 + k, f"LAB//NEW{k}", None) for k in range(8)] + refitted = tiny_dataset(extra=[sample(9, [(0.0, ADMIT, None), *new_codes])]) + with self.assertRaisesRegex(ValueError, "input_processors"): + self.model.estimate_risk(get_dataloader(refitted, batch_size=3), RULE, + num_rollouts=1) + # a plain list of batches has no dataset to compare; out-of-vocabulary + # ids still raise + with self.assertRaisesRegex(ValueError, "outside this model's vocabulary"): + self.model.estimate_risk([batch_of(refitted, size=4)], RULE, + num_rollouts=1) + shared = create_sample_dataset( + [sample(i, [(0.0, ADMIT, None), (30.0, HOME, None)]) for i in range(2)], + input_schema={"timeline": "ethos", "context": "ethos_context"}, + output_schema={}, + input_processors=self.dataset.input_processors, + ) + risk = self.model.estimate_risk(get_dataloader(shared, batch_size=2), RULE, + num_rollouts=1) + self.assertEqual(len(risk["y_prob"]), 2) + + def test_all_positive(self): + script(self.model, DEATH) + risk = self.model.estimate_risk([self.batch], RULE, num_rollouts=2) + self.assertEqual(risk["y_prob"].tolist(), [1.0, 1.0, 1.0]) + self.assertEqual(risk["num_kept"].tolist(), [2, 2, 2]) + self.assertEqual(sorted(risk["patient_id"]), ["p0", "p1", "p2"]) + + def test_all_negative(self): + script(self.model, HOME) + risk = self.model.estimate_risk([self.batch], RULE, num_rollouts=2) + self.assertEqual(risk["y_prob"].tolist(), [0.0, 0.0, 0.0]) + + def test_all_dropped_is_nan(self): + script(self.model, LAB) + risk = self.model.estimate_risk( + [self.batch], RULE, num_rollouts=2, max_new_tokens=2 + ) + self.assertTrue(risk["y_prob"].isnan().all()) + self.assertEqual(risk["num_kept"].tolist(), [0, 0, 0]) + + def test_seed_makes_it_reproducible(self): + options = {"num_rollouts": 4, "max_new_tokens": 8, "seed": 3} + first = self.model.estimate_risk([self.batch], RULE, **options) + second = self.model.estimate_risk([self.batch], RULE, **options) + self.assertTrue(first["y_prob"].nan_to_num(-1).equal(second["y_prob"].nan_to_num(-1))) + + def test_label_key(self): + script(self.model, DEATH) + batch = {**self.batch, "outcome": torch.tensor([[1.0], [0.0], [1.0]])} + risk = self.model.estimate_risk( + [batch], RULE, num_rollouts=1, label_key="outcome" + ) + self.assertEqual(risk["y_true"].tolist(), [1.0, 0.0, 1.0]) + + +class TestTraining(unittest.TestCase): + def test_trainer_and_checkpoint_round_trip(self): + dataset = tiny_dataset() + loader = get_dataloader(dataset, batch_size=3) + torch.manual_seed(0) + model = tiny_model(dataset, n_embd=16) + trainer = Trainer(model=model, enable_logging=False) + batch = next(iter(loader)) + before = model(**batch)["loss"].item() + trainer.train( + train_dataloader=loader, + epochs=6, + optimizer_params={"lr": 0.05}, + max_grad_norm=1.0, + ) + model.eval() + self.assertLess(model(**batch)["loss"].item(), before) + self.assertIn("loss", trainer.evaluate(loader)) + + with tempfile.TemporaryDirectory() as tmp: + path = str(Path(tmp) / "ethos.ckpt") + trainer.save_ckpt(path) + restored = tiny_model(dataset, n_embd=16) + Trainer(model=restored, enable_logging=False).load_ckpt(path) + restored.eval() + self.assertTrue( + torch.allclose(model(**batch)["logit"], restored(**batch)["logit"]) + ) + options = {"num_rollouts": 2, "max_new_tokens": 8, "seed": 1} + self.assertEqual( + model.estimate_risk([batch], RULE, **options)["num_kept"].tolist(), + restored.estimate_risk([batch], RULE, **options)["num_kept"].tolist(), + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/core/test_ethos_context_processor.py b/tests/core/test_ethos_context_processor.py new file mode 100644 index 0000000000..70fb496bfc --- /dev/null +++ b/tests/core/test_ethos_context_processor.py @@ -0,0 +1,120 @@ +"""Tests for EthosContextProcessor. All data here is synthetic.""" + +import math +import tempfile +import unittest +from datetime import datetime +from pathlib import Path + +import torch + +from pyhealth.processors import EthosContextProcessor + +BIRTH = datetime.fromisoformat("1980-01-01") +START = datetime.fromisoformat("2024-01-01") + + +def static(*rows, start=START): + return { + "time": [time for time, _ in rows], + "code": [code for _, code in rows], + "start": start, + } + + +def fitted(*contexts, **kwargs): + processor = EthosContextProcessor(**kwargs) + processor.fit([{"context": context} for context in contexts], "context") + return processor + + +def tokens_of(processor, context): + return processor.decode(processor.process(context)[1]) + + +class TestEthosContextProcessor(unittest.TestCase): + def test_order_and_shape(self): + context = static( + (BIRTH, "MEDS_BIRTH"), + (None, "RACE//WHITE"), + (None, "GENDER//F"), + (BIRTH, "MARITAL//SINGLE"), + ) + processor = fitted(context) + age, tokens = processor.process(context) + self.assertEqual(processor.context_size, 5) + self.assertEqual(processor.age_position, 2) + self.assertEqual(tokens.dtype, torch.long) + self.assertEqual(age.dtype, torch.float64) + self.assertEqual(age.shape, (1,)) + self.assertAlmostEqual(age.item(), (START - BIRTH).days / 365.25) + self.assertEqual( + processor.decode(tokens), + ["GENDER//F", "MARITAL//SINGLE", "", "", "RACE//WHITE"], + ) + + def test_missing_attributes_are_unknown(self): + processor = fitted(static()) + age, tokens = processor.process(static()) + self.assertTrue(math.isnan(age.item())) + self.assertEqual( + processor.decode(tokens), + ["GENDER//UNKNOWN", "MARITAL//UNKNOWN", "", "", "RACE//UNKNOWN"], + ) + + def test_unseen_value_is_unk(self): + processor = fitted(static((None, "GENDER//F"))) + out = tokens_of(processor, static((None, "GENDER//X"))) + self.assertEqual(out[0], "") + + def test_birth_without_a_time_gives_no_age(self): + processor = fitted(static((None, "MEDS_BIRTH"))) + age, _ = processor.process(static((None, "MEDS_BIRTH"))) + self.assertTrue(math.isnan(age.item())) + + def test_changing_attribute_uses_the_latest_known_value(self): + early, late = datetime.fromisoformat("2020-01-01"), datetime.fromisoformat("2030-01-01") + context = static((early, "MARITAL//SINGLE"), (late, "MARITAL//MARRIED")) + processor = fitted(context) + self.assertEqual(tokens_of(processor, context)[1], "MARITAL//SINGLE") + + def test_changing_attribute_before_any_value_is_unknown(self): + later = datetime.fromisoformat("2030-01-01"), datetime.fromisoformat("2031-01-01") + context = static((later[0], "MARITAL//A"), (later[1], "MARITAL//B")) + processor = fitted(context) + self.assertEqual(tokens_of(processor, context)[1], "MARITAL//UNKNOWN") + + def test_single_value_applies_whenever_recorded(self): + context = static((datetime.fromisoformat("2030-01-01"), "MARITAL//SINGLE")) + processor = fitted(context) + self.assertEqual(tokens_of(processor, context)[1], "MARITAL//SINGLE") + + def test_prefixes_must_include_birth(self): + with self.assertRaises(ValueError): + EthosContextProcessor(prefixes=("GENDER",)) + + def test_process_needs_fit(self): + with self.assertRaises(RuntimeError): + EthosContextProcessor().process(static()) + + def test_save_and_load(self): + context = static((BIRTH, "MEDS_BIRTH"), (None, "GENDER//F")) + processor = fitted(context, prefixes=("MEDS_BIRTH", "GENDER")) + with tempfile.TemporaryDirectory() as tmp: + path = str(Path(tmp) / "context.json") + processor.save(path) + restored = EthosContextProcessor() + restored.load(path) + self.assertEqual(restored.prefixes, processor.prefixes) + self.assertTrue( + torch.equal(restored.process(context)[1], processor.process(context)[1]) + ) + + def test_schema_matches_the_output(self): + processor = fitted(static()) + self.assertEqual(len(processor.schema()), len(processor.process(static()))) + self.assertTrue(processor.is_token()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/core/test_ethos_processor.py b/tests/core/test_ethos_processor.py index faff7c7dc6..3aa2cc9289 100644 --- a/tests/core/test_ethos_processor.py +++ b/tests/core/test_ethos_processor.py @@ -374,6 +374,36 @@ def test_sample_dataset_and_batching(self): self.assertEqual(time.shape, (3, 5)) self.assertEqual(int((tokens == 0).sum()), 7) + def test_interval_estimates_are_mean_hours_per_token(self): + processor = EthosProcessor() + timelines = [ + timeline((0, "A", None), (10, "A", None)), + timeline((0, "A", None), (14, "A", None)), + ] + processor.fit([{"timeline": t} for t in timelines], "timeline") + self.assertAlmostEqual( + processor.interval_estimates["5m-15m"], (10 + 14) / 2 / 60 + ) + + def test_interval_estimates_split_repeated_tokens(self): + days = 24 * 60 + processor = fitted((0, "A", None), (400 * days, "A", None)) + self.assertAlmostEqual(processor.interval_estimates["=6mt"], 200 * 24.0) + + def test_interval_estimates_fall_back_to_the_lower_bound(self): + processor = fitted((0, "A", None)) + self.assertEqual(len(processor.interval_estimates), 19) + self.assertAlmostEqual(processor.interval_estimates["2h-3h"], 2.0) + + def test_interval_estimates_survive_save_and_load(self): + processor = fitted((0, "A", None), (10, "A", None)) + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, "ethos.json") + processor.save(path) + restored = EthosProcessor() + restored.load(path) + self.assertEqual(restored.interval_estimates, processor.interval_estimates) + if __name__ == "__main__": unittest.main() diff --git a/tests/core/test_ethos_tasks.py b/tests/core/test_ethos_tasks.py new file mode 100644 index 0000000000..91511b79e4 --- /dev/null +++ b/tests/core/test_ethos_tasks.py @@ -0,0 +1,284 @@ +"""Tests for EthosTimelineMEDS, EthosOutcomeMEDS and EthosRolloutRule. + +Most tests run the tasks directly on an in-memory ``Patient``; +``TestSetTask`` runs them through ``MEDSDataset.set_task`` on synthetic +Parquet. All data here is synthetic. +""" + +import shutil +import tempfile +import unittest +from datetime import datetime, timedelta +from pathlib import Path + +import polars as pl + +from pyhealth.data import Patient +from pyhealth.datasets import MEDSDataset +from pyhealth.processors import EthosContextProcessor, EthosProcessor +from pyhealth.tasks import ( + EthosOutcomeMEDS, + EthosRolloutRule, + EthosTimelineMEDS, + HospitalReadmissionMEDS, + ICUAdmissionMEDS, + ProlongedLengthOfStayMEDS, +) + +T0 = datetime.fromisoformat("2024-01-01T08:00:00") +ADMIT = "HOSPITAL_ADMISSION//ER" +HOME = "HOSPITAL_DISCHARGE//HOME" +DIED = "HOSPITAL_DISCHARGE//DIED" +ICU = "ICU_ADMISSION//MICU" +DEATH = "MEDS_DEATH" +GOT = "token_of_interest" + + +def patient(*rows): + """Rows are ``(hours or None, code, hadm_id, value)``.""" + frame = pl.DataFrame( + { + "patient_id": ["1"] * len(rows), + "event_type": ["meds"] * len(rows), + "timestamp": pl.Series( + [None if r[0] is None else T0 + timedelta(hours=r[0]) for r in rows], + dtype=pl.Datetime("ms"), + ), + "meds/code": pl.Series([r[1] for r in rows], dtype=pl.String), + "meds/hadm_id": pl.Series([r[2] for r in rows], dtype=pl.Int64), + "meds/numeric_value": pl.Series([r[3] for r in rows], dtype=pl.Float64), + } + ) + return Patient(patient_id="1", data_source=frame) + + +STAYS = patient( + (None, "GENDER//F", None, None), + (-1000.0, "MEDS_BIRTH", None, None), + (-5.0, "LAB//EARLY", None, 3.0), + (0.0, ADMIT, 1, None), + (2.0, ICU, 1, None), + (3.0, "LAB//DURING", 1, 7.0), + (48.0, HOME, 1, None), + (48.0, "DX//AT_DISCHARGE", 1, None), + (96.0, ADMIT, 2, None), + (400.0, DIED, 2, None), + (400.0, DEATH, None, None), +) + + +class TestEthosTimelineMEDS(unittest.TestCase): + def test_whole_timeline_and_static_split(self): + samples = EthosTimelineMEDS()(STAYS) + self.assertEqual(len(samples), 1) + sample = samples[0] + self.assertEqual(sample["patient_id"], "1") + self.assertEqual(len(sample["timeline"]["code"]), 9) + self.assertIn(DEATH, sample["timeline"]["code"]) + self.assertNotIn("GENDER//F", sample["timeline"]["code"]) + self.assertEqual(sample["timeline"]["numeric_value"][0], 3.0) + self.assertEqual( + sorted(sample["context"]["code"]), ["GENDER//F", "MEDS_BIRTH"] + ) + self.assertEqual(sample["context"]["start"], T0 + timedelta(hours=-5)) + + def test_patient_with_only_static_rows_has_no_sample(self): + only_static = patient((None, "GENDER//F", None, None)) + self.assertEqual(EthosTimelineMEDS()(only_static), []) + + +class TestEthosOutcomeMEDS(unittest.TestCase): + def test_keeps_the_cohort_labels_and_codes_of_the_outcome_task(self): + for task_class in ( + ICUAdmissionMEDS, + HospitalReadmissionMEDS, + ProlongedLengthOfStayMEDS, + ): + with self.subTest(task=task_class.__name__): + outcomes = task_class()(STAYS) + samples = EthosOutcomeMEDS(task_class)(STAYS) + label = next(iter(task_class.output_schema)) + self.assertEqual(len(samples), len(outcomes)) + for sample, outcome in zip(samples, outcomes): + self.assertNotIn("codes", sample) + self.assertEqual(sample[label], outcome[label]) + self.assertEqual(sample["hadm_id"], outcome["hadm_id"]) + rows = sample["timeline"]["code"] + sample["context"]["code"] + self.assertEqual(sorted(rows), sorted(outcome["codes"])) + + def test_admission_cut_excludes_the_stay(self): + sample = EthosOutcomeMEDS(ICUAdmissionMEDS)(STAYS)[0] + self.assertEqual(sample["timeline"]["code"], ["LAB//EARLY", ADMIT]) + self.assertEqual(sample["timeline"]["numeric_value"], [3.0, None]) + + def test_discharge_cut_excludes_what_follows(self): + sample = EthosOutcomeMEDS(HospitalReadmissionMEDS)(STAYS)[0] + codes = sample["timeline"]["code"] + self.assertEqual(codes[-2:], [HOME, "DX//AT_DISCHARGE"]) + self.assertNotIn(DIED, codes) + self.assertNotIn(DEATH, codes) + + def test_patient_without_a_stay_has_no_sample(self): + lab_only = patient((0.0, "LAB//X", None, 1.0)) + self.assertEqual(EthosOutcomeMEDS(ICUAdmissionMEDS)(lab_only), []) + + def test_names_and_schema(self): + task = EthosOutcomeMEDS(ProlongedLengthOfStayMEDS, threshold_days=7.0) + self.assertEqual(task.task_name, "EthosProlongedLengthOfStayMEDS") + self.assertEqual(task.output_schema, {"prolonged_los": "binary"}) + self.assertEqual(task.input_schema, EthosTimelineMEDS.input_schema) + + def test_rejects_other_tasks(self): + with self.assertRaises(ValueError): + EthosOutcomeMEDS(EthosTimelineMEDS) + + +class TestRolloutRules(unittest.TestCase): + def test_icu_admission(self): + rule = EthosOutcomeMEDS(ICUAdmissionMEDS).rule + self.assertIs(rule.score(ICU, GOT, 1.0), True) + self.assertIs(rule.score(DEATH, GOT, 1.0), True) + self.assertIs(rule.score(DIED, GOT, 1.0), True) + self.assertIs(rule.score(HOME, GOT, 1.0), False) + self.assertIsNone(rule.score("TIMELINE_END", GOT, 1.0)) + self.assertIsNone(rule.score("LAB//X", "time_limit", 800.0)) + self.assertEqual(rule.time_limit_days, 730.5) + + def test_icu_admission_without_deaths(self): + rule = EthosOutcomeMEDS(ICUAdmissionMEDS, death_as_positive=False).rule + self.assertIs(rule.score(ICU, GOT, 1.0), True) + self.assertIs(rule.score(DEATH, GOT, 1.0), False) + self.assertIs(rule.score(DIED, GOT, 1.0), False) + self.assertEqual( + rule.stop_prefixes, + EthosOutcomeMEDS(ICUAdmissionMEDS).rule.stop_prefixes, + ) + + def test_prolonged_stay_threshold_is_inclusive(self): + rule = EthosOutcomeMEDS(ProlongedLengthOfStayMEDS).rule + self.assertIs(rule.score(HOME, GOT, 10.0), True) + self.assertIs(rule.score(DEATH, GOT, 11.0), True) + self.assertIs(rule.score(HOME, GOT, 9.9), False) + self.assertIs(rule.score(DEATH, GOT, 9.9), False) + self.assertIsNone(rule.score("TIMELINE_END", GOT, 11.0)) + custom = EthosOutcomeMEDS(ProlongedLengthOfStayMEDS, threshold_days=3.0).rule + self.assertIs(custom.score(HOME, GOT, 3.0), True) + + def test_readmission(self): + rule = EthosOutcomeMEDS(HospitalReadmissionMEDS).rule + self.assertEqual(rule.time_limit_days, 30.0) + self.assertIs(rule.score(ADMIT, GOT, 1.0), True) + self.assertIs(rule.score(DEATH, GOT, 1.0), True) + self.assertIs(rule.score("TIMELINE_END", GOT, 1.0), False) + self.assertIs(rule.score("LAB//X", "time_limit", 31.0), False) + custom = EthosOutcomeMEDS(HospitalReadmissionMEDS, window_days=7.0).rule + self.assertEqual(custom.time_limit_days, 7.0) + + def test_full_followup_does_not_change_the_rollout(self): + self.assertEqual( + EthosOutcomeMEDS(HospitalReadmissionMEDS).rule, + EthosOutcomeMEDS(HospitalReadmissionMEDS, require_full_followup=True).rule, + ) + + def test_failed_rollouts_are_always_dropped(self): + rule = EthosRolloutRule(stop_prefixes=("X",), keep_time_limited=True) + self.assertIsNone(rule.score(None, "key_error", 0.0)) + self.assertIsNone(rule.score("X", "token_limit", 0.0)) + + +_CONFIG = """version: "1.0" +tables: + meds: + file_path: "data" + patient_id: "subject_id" + timestamp: "time" + attributes: + - "code" + - "numeric_value" + - "hadm_id" +""" + + +class TestSetTask(unittest.TestCase): + """Both tasks through MEDSDataset, so cache keys and processors are real.""" + + @classmethod + def setUpClass(cls): + cls.temp_dir = Path(tempfile.mkdtemp()) + root = cls.temp_dir / "meds" + (root / "data").mkdir(parents=True) + config_path = cls.temp_dir / "meds_hadm.yaml" + config_path.write_text(_CONFIG) + rows = [ # (subject, hours or None, code, hadm_id, value) + (1, None, "GENDER//F", None, None), + (1, -1e5, "MEDS_BIRTH", None, None), + (1, 0.0, ADMIT, 10, None), + (1, 2.0, "LAB//A", 10, 1.0), + (1, 5.0, ICU, 10, None), + (1, 264.0, HOME, 10, None), + (1, 480.0, ADMIT, 11, None), + (1, 483.0, "LAB//A", 11, 3.0), + (1, 528.0, DIED, 11, None), + (2, None, "GENDER//M", None, None), + (2, 0.0, ADMIT, 20, None), + (2, 3.0, "LAB//A", 20, 2.0), + (2, 48.0, HOME, 20, None), + ] + times = [None if r[1] is None else T0 + timedelta(hours=r[1]) for r in rows] + pl.DataFrame( + { + "subject_id": pl.Series([r[0] for r in rows], dtype=pl.Int64), + "time": pl.Series(times, dtype=pl.Datetime("us")), + "code": pl.Series([r[2] for r in rows], dtype=pl.String), + "numeric_value": pl.Series([r[4] for r in rows], dtype=pl.Float32), + "hadm_id": pl.Series([r[3] for r in rows], dtype=pl.Int64), + } + ).write_parquet(root / "data" / "0.parquet") + cls.dataset = MEDSDataset( + root=str(root), + config_path=str(config_path), + cache_dir=cls.temp_dir / "cache", + num_workers=1, + ) + cls.timelines = cls.dataset.set_task(EthosTimelineMEDS(), num_workers=1) + + @classmethod + def tearDownClass(cls): + cls.timelines.close() + shutil.rmtree(cls.temp_dir, ignore_errors=True) + + def outcome_labels(self, **options): + task = EthosOutcomeMEDS(ICUAdmissionMEDS, **options) + samples = self.dataset.set_task( + task, num_workers=1, input_processors=self.timelines.input_processors + ) + try: + for key in ("timeline", "context"): + self.assertEqual( + samples.input_processors[key].vocab.token_to_id, + self.timelines.input_processors[key].vocab.token_to_id, + ) + return sorted(int(samples[i]["icu_admission"]) for i in range(len(samples))) + finally: + samples.close() + + def test_timeline_processors_are_fitted(self): + self.assertEqual(len(self.timelines), 2) + timeline = self.timelines.input_processors["timeline"] + context = self.timelines.input_processors["context"] + self.assertIsInstance(timeline, EthosProcessor) + self.assertIsInstance(context, EthosContextProcessor) + self.assertIn("LAB//A", timeline.vocab.token_to_id) + self.assertNotIn("GENDER//F", timeline.vocab.token_to_id) + self.assertIn("GENDER//F", context.vocab.token_to_id) + _, tokens = self.timelines[0]["timeline"] + self.assertEqual(timeline.decode(tokens)[-1], "TIMELINE_END") + + def test_outcome_options_reach_the_cache_key(self): + # Stays: ICU (10), death without ICU (11), neither (20). + self.assertEqual(self.outcome_labels(), [0, 1, 1]) + self.assertEqual(self.outcome_labels(death_as_positive=False), [0, 0, 1]) + + +if __name__ == "__main__": + unittest.main()