From c21db4f375bf71b0c024153789bc2394b5eba2a3 Mon Sep 17 00:00:00 2001 From: solarsys Date: Tue, 3 Nov 2026 23:58:31 -0800 Subject: [PATCH 1/6] Add APRICOT-M ICU acuity model and MIMIC-IV acuity task APRICOT-M (Contreras et al., Nature Communications 2025) predicts, every 4 hours of an ICU stay, the next 4 hours' acuity state (discharge, stable, unstable, deceased), stable/unstable transitions and the stop or onset of mechanical ventilation, vasopressors and CRRT, from the past 4 hours of clinical events as (time, variable, value) triplets. - pyhealth/tasks/acuity_mimic4.py: ICUAcuityMIMIC4, built on the YAIB MIMIC-IV features; therapy intervals from procedureevents/inputevents. - pyhealth/models/apricotm.py: APRICOTM, with a pure-PyTorch selective state-space (Mamba) mixer and a chunked log-space parallel scan, so no CUDA mamba_ssm is needed. - yaib_mimic4: _measurements can also return fractional hours. - Tests, docs pages and an example notebook run on the MIMIC-IV demo. Clean reimplementation from the paper: the authors' code is GPL-3.0 and was only read to confirm details; nothing was copied. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BdtuVKBLhWpYbhTQbaZaTt --- docs/api/models.rst | 1 + docs/api/models/pyhealth.models.APRICOTM.rst | 53 ++ docs/api/tasks.rst | 1 + .../tasks/pyhealth.tasks.ICUAcuityMIMIC4.rst | 14 + examples/apricotm_mimic4_acuity.ipynb | 397 +++++++++++++++ pyhealth/models/__init__.py | 1 + pyhealth/models/apricotm.py | 479 ++++++++++++++++++ pyhealth/tasks/__init__.py | 1 + pyhealth/tasks/acuity_mimic4.py | 385 ++++++++++++++ pyhealth/tasks/yaib_mimic4.py | 23 +- tests/core/test_apricotm.py | 350 +++++++++++++ 11 files changed, 1701 insertions(+), 4 deletions(-) create mode 100644 docs/api/models/pyhealth.models.APRICOTM.rst create mode 100644 docs/api/tasks/pyhealth.tasks.ICUAcuityMIMIC4.rst create mode 100644 examples/apricotm_mimic4_acuity.ipynb create mode 100644 pyhealth/models/apricotm.py create mode 100644 pyhealth/tasks/acuity_mimic4.py create mode 100644 tests/core/test_apricotm.py diff --git a/docs/api/models.rst b/docs/api/models.rst index 9d63abb567..040eb3d4a0 100644 --- a/docs/api/models.rst +++ b/docs/api/models.rst @@ -275,6 +275,7 @@ API Reference models/pyhealth.models.survival_mdn models/pyhealth.models.TrajSurv models/pyhealth.models.KnowRare + models/pyhealth.models.APRICOTM models/pyhealth.models.ProtoECGNet models/pyhealth.models.HeartLang models/pyhealth.models.APN diff --git a/docs/api/models/pyhealth.models.APRICOTM.rst b/docs/api/models/pyhealth.models.APRICOTM.rst new file mode 100644 index 0000000000..07973e2698 --- /dev/null +++ b/docs/api/models/pyhealth.models.APRICOTM.rst @@ -0,0 +1,53 @@ +pyhealth.models.APRICOTM +======================== + +Overview +-------- + +APRICOT-M (Contreras et al., `Real-time prediction of intensive care unit +patient acuity and therapy requirements using state-space modelling +`_, Nature Communications 16, +7315, 2025) predicts, every 4 hours of an ICU stay, the patient's acuity in +the next 4 hours (discharge, stable, unstable or deceased), transitions +between stable and unstable, and the onset or stop of mechanical +ventilation, vasopressors and continuous renal replacement therapy. + +The model reads the clinical events of the last 4 hours as (time, variable, +value) triplets, so sparse, irregular measurements need no resampling or +imputation. Time and value pass through position-wise layers, the variable +through an embedding; a stack of Mamba (selective state-space) blocks +contextualizes the events, top-k pooling over time and an MLP summarize +them, a static-feature embedding is added, and one head per label gives its +probability. + +This is a clean reimplementation from the paper. The authors' code +(https://github.com/iheallab/apricotM) is GPL-3.0, so none of it was +copied; it was only read to confirm details. The Mamba blocks are written in +pure PyTorch (a chunked parallel selective scan), so the CUDA ``mamba_ssm`` +package is not needed and the model runs on CPU. + +Inputs and outputs +------------------ + +The input is a ``sequence_v2`` series with one token and one value per +event, such as the ``events`` field of +:class:`~pyhealth.tasks.ICUAcuityMIMIC4`, plus an optional static tensor +field. The label is a tensor of ``K`` binary labels (12 for that task, in the +order of ``ICUAcuityMIMIC4.LABELS``). ``mode`` is ``"multilabel"``; the model +returns ``logit``, ``y_prob`` and, with labels, ``loss`` (binary +cross-entropy) and ``y_true``. Use ``set_pos_weight("balanced", +train_samples)`` for the class weighting of the paper. The example notebook +``examples/apricotm_mimic4_acuity.ipynb`` trains it on MIMIC-IV. + +API +--- + +.. autoclass:: pyhealth.models.APRICOTM + :members: + :show-inheritance: + +.. autoclass:: pyhealth.models.SelectiveSSM + :members: + :show-inheritance: + +.. autofunction:: pyhealth.models.apricotm.selective_scan diff --git a/docs/api/tasks.rst b/docs/api/tasks.rst index 25d56df410..0b7837c4ab 100644 --- a/docs/api/tasks.rst +++ b/docs/api/tasks.rst @@ -250,4 +250,5 @@ Available Tasks Cancer Survival Prediction (TCGA) In-Hospital Survival (MIMIC-IV) Rare-Condition ICU Mortality (KnowRare, MIMIC-IV) + ICU Acuity and Therapies (MIMIC-IV) Cancer Mutation Burden (TCGA) diff --git a/docs/api/tasks/pyhealth.tasks.ICUAcuityMIMIC4.rst b/docs/api/tasks/pyhealth.tasks.ICUAcuityMIMIC4.rst new file mode 100644 index 0000000000..b2c268ab9f --- /dev/null +++ b/docs/api/tasks/pyhealth.tasks.ICUAcuityMIMIC4.rst @@ -0,0 +1,14 @@ +pyhealth.tasks.ICUAcuityMIMIC4 +============================== + +Real-time ICU acuity on MIMIC-IV, the setting of APRICOT-M (Contreras et al., +Nature Communications 2025): every 4 hours, the events of the past 4 hours +predict the next 4 hours' acuity state (discharge, stable, unstable, +deceased), stable/unstable transitions and the stop or onset of mechanical +ventilation, vasopressors and CRRT. Pairs with +:class:`~pyhealth.models.APRICOTM`. + +.. autoclass:: pyhealth.tasks.ICUAcuityMIMIC4 + :members: + :undoc-members: + :show-inheritance: diff --git a/examples/apricotm_mimic4_acuity.ipynb b/examples/apricotm_mimic4_acuity.ipynb new file mode 100644 index 0000000000..5b980b72ef --- /dev/null +++ b/examples/apricotm_mimic4_acuity.ipynb @@ -0,0 +1,397 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "60cb63c6", + "metadata": {}, + "source": [ + "# APRICOT-M in PyHealth: real-time ICU acuity and therapy prediction\n", + "\n", + "\"Open\n", + "\n", + "This notebook runs the prediction setting of **APRICOT-M** (Contreras et al., *Real-time prediction of intensive care unit patient acuity and therapy requirements using state-space modelling*, Nature Communications 16, 7315, 2025, [doi:10.1038/s41467-025-62121-1](https://doi.org/10.1038/s41467-025-62121-1); authors' code: [iheallab/apricotM](https://github.com/iheallab/apricotM)) with PyHealth:\n", + "\n", + "- **Task** (`ICUAcuityMIMIC4`): every 4 hours of an ICU stay, the clinical events of the past 4 hours and the static data predict 12 outcomes for the next 4 hours: the acuity state (discharge, stable, unstable, deceased), the transitions unstable→stable and stable→unstable, and the stop and onset of mechanical ventilation (MV), vasopressors (VP) and continuous renal replacement therapy (CRRT). An interval is *unstable* when MV, a vasopressor, CRRT or a massive transfusion is present in it.\n", + "- **Model** (`APRICOTM`): the events are (time, variable, value) triplets, embedded without resampling or imputation, contextualized by Mamba (selective state-space) blocks, summarized by top-k pooling, fused with a static embedding, with one head per outcome.\n", + "- **Baseline**: logistic regression on per-window statistics (min, max, mean, last value and missingness of each variable, plus static features), the feature set the paper uses for its CatBoost baseline.\n", + "- **Metrics**: AUROC and AUPRC per outcome, as in the paper's Table 2.\n", + "\n", + "The PyHealth model is a clean reimplementation from the paper (the authors' code is GPL-3.0 and was only read to confirm details). Its Mamba blocks are pure PyTorch, so it runs on CPU, without the CUDA `mamba_ssm` package.\n", + "\n", + "Part 1 runs end to end on the open **MIMIC-IV Clinical Database Demo** (100 patients, no credentials). It is a **smoke test**: it shows that the pipeline runs, but the test split has only about 20 patients and a handful of positives for most outcomes, so its numbers say nothing about how well the model works. Part 2 runs the same code on the full, credentialed MIMIC-IV." + ] + }, + { + "cell_type": "markdown", + "id": "fa9c5362", + "metadata": {}, + "source": [ + "## Setup\n", + "\n", + "Until the PR is merged, install PyHealth from its branch. After the merge, install from `sunlabuiuc/PyHealth` master instead (`pip install \"git+https://github.com/sunlabuiuc/PyHealth\"`), or `pip install pyhealth` once it is released. The cell only installs on Colab." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "a7faface", + "metadata": {}, + "outputs": [], + "source": [ + "import sys\n", + "\n", + "if \"google.colab\" in sys.modules:\n", + " # APRICOT-M is on PyHealth's master branch; after the next PyPI release,\n", + " # `pip install pyhealth` is enough.\n", + " !pip install -q \"git+https://github.com/sunlabuiuc/PyHealth\"" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "22962904", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "device: cpu\n" + ] + } + ], + "source": [ + "import os\n", + "import time\n", + "import urllib.request\n", + "\n", + "import numpy as np\n", + "import torch\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.metrics import average_precision_score, roc_auc_score\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "from pyhealth.datasets import MIMIC4EHRDataset, PatientSplit, get_dataloader\n", + "from pyhealth.models import APRICOTM\n", + "from pyhealth.tasks import ICUAcuityMIMIC4\n", + "\n", + "device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n", + "torch.manual_seed(0)\n", + "np.random.seed(0)\n", + "print(\"device:\", device)" + ] + }, + { + "cell_type": "markdown", + "id": "f7d88819", + "metadata": {}, + "source": [ + "## Part 1: the open MIMIC-IV demo\n", + "\n", + "Download the demo tables the task needs from PhysioNet (open access, about 10 MB)." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "9ad32316", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "downloaded 9 tables\n" + ] + } + ], + "source": [ + "DEMO_ROOT = \"mimic-iv-demo-2.2\"\n", + "BASE = \"https://physionet.org/files/mimic-iv-demo/2.2/\"\n", + "TABLES = [\"hosp/admissions\", \"hosp/patients\", \"hosp/labevents\", \"hosp/d_labitems\",\n", + " \"icu/icustays\", \"icu/chartevents\", \"icu/outputevents\",\n", + " \"icu/procedureevents\", \"icu/inputevents\"]\n", + "for table in TABLES:\n", + " path = os.path.join(DEMO_ROOT, table + \".csv.gz\")\n", + " os.makedirs(os.path.dirname(path), exist_ok=True)\n", + " if not os.path.exists(path):\n", + " urllib.request.urlretrieve(BASE + table + \".csv.gz\", path)\n", + "print(\"downloaded\", len(TABLES), \"tables\")" + ] + }, + { + "cell_type": "markdown", + "id": "2d0c889f", + "metadata": {}, + "source": [ + "### Helpers\n", + "\n", + "`run` builds the samples with the processors fitted on the training patients only (`set_task(..., split=PatientSplit(...))`: 70% train, 15% validation, 15% test, by patient), trains APRICOT-M with the authors' settings (width 92, 2 Mamba blocks, top-5 pooling, dropout 0.2, Adam with learning rate 3e-4 and weight decay 1e-5, batch size 128, class weights from the training labels) and keeps the epoch with the best mean validation AUROC. The logistic regression baseline gets the same split and class weighting.\n", + "\n", + "An outcome without both classes in the test split has no AUROC; it is shown as `n/a`." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "1d66d64b", + "metadata": {}, + "outputs": [], + "source": [ + "LABELS = ICUAcuityMIMIC4.LABELS\n", + "TABLES_NEEDED = [\"labevents\", \"chartevents\", \"outputevents\",\n", + " \"procedureevents\", \"inputevents\", \"admissions\"]\n", + "\n", + "\n", + "def auroc_auprc(y_true, y_prob):\n", + " \"\"\"Per-outcome AUROC and AUPRC (NaN when a class is missing).\"\"\"\n", + " scores = {}\n", + " for k, name in enumerate(LABELS):\n", + " y = y_true[:, k]\n", + " if 0 < y.sum() < len(y):\n", + " scores[name] = (roc_auc_score(y, y_prob[:, k]),\n", + " average_precision_score(y, y_prob[:, k]), int(y.sum()))\n", + " else:\n", + " scores[name] = (float(\"nan\"), float(\"nan\"), int(y.sum()))\n", + " return scores\n", + "\n", + "\n", + "@torch.no_grad()\n", + "def predict(model, loader):\n", + " model.eval()\n", + " y_true, y_prob = [], []\n", + " for batch in loader:\n", + " out = model(**batch)\n", + " y_true.append(out[\"y_true\"].cpu())\n", + " y_prob.append(out[\"y_prob\"].cpu())\n", + " return torch.cat(y_true).numpy(), torch.cat(y_prob).numpy()\n", + "\n", + "\n", + "def mean_auroc(scores):\n", + " values = [auc for auc, _, _ in scores.values() if not np.isnan(auc)]\n", + " return float(np.mean(values)) if values else float(\"nan\")\n", + "\n", + "\n", + "def train_apricotm(train_part, train_dl, val_dl, epochs, patience=5):\n", + " model = APRICOTM(train_part, static_key=\"static\").to(device)\n", + " model.set_pos_weight(\"balanced\", train_part)\n", + " optimizer = torch.optim.Adam(model.parameters(), lr=3e-4, weight_decay=1e-5)\n", + " best, best_state, waited = -1.0, None, 0\n", + " for epoch in range(epochs):\n", + " model.train()\n", + " start, losses = time.time(), []\n", + " for batch in train_dl:\n", + " optimizer.zero_grad()\n", + " loss = model(**batch)[\"loss\"]\n", + " loss.backward()\n", + " optimizer.step()\n", + " losses.append(loss.item())\n", + " val = mean_auroc(auroc_auprc(*predict(model, val_dl)))\n", + " print(f\"epoch {epoch + 1}: train loss {np.mean(losses):.3f}, \"\n", + " f\"val mean AUROC {val:.3f} ({time.time() - start:.0f}s)\")\n", + " if val > best:\n", + " best, waited = val, 0\n", + " best_state = {k: v.detach().clone() for k, v in model.state_dict().items()}\n", + " else:\n", + " waited += 1\n", + " if waited >= patience:\n", + " break\n", + " model.load_state_dict(best_state)\n", + " return model\n", + "\n", + "\n", + "def window_statistics(part):\n", + " \"\"\"Min, max, mean, last value and missingness per variable, plus static.\"\"\"\n", + " vocab = part.input_processors[\"events\"].vocab(0)\n", + " n_vars = len(vocab)\n", + " rows, labels = [], []\n", + " for i in range(len(part)):\n", + " sample = part[i]\n", + " tokens, values = sample[\"events\"][0], sample[\"events\"][1].reshape(-1)\n", + " stats = np.zeros((n_vars, 5))\n", + " stats[:, 4] = 1.0 # missing\n", + " for v in torch.unique(tokens).tolist():\n", + " x = values[tokens == v].numpy()\n", + " stats[v] = [x.min(), x.max(), x.mean(), x[-1], 0.0]\n", + " rows.append(np.concatenate([stats.ravel(), sample[\"static\"].numpy()]))\n", + " labels.append(sample[\"acuity\"].numpy())\n", + " return np.array(rows), np.array(labels)\n", + "\n", + "\n", + "def logistic_baseline(parts):\n", + " (x_train, y_train), (x_test, y_test) = (window_statistics(parts[0]),\n", + " window_statistics(parts[2]))\n", + " scaler = StandardScaler().fit(x_train)\n", + " y_prob = np.zeros_like(y_test)\n", + " for k in range(len(LABELS)):\n", + " if 0 < y_train[:, k].sum() < len(y_train):\n", + " clf = LogisticRegression(max_iter=2000, class_weight=\"balanced\")\n", + " clf.fit(scaler.transform(x_train), y_train[:, k])\n", + " y_prob[:, k] = clf.predict_proba(scaler.transform(x_test))[:, 1]\n", + " return auroc_auprc(y_test, y_prob)\n", + "\n", + "\n", + "def run(root, cache_dir, epochs, batch_size=128, num_workers=1):\n", + " dataset = MIMIC4EHRDataset(root=root, tables=TABLES_NEEDED, cache_dir=cache_dir,\n", + " num_workers=num_workers)\n", + " parts = dataset.set_task(ICUAcuityMIMIC4(), num_workers=num_workers,\n", + " split=PatientSplit((0.7, 0.15, 0.15), seed=0))\n", + " for name, part in zip((\"train\", \"val\", \"test\"), parts):\n", + " stays = len({part[i][\"stay_id\"] for i in range(len(part))})\n", + " print(f\"{name}: {len(part)} windows from {stays} ICU stays\")\n", + " train_dl, val_dl, test_dl = (\n", + " get_dataloader(p, batch_size=batch_size, shuffle=(i == 0))\n", + " for i, p in enumerate(parts)\n", + " )\n", + " start = time.time()\n", + " model = train_apricotm(parts[0], train_dl, val_dl, epochs)\n", + " print(f\"APRICOT-M trained in {time.time() - start:.0f}s\")\n", + " return {\"APRICOT-M\": auroc_auprc(*predict(model, test_dl)),\n", + " \"LogReg (window stats)\": logistic_baseline(parts)}\n", + "\n", + "\n", + "def show(results):\n", + " names = list(results)\n", + " print(\"outcome\".ljust(20) + \"test +\".rjust(7)\n", + " + \"\".join(f\"{n[:22]:>24}\" for n in names))\n", + " print(\" \" * 27 + \"\".join(f\"{'AUROC AUPRC':>24}\" for _ in names))\n", + " for label in LABELS:\n", + " positives = results[names[0]][label][2]\n", + " row = label.ljust(20) + str(positives).rjust(7)\n", + " for n in names:\n", + " auc, ap, _ = results[n][label]\n", + " row += (\"n/a\".rjust(24) if np.isnan(auc)\n", + " else f\"{auc:>17.2f}{ap:>7.2f}\")\n", + " print(row)" + ] + }, + { + "cell_type": "markdown", + "id": "21b1f133", + "metadata": {}, + "source": [ + "### Train and evaluate on the demo\n", + "\n", + "The demo gives about 3,000 four-hour windows from about 130 ICU stays. Ten epochs took about 15 minutes on a laptop CPU (much less on a GPU)." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "c01cdcf4", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": "train: 1715 windows from 91 ICU stays\nval: 485 windows from 19 ICU stays\ntest: 816 windows from 26 ICU stays\nepoch 1: train loss 1.247, val mean AUROC 0.640 (124s)\nepoch 2: train loss 1.225, val mean AUROC 0.695 (104s)\nepoch 3: train loss 1.192, val mean AUROC 0.706 (118s)\nepoch 4: train loss 1.158, val mean AUROC 0.716 (95s)\nepoch 5: train loss 1.168, val mean AUROC 0.698 (88s)\nepoch 6: train loss 1.108, val mean AUROC 0.705 (85s)\nepoch 7: train loss 1.090, val mean AUROC 0.719 (104s)\nepoch 8: train loss 1.042, val mean AUROC 0.711 (88s)\nepoch 9: train loss 1.038, val mean AUROC 0.703 (86s)\nepoch 10: train loss 0.991, val mean AUROC 0.726 (81s)\nAPRICOT-M trained in 973s\noutcome test + APRICOT-M LogReg (window stats)\n AUROC AUPRC AUROC AUPRC\ndischarge 25 0.76 0.09 0.70 0.06\nstable 352 0.73 0.66 0.77 0.64\nunstable 438 0.74 0.73 0.79 0.86\ndeceased 1 0.97 0.04 1.00 1.00\nunstable_to_stable 19 0.63 0.05 0.61 0.07\nstable_to_unstable 7 0.54 0.01 0.72 0.02\nmv_stop 12 0.74 0.11 0.78 0.13\nmv_onset 1 0.46 0.00 0.03 0.00\nvp_stop 18 0.59 0.05 0.44 0.02\nvp_onset 13 0.58 0.04 0.66 0.07\ncrrt_stop 3 0.19 0.00 0.29 0.00\ncrrt_onset 3 0.68 0.01 0.24 0.00\n" + } + ], + "source": [ + "demo_results = run(DEMO_ROOT, cache_dir=\"cache-demo\", epochs=10)\n", + "show(demo_results)" + ] + }, + { + "cell_type": "markdown", + "id": "aab170d7", + "metadata": {}, + "source": [ + "## Part 2: full MIMIC-IV (credentialed)\n", + "\n", + "MIMIC-IV requires PhysioNet credentialing ([physionet.org/content/mimiciv](https://physionet.org/content/mimiciv/)). Point `MIMIC4_ROOT` at your copy (the folder with `hosp/` and `icu/`), e.g. on a mounted Google Drive, and use a GPU runtime. Building the event table reads `chartevents` once and caches it in `cache_dir`; MIMIC-IV gives several hundred thousand windows, so expect a long first run. The authors train up to 100 epochs with early stopping." + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "fd03d5ba", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Set MIMIC4_ROOT to your MIMIC-IV folder to run Part 2.\n" + ] + } + ], + "source": [ + "MIMIC4_ROOT = \"/content/drive/MyDrive/mimic-iv/2.2\" # change me\n", + "EPOCHS = 100\n", + "\n", + "if os.path.isdir(MIMIC4_ROOT):\n", + " full_results = run(MIMIC4_ROOT, cache_dir=\"cache-mimic4\", epochs=EPOCHS,\n", + " num_workers=4)\n", + " show(full_results)\n", + "else:\n", + " print(\"Set MIMIC4_ROOT to your MIMIC-IV folder to run Part 2.\")" + ] + }, + { + "cell_type": "markdown", + "id": "3cdbd7ee", + "metadata": {}, + "source": [ + "## Comparison with the paper\n", + "\n", + "APRICOT-M's reported AUROC for 4-hour predictions (Table 2 of the paper; median of 100 bootstrap samples). *Development* is the validation split of the training cohort (University of Florida Health 2014-2017 and 54 eICU hospitals); *External* is MIMIC-IV plus the other 143 eICU hospitals, never seen in training.\n", + "\n", + "| Outcome | Development | External | Prospective | This notebook |\n", + "|---|---|---|---|---|\n", + "| Discharge | 0.85 | 0.85 | 0.86 | see above |\n", + "| Stable | 0.91 | 0.87 | 0.92 | |\n", + "| Unstable | 0.92 | 0.88 | 0.92 | |\n", + "| Deceased | 0.94 | 0.95 | 0.99 | |\n", + "| Unstable→stable | 0.77 | 0.70 | 0.73 | |\n", + "| Stable→unstable | 0.77 | 0.77 | 0.71 | |\n", + "| MV onset | 0.80 | 0.81 | 0.73 | |\n", + "| VP onset | 0.81 | 0.76 | 0.83 | |\n", + "| CRRT onset | 0.94 | 0.86 | 0.93 | |\n", + "\n", + "The paper reports the onset of the three therapies; the task and model also give their stop (`mv_stop`, `vp_stop`, `crrt_stop`), as the authors' code does.\n", + "\n", + "**The demo numbers above are a smoke test, not a reproduction.** The demo test split holds about 20 patients and only a handful of positives for most outcomes (see the `test +` column), so its AUROCs are very noisy, and several outcomes have no positive at all.\n", + "\n", + "What differs from the paper even on full data, so numbers are comparable in trend rather than identical:\n", + "\n", + "- **Data and split**: here the model is trained and tested on MIMIC-IV (a random 70/15/15 split by patient). In the paper MIMIC-IV is part of the *external* cohort: the model never trains on it.\n", + "- **Features**: the 48 YAIB labs and vitals (with their plausibility bounds and unit conversions) as events, plus age, sex, height and weight. The paper uses its own list of vitals, labs, medications and assessment scores (Supplementary Table S1), plus race, BMI and comorbidities.\n", + "- **Labels**: the paper's text counts any alive ICU discharge as *discharge*; the authors' MIMIC-IV code only counts a discharge home within 24 hours. The task follows the text by default (`ICUAcuityMIMIC4(discharge_home_only=True)` switches). Windows without any event are skipped, while the authors drop the whole stay.\n", + "- **Model**: a pure-PyTorch Mamba (same equations, no fused CUDA kernel), padding masked out of the scan and the pooling, no positional encoding (disabled in the authors' code too), and class weights on the positive examples instead of on each label's loss term. No hyperparameter search (the authors run 10 Optuna trials); the defaults are the authors' final settings.\n", + "- **Calibration and episodes**: the paper recalibrates probabilities with isotonic regression and also reports episode-level (per-stay) metrics; neither is in this notebook. The samples carry `stay_id` and `window`, so episode-level metrics can be computed from the predictions.\n", + "\n", + "## What to check (for the APRICOT-M authors)\n", + "\n", + "1. The MIMIC-IV therapy items: MV = procedureevents 225792 (invasive ventilation); CRRT = 225802, 225803, 225809; massive transfusion = 229620; vasopressors = inputevents 221906, 221289, 229617, 221662, 222315, 221749 (`pyhealth/tasks/acuity_mimic4.py`).\n", + "2. The interval rule: a therapy is present in a 4-hour interval when its start-end period overlaps it; intervals start at ICU admission; the last interval is *deceased* when the patient died in the ICU (death up to 1 hour after the recorded ICU discharge counts) and *discharge* otherwise.\n", + "3. Whether the 12-output order (`ICUAcuityMIMIC4.LABELS`) and the model's fusion (pooled events plus static embedding, one two-layer head per outcome) match the published model." + ] + } + ], + "metadata": { + "accelerator": "GPU", + "colab": { + "provenance": [] + }, + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.13.5" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/pyhealth/models/__init__.py b/pyhealth/models/__init__.py index 046264f5a3..3b1c7ab204 100644 --- a/pyhealth/models/__init__.py +++ b/pyhealth/models/__init__.py @@ -81,6 +81,7 @@ from .survival_mdn import SurvivalMDN as SurvivalMDN from .trajsurv import TrajSurv as TrajSurv from .knowrare import KnowRare as KnowRare +from .apricotm import APRICOTM as APRICOTM, SelectiveSSM as SelectiveSSM from .heartlang import ( HeartLang as HeartLang, HeartLangBackbone as HeartLangBackbone, diff --git a/pyhealth/models/apricotm.py b/pyhealth/models/apricotm.py new file mode 100644 index 0000000000..3c2438679f --- /dev/null +++ b/pyhealth/models/apricotm.py @@ -0,0 +1,479 @@ +"""APRICOT-M: a state-space model for real-time ICU acuity prediction. + +Implements APRICOT-M from Contreras et al., "Real-time prediction of +intensive care unit patient acuity and therapy requirements using +state-space modelling", Nature Communications 16, 7315 (2025), +https://doi.org/10.1038/s41467-025-62121-1. + +APRICOT-M reads the clinical events of the last few hours as a sequence of +(time, variable, value) triplets, so irregular, sparse measurements need no +resampling or imputation. Time and value pass through two position-wise +layers (the paper's 1D convolutions with kernel size 1), the variable code +through an embedding, and the two are added. A stack of Mamba (selective +state-space) blocks contextualizes the events; top-k pooling over time keeps +the ``k`` largest activations of each channel, an MLP maps them to one +vector, and a static-feature embedding is added to it. One small head per +outcome gives the probability of each label (12 in the paper: four acuity +states, two transitions and the stop and onset of three therapies). + +Clean reimplementation from the paper. The authors' code +(https://github.com/iheallab/apricotM) is GPL-3.0, so none of it is copied +here; it was only read to confirm details (the default sizes below are the +ones it trains with). Differences: + +- The Mamba blocks are written in pure PyTorch (the selective scan of Gu + and Dao, 2023, computed in parallel in log space), so the CUDA + ``mamba_ssm`` package is not needed and the model runs on CPU. It uses + more memory than the fused kernel on long sequences. +- Padding is masked: padded positions do not update the state and are + excluded from top-k pooling, so a sample's prediction does not depend on + the other samples in its batch. +- No positional encoding is added (the authors' code has it disabled; the + scan is order-aware). +- Class imbalance: the paper weights each label's loss term; here + :meth:`~pyhealth.models.BaseModel.set_pos_weight` (e.g. ``"balanced"``) + weights the positive examples of each label. +- The isotonic recalibration and the overall-acuity logic of the paper are + evaluation steps and are not part of the model. +""" + +from __future__ import annotations + +import math + +import torch +import torch.nn.functional as F +from torch import Tensor, nn + +from pyhealth.datasets import SampleDataset +from pyhealth.models.base_model import BaseModel + +__all__ = ["APRICOTM", "SelectiveSSM", "selective_scan"] + + +def selective_scan(log_decay: Tensor, drive: Tensor, chunk_size: int = 32) -> Tensor: + """Parallel scan of ``h_t = exp(log_decay_t) * h_{t-1} + drive_t``, ``h_0 = 0``. + + Computed along dimension 1 in log space: within a chunk, with ``S_t`` + the cumulative sum of ``log_decay`` since the chunk start, + ``h_t = exp(S_t) h_start + sum_{s <= t} exp(S_t - S_s) drive_s``. The + positive and negative parts of ``drive`` are summed separately with + ``logcumsumexp``, so no ``exp(-S)`` can overflow; chunking keeps ``S`` + small enough for float32 precision. + + Args: + log_decay: Non-positive log decay factors, shape ``[B, L, ...]``. + drive: Inputs, same shape. + chunk_size: Steps per chunk. + + Returns: + The states ``h``, same shape. + + Examples: + >>> import torch + >>> log_decay = torch.log(torch.tensor([[0.5, 0.5, 0.5]])) + >>> drive = torch.tensor([[1.0, -2.0, 4.0]]) + >>> selective_scan(log_decay, drive) # h = 1, 0.5 - 2, -0.75 + 4 + tensor([[ 1.0000, -1.5000, 3.2500]]) + """ + very_negative = -1e30 + + def part(values: Tensor, cumulative: Tensor) -> Tensor: + positive = values > 0 + log_values = torch.where( + positive, torch.log(torch.where(positive, values, 1.0)), very_negative + ) + return torch.exp( + torch.logcumsumexp(log_values - cumulative, dim=1) + cumulative + ) + + chunks = [] + carry = None + for begin in range(0, log_decay.shape[1], chunk_size): + decay = log_decay[:, begin : begin + chunk_size] + inputs = drive[:, begin : begin + chunk_size] + cumulative = torch.cumsum(decay, dim=1) + states = part(inputs, cumulative) - part(-inputs, cumulative) + if carry is not None: + states = states + torch.exp(cumulative) * carry.unsqueeze(1) + carry = states[:, -1] + chunks.append(states) + if not chunks: + return drive.clone() + return torch.cat(chunks, dim=1) + + +class SelectiveSSM(nn.Module): + """A Mamba (selective state-space) mixer, in pure PyTorch. + + Follows Gu and Dao, "Mamba: Linear-Time Sequence Modeling with Selective + State Spaces" (2023): an input projection into a gated branch and an SSM + branch, a causal depthwise convolution, input-dependent step size + ``dt`` and matrices ``B`` and ``C``, a diagonal state matrix ``A``, and + the scan ``h_t = exp(dt_t A) h_{t-1} + dt_t B_t x_t``, + ``y_t = C_t h_t + D x_t``, computed in parallel by + :func:`selective_scan`. + + Args: + d_model: Input and output width. + d_state: State size ``N`` per channel. + d_conv: Kernel size of the causal depthwise convolution. + expand: Inner width is ``expand * d_model``. + dt_rank: Rank of the ``dt`` projection; ``ceil(d_model / 16)`` when + None. + + Examples: + >>> import torch + >>> mixer = SelectiveSSM(d_model=8, d_state=4) + >>> x = torch.randn(2, 5, 8) + >>> mixer(x).shape + torch.Size([2, 5, 8]) + >>> mask = torch.tensor([[1, 1, 1, 0, 0], [1, 1, 1, 1, 1]]).bool() + >>> y = mixer(x, mask) + >>> torch.allclose(y[0, :3], mixer(x[:1, :3])[0], atol=1e-6) + True + """ + + def __init__( + self, + d_model: int, + d_state: int = 16, + d_conv: int = 4, + expand: int = 2, + dt_rank: int | None = None, + ) -> None: + super().__init__() + self.d_model = d_model + self.d_state = d_state + self.d_inner = expand * d_model + self.dt_rank = dt_rank or math.ceil(d_model / 16) + self.in_proj = nn.Linear(d_model, 2 * self.d_inner, bias=False) + # Causal depthwise convolution, weight [D, d_conv] (last tap = now). + bound = 1.0 / math.sqrt(d_conv) + self.conv_weight = nn.Parameter( + torch.empty(self.d_inner, d_conv).uniform_(-bound, bound) + ) + self.conv_bias = nn.Parameter( + torch.empty(self.d_inner).uniform_(-bound, bound) + ) + self.x_proj = nn.Linear(self.d_inner, self.dt_rank + 2 * d_state, bias=False) + self.dt_proj = nn.Linear(self.dt_rank, self.d_inner) + # dt initialized log-uniformly in [1e-3, 1e-1] (Mamba's default). + dt = torch.exp( + torch.rand(self.d_inner) * (math.log(0.1) - math.log(1e-3)) + + math.log(1e-3) + ) + with torch.no_grad(): + self.dt_proj.bias.copy_(dt + torch.log(-torch.expm1(-dt))) + a = torch.arange(1, d_state + 1, dtype=torch.float32) + self.A_log = nn.Parameter(torch.log(a).repeat(self.d_inner, 1)) + self.D = nn.Parameter(torch.ones(self.d_inner)) + self.out_proj = nn.Linear(self.d_inner, d_model, bias=False) + + def _causal_conv(self, u: Tensor) -> Tensor: + """Depthwise causal convolution over time of ``u`` ``[B, L, D]``. + + Written as shifted sums: on CPU this is much faster to train than a + grouped ``nn.Conv1d``. + """ + taps = self.conv_weight.shape[1] + padded = F.pad(u, (0, 0, taps - 1, 0)) + length = u.shape[1] + out = self.conv_bias.expand_as(u) + for k in range(taps): + out = out + padded[:, k : k + length] * self.conv_weight[:, k] + return out + + def forward(self, x: Tensor, mask: Tensor | None = None) -> Tensor: + """Mixes a sequence. + + Args: + x: Shape ``[B, L, d_model]``. + mask: Optional bool ``[B, L]``, True for real positions. Padded + positions do not change the state; use right padding. + + Returns: + Shape ``[B, L, d_model]``; padded positions are zero. + """ + u, gate = self.in_proj(x).chunk(2, dim=-1) + if mask is not None: + u = u * mask.unsqueeze(-1) + u = F.silu(self._causal_conv(u)) + dt, b, c = self.x_proj(u).split( + [self.dt_rank, self.d_state, self.d_state], dim=-1 + ) + dt = F.softplus(self.dt_proj(dt)) # [B, L, D] + if mask is not None: + dt = dt * mask.unsqueeze(-1) + a = -torch.exp(self.A_log.float()) # [D, N] + log_decay = dt.unsqueeze(-1) * a # [B, L, D, N] + drive = (dt * u).unsqueeze(-1) * b.unsqueeze(2) # [B, L, D, N] + states = selective_scan(log_decay, drive) + y = torch.einsum("bldn,bln->bld", states, c) + u * self.D + y = self.out_proj(y * F.silu(gate)) + if mask is not None: + y = y * mask.unsqueeze(-1) + return y + + +class _MambaStack(nn.Module): + """Pre-norm residual Mamba blocks with a final LayerNorm.""" + + def __init__(self, d_model: int, n_layers: int, **ssm_kwargs) -> None: + super().__init__() + self.norms = nn.ModuleList(nn.LayerNorm(d_model) for _ in range(n_layers)) + self.mixers = nn.ModuleList( + SelectiveSSM(d_model, **ssm_kwargs) for _ in range(n_layers) + ) + self.final_norm = nn.LayerNorm(d_model) + + def forward(self, x: Tensor, mask: Tensor) -> Tensor: + for norm, mixer in zip(self.norms, self.mixers): + x = x + mixer(norm(x), mask) + return self.final_norm(x) + + +class APRICOTM(BaseModel): + """APRICOT-M: Mamba over clinical event triplets, for ICU acuity. + + The input is a ``sequence_v2`` series of events with one token (the + variable) and one value per event, such as the ``events`` field of + :class:`~pyhealth.tasks.ICUAcuityMIMIC4`; its ``time`` is the event time + (hours since ICU admission in that task), divided by ``time_scale``. + Only the last ``max_seq_len`` events of a sample are read, as in the + paper. ``static_key`` names an optional static tensor field. + + The label is a tensor field of ``K`` binary labels (the ``acuity`` + field of :class:`~pyhealth.tasks.ICUAcuityMIMIC4`, ``K = 12``). The + model is a multilabel classifier: one two-layer head per label, + ``mode`` is ``"multilabel"``, and the loss is the binary cross-entropy + averaged over labels. Use :meth:`set_pos_weight` (e.g. ``"balanced"`` + with the training samples) for the class weighting of the paper. + + Args: + dataset: The dataset (schemas, vocabulary and static width). + feature_key: The event series field. + label_key: The label field; None uses the only output field. + static_key: Optional static tensor field. + embedding_dim: Model width ``d_model`` (92 in the authors' code). + hidden_dim: Hidden width of the time-value layers (28). + num_layers: Mamba blocks (2). + state_size: SSM state size per channel. + conv_kernel: Kernel size of the Mamba convolution. + expand: Mamba inner width factor. + top_k: Time steps kept per channel by top-k pooling (5). + dropout: Dropout after the pooling MLP (0.2). + max_seq_len: Events read per sample, the most recent ones (512). + time_scale: Divides the event times (720 hours = 30 days, the + longest stay in the paper's cohort, maps them to [0, 1]). + + Examples: + >>> from pyhealth.datasets import create_sample_dataset + >>> levels = [{"ordering": "series", "tokens": 1, "values": [1]}] + >>> samples = [ + ... {"patient_id": f"p{i}", + ... "events": {"time": [0.5, 1.0 + i], "tokens": ["hr", "sbp"], + ... "values": [[80.0 + i], [120.0]]}, + ... "static": [60.0, 1.0], "acuity": [float(i % 2), 1.0, 0.0]} + ... for i in range(4) + ... ] + >>> dataset = create_sample_dataset( + ... samples=samples, + ... input_schema={"events": ("sequence_v2", {"levels": levels}), + ... "static": "tensor"}, + ... output_schema={"acuity": "tensor"}, + ... dataset_name="toy", + ... ) + >>> model = APRICOTM(dataset, static_key="static", embedding_dim=16) + >>> model.mode, model.num_labels + ('multilabel', 3) + + References: + Contreras, M., et al. Real-time prediction of intensive care unit + patient acuity and therapy requirements using state-space + modelling. Nature Communications 16, 7315 (2025). + """ + + def __init__( + self, + dataset: SampleDataset, + feature_key: str = "events", + label_key: str | None = None, + static_key: str | None = None, + embedding_dim: int = 92, + hidden_dim: int = 28, + num_layers: int = 2, + state_size: int = 16, + conv_kernel: int = 4, + expand: int = 2, + top_k: int = 5, + dropout: float = 0.2, + max_seq_len: int = 512, + time_scale: float = 720.0, + ) -> None: + super().__init__(dataset) + if feature_key not in dataset.input_schema: + raise ValueError(f"{feature_key!r} is not in dataset.input_schema") + if static_key is not None and static_key not in dataset.input_schema: + raise ValueError(f"{static_key!r} is not in dataset.input_schema") + if label_key is None: + if len(self.label_keys) != 1: + raise ValueError("label_key is required with several output fields") + label_key = self.label_keys[0] + if label_key not in dataset.output_schema: + raise ValueError(f"{label_key!r} is not in dataset.output_schema") + if top_k < 1 or max_seq_len < 1: + raise ValueError("top_k and max_seq_len must be positive") + self.feature_key = feature_key + self.label_key = label_key + self.label_keys = [label_key] + self.static_key = static_key + self.top_k = top_k + self.max_seq_len = max_seq_len + self.time_scale = float(time_scale) + self.mode = "multilabel" + + processor = dataset.input_processors[feature_key] + self._roles = self._event_roles(processor, feature_key) + sample = dataset[0] + self.num_labels = int(torch.as_tensor(sample[label_key]).numel()) + static_dim = 0 + if static_key is not None: + static_dim = int(torch.as_tensor(sample[static_key]).numel()) + + self.value_time = nn.Sequential( + nn.Linear(2, hidden_dim), nn.ReLU(), nn.Linear(hidden_dim, embedding_dim) + ) + self.variable_embedding = nn.Embedding( + processor.vocab_size()[0][0], embedding_dim, padding_idx=0 + ) + self.encoder = _MambaStack( + embedding_dim, + num_layers, + d_state=state_size, + d_conv=conv_kernel, + expand=expand, + ) + self.pool_mlp = nn.Sequential( + nn.Linear(embedding_dim * top_k, embedding_dim), nn.Dropout(dropout) + ) + self.static_ffn = ( + nn.Sequential( + nn.Linear(static_dim, embedding_dim), + nn.ReLU(), + nn.Linear(embedding_dim, embedding_dim), + ) + if static_key is not None + else None + ) + self.heads = nn.ModuleList( + nn.Sequential( + nn.Linear(embedding_dim, embedding_dim), + nn.ReLU(), + nn.Linear(embedding_dim, 1), + ) + for _ in range(self.num_labels) + ) + + # ------------------------------------------------------------ input + @staticmethod + def _event_roles(processor, key: str) -> dict[str, int]: + schema = getattr(processor, "schema", None) + entries = schema() if callable(schema) else () + roles: dict[str, int] = {} + for index, entry in enumerate(entries): + if not isinstance(entry, tuple) or entry[0] != 0: + raise ValueError( + f"{key!r} must be a single-level sequence_v2 series of events" + ) + roles[entry[1]] = index + if not {"tokens", "values", "time"} <= set(roles): + raise ValueError( + f"{key!r} must be a sequence_v2 'series' level with one token " + "namespace and values" + ) + # SequenceProcessorV2's collate appends the record offsets. + roles["offsets"] = len(entries) + return roles + + def _dense(self, value) -> tuple[Tensor, Tensor, Tensor, Tensor]: + """Packed events to right-padded ``tokens, values, times, mask``. + + Keeps the last ``max_seq_len`` events of each sample. + """ + tokens = value[self._roles["tokens"]].to(self.device).reshape(-1) + values = value[self._roles["values"]].to(self.device, torch.float32) + values = values.reshape(values.shape[0], -1)[:, 0] + times = value[self._roles["time"]].to(self.device, torch.float32).reshape(-1) + offsets = value[self._roles["offsets"]].to(self.device) + lengths = (offsets[1:] - offsets[:-1]).clamp(max=self.max_seq_len) + starts = offsets[1:] - lengths + steps = max(int(lengths.max().item()) if len(lengths) else 0, 1) + position = torch.arange(steps, device=self.device) + mask = position[None, :] < lengths[:, None] + if tokens.shape[0] == 0: + zeros = torch.zeros_like(mask, dtype=torch.float32) + return zeros.long(), zeros, zeros, mask + index = (starts[:, None] + position[None, :]).clamp(max=tokens.shape[0] - 1) + dense_tokens = torch.where(mask, tokens[index], 0) + dense_values = torch.where(mask, torch.nan_to_num(values[index]), 0.0) + dense_times = torch.where(mask, times[index] / self.time_scale, 0.0) + return dense_tokens, dense_values, dense_times, mask + + # ------------------------------------------------------------ model + def encode(self, **kwargs) -> Tensor: + """The fused patient representation, ``[B, embedding_dim]``. + + Args: + **kwargs: Batch fields from the PyHealth dataloader. + + Returns: + The pooled event encoding plus the static embedding. + """ + tokens, values, times, mask = self._dense(kwargs[self.feature_key]) + x = self.value_time(torch.stack([times, values], dim=-1)) + x = x + self.variable_embedding(tokens) + x = self.encoder(x * mask.unsqueeze(-1), mask) # [B, L, d] + x = x.masked_fill(~mask.unsqueeze(-1), float("-inf")).transpose(1, 2) + if x.shape[-1] < self.top_k: + x = F.pad(x, (0, self.top_k - x.shape[-1]), value=float("-inf")) + pooled = torch.topk(x, k=self.top_k, dim=-1).values # [B, d, k] + pooled = torch.nan_to_num(pooled, neginf=0.0).flatten(1) + h = self.pool_mlp(pooled) + if self.static_ffn is not None: + static = torch.as_tensor(kwargs[self.static_key]).to( + self.device, torch.float32 + ) + h = h + self.static_ffn(static.reshape(static.shape[0], -1)) + return h + + def forward(self, **kwargs) -> dict[str, Tensor]: + """Runs APRICOT-M on a batch. + + Args: + **kwargs: Batch fields from the PyHealth dataloader; the label + is optional (inference without labels). + + Returns: + ``logit`` ``[B, K]``, ``y_prob`` (sigmoid of the logits), and + with labels ``loss`` (mean binary cross-entropy, weighted by + :attr:`pos_weight` when set) and ``y_true``. ``embed=True`` adds + ``embed``, the fused representation. + """ + h = self.encode(**kwargs) + logits = torch.cat([head(h) for head in self.heads], dim=-1) + out = {"logit": logits, "y_prob": torch.sigmoid(logits)} + if self.label_key in kwargs: + y_true = torch.as_tensor(kwargs[self.label_key]).to( + self.device, torch.float32 + ).reshape(logits.shape) + pos_weight = self.pos_weight + out["loss"] = F.binary_cross_entropy_with_logits( + logits, + y_true, + pos_weight=None if pos_weight is None else pos_weight.to(self.device), + ) + out["y_true"] = y_true + if kwargs.get("embed", False): + out["embed"] = h + return out diff --git a/pyhealth/tasks/__init__.py b/pyhealth/tasks/__init__.py index 305e59d57a..22316ae234 100644 --- a/pyhealth/tasks/__init__.py +++ b/pyhealth/tasks/__init__.py @@ -69,6 +69,7 @@ MultimodalMortalityPredictionMIMIC4, ) from .survival_mimic4 import InHospitalSurvivalMIMIC4 as InHospitalSurvivalMIMIC4 +from .acuity_mimic4 import ICUAcuityMIMIC4 as ICUAcuityMIMIC4 from .survival_preprocess_support2 import SurvivalPreprocessSupport2 from .mortality_prediction_stagenet_mimic4 import ( MortalityPredictionStageNetMIMIC4, diff --git a/pyhealth/tasks/acuity_mimic4.py b/pyhealth/tasks/acuity_mimic4.py new file mode 100644 index 0000000000..d1bcc59946 --- /dev/null +++ b/pyhealth/tasks/acuity_mimic4.py @@ -0,0 +1,385 @@ +"""Real-time ICU acuity and life-sustaining therapy prediction on MIMIC-IV. + +The prediction setting of APRICOT-M (Contreras et al., "Real-time prediction +of intensive care unit patient acuity and therapy requirements using +state-space modelling", Nature Communications 16, 7315 (2025), +https://doi.org/10.1038/s41467-025-62121-1). Every 4 hours of an ICU stay, +the clinical events of the past 4 hours and the patient's static data predict +the acuity state of the next 4 hours (discharge, stable, unstable or +deceased), transitions between stable and unstable, and the onset or stop of +mechanical ventilation, vasopressors and continuous renal replacement +therapy. The acuity states follow the computable phenotype of Ren et al. +(2022): a 4-hour interval is unstable when the patient receives at least one +life-sustaining therapy in it. + +This is a clean reimplementation from the paper's Methods. The authors' +code (https://github.com/iheallab/apricotM) is GPL-3.0, so no code was +copied; it was only read to confirm details the paper leaves open (the +MIMIC-IV item IDs of the therapies and the order of the 12 outputs). +""" + +from __future__ import annotations + +import math +from datetime import datetime, timedelta +from typing import Any, ClassVar + +import polars as pl + +from .yaib_mimic4 import _parse_time, _YAIBMIMIC4Task + +# MIMIC-IV item IDs of the life-sustaining therapies (MetaVision items). +MECHANICAL_VENTILATION_ITEMIDS = (225792,) # procedureevents: Invasive Ventilation +CRRT_ITEMIDS = (225802, 225803, 225809) # procedureevents: CRRT, CVVHD, CVVHDF +MASSIVE_TRANSFUSION_ITEMIDS = (229620,) # procedureevents: Massive Transfusion +VASOPRESSOR_ITEMIDS = ( # inputevents + 221906, # norepinephrine + 221289, # epinephrine + 229617, # epinephrine (second item) + 221662, # dopamine + 222315, # vasopressin + 221749, # phenylephrine +) + +# The six routine vital signs every included stay must have (paper Methods). +_REQUIRED_VITALS = ("hr", "resp", "sbp", "dbp", "temp", "o2sat") + +_STATES = ("discharge", "stable", "unstable", "deceased") + + +class ICUAcuityMIMIC4(_YAIBMIMIC4Task): + """Next-4-hour ICU acuity, acuity transitions and therapy changes (MIMIC-IV). + + Cohort (paper Methods): every ICU stay of an adult (age 18 or more) that + lasts between ``min_stay_hours`` (8) hours and ``max_stay_days`` (30) + days and has at least one measurement of each of the six routine vital + signs (heart rate, respiratory rate, systolic and diastolic blood + pressure, temperature and oxygen saturation). + + Each stay is cut into 4-hour intervals from ICU admission. Interval + ``j`` covers hours ``[4j, 4j + 4)``. A therapy is present in an interval + when its start-end period overlaps it. The interval is ``unstable`` when + mechanical ventilation, a vasopressor, CRRT or (if + ``include_massive_transfusion``) a massive transfusion is present, and + ``stable`` otherwise. The last interval of the stay is ``deceased`` when + the patient died in the ICU, and ``discharge`` when the patient left the + ICU alive (with ``discharge_home_only``, only when the hospital + discharged the patient home within 24 hours of leaving the ICU). + + One sample per stay and interval ``j >= 1`` (the prediction window) whose + observation window, hours ``[4(j - 1), 4j)``, has at least one event: + + - ``events``: the clinical events of the observation window as a + ``sequence_v2`` series of (time, variable, value) triplets: time in + hours since ICU admission, the variable name as the token, and the + value. The processor scales each variable to [0, 1] (min-max per + variable, fitted on the training patients). The variables are the 48 + YAIB labs and vitals (see + :class:`~pyhealth.tasks.YAIBMortalityMIMIC4`), with their plausibility + bounds and unit conversions. Events are not resampled or imputed. + - ``static``: age, sex, height and weight (missing values get + indicators, then standardized), as in the YAIB tasks. + - ``acuity``: 12 binary labels, in the order of :attr:`LABELS`: the + next interval's state (one-hot: discharge, stable, unstable, + deceased), the transitions unstable to stable and stable to unstable, + and for mechanical ventilation, vasopressors and CRRT the stop (on in + the observation interval, off in the prediction interval) and the + onset (off, then on). + - ``stay_id`` and ``window`` (``j``), for episode-level evaluation. + + Fit the processors on the training patients only, with + ``set_task(task, split=...)``. + + Requires the ``labevents``, ``chartevents``, ``outputevents``, + ``procedureevents``, ``inputevents`` and ``admissions`` tables. + + Args: + window_hours: Length of the observation and prediction windows (4 in + the paper). + min_stay_hours: Shortest ICU stay kept. + max_stay_days: Longest ICU stay kept. + include_massive_transfusion: Count a massive transfusion as a + life-sustaining therapy for the stable/unstable state (as in the + paper; it gets no label of its own). + discharge_home_only: Label the last interval ``discharge`` only when + the patient went home within 24 hours of leaving the ICU, as in + the authors' MIMIC-IV code. By default any alive ICU discharge + counts, as the paper's text describes. + death_tolerance_hours: A hospital death up to this many hours after + ICU discharge still counts as an ICU death (the recorded ICU + discharge can precede the death time slightly). + + Examples: + >>> from pyhealth.datasets import MIMIC4EHRDataset + >>> from pyhealth.tasks import ICUAcuityMIMIC4 + >>> dataset = MIMIC4EHRDataset( + ... root="/path/to/mimic-iv/2.2", + ... tables=["labevents", "chartevents", "outputevents", + ... "procedureevents", "inputevents", "admissions"], + ... ) # doctest: +SKIP + >>> samples = dataset.set_task(ICUAcuityMIMIC4()) # doctest: +SKIP + >>> ICUAcuityMIMIC4.LABELS[:4] + ['discharge', 'stable', 'unstable', 'deceased'] + """ + + task_name: str = "ICUAcuityMIMIC4" + input_schema: ClassVar[dict[str, Any]] = { + "events": ( + "sequence_v2", + { + "levels": [ + { + "ordering": "series", + "tokens": 1, + "values": [1], + "normalize": {"method": "minmax", "by_tokens": [0]}, + } + ] + }, + ), + "static": _YAIBMIMIC4Task.input_schema["static"], + } + output_schema: ClassVar[dict[str, Any]] = {"acuity": "tensor"} + + LABELS: ClassVar[list[str]] = [ + *_STATES, + "unstable_to_stable", + "stable_to_unstable", + "mv_stop", + "mv_onset", + "vp_stop", + "vp_onset", + "crrt_stop", + "crrt_onset", + ] + + _EXTRA_ITEMIDS: ClassVar[dict[str, tuple[int, ...]]] = { + "procedureevents": ( + *MECHANICAL_VENTILATION_ITEMIDS, + *CRRT_ITEMIDS, + *MASSIVE_TRANSFUSION_ITEMIDS, + ), + "inputevents": VASOPRESSOR_ITEMIDS, + } + _EXTRA_TABLES: ClassVar[tuple[str, ...]] = ( + "procedureevents", + "inputevents", + "admissions", + ) + + def __init__( + self, + window_hours: float = 4.0, + min_stay_hours: float = 8.0, + max_stay_days: float = 30.0, + include_massive_transfusion: bool = True, + discharge_home_only: bool = False, + death_tolerance_hours: float = 1.0, + ) -> None: + super().__init__() + if window_hours <= 0: + raise ValueError("window_hours must be positive") + if min_stay_hours < 2 * window_hours: + raise ValueError( + "min_stay_hours must cover one observation and one prediction " + "window (2 * window_hours)" + ) + self.window_hours = float(window_hours) + self.min_stay_hours = float(min_stay_hours) + self.max_stay_days = float(max_stay_days) + self.include_massive_transfusion = include_massive_transfusion + self.discharge_home_only = discharge_home_only + self.death_tolerance_hours = float(death_tolerance_hours) + + # ------------------------------------------------------------ therapies + def _therapies( + self, patient: Any, stays: pl.DataFrame + ) -> dict[int, list[tuple[str, float, float]]]: + """Per stay: (therapy, start hour, end hour) since ICU admission.""" + kinds = { + **{i: "mv" for i in MECHANICAL_VENTILATION_ITEMIDS}, + **{i: "crrt" for i in CRRT_ITEMIDS}, + **{i: "vp" for i in VASOPRESSOR_ITEMIDS}, + } + if self.include_massive_transfusion: + kinds.update({i: "bt" for i in MASSIVE_TRANSFUSION_ITEMIDS}) + intimes = dict(stays.select("stay_id", "intime").iter_rows()) + therapies: dict[int, list[tuple[str, float, float]]] = {} + for table in ("procedureevents", "inputevents"): + events = patient.get_events(event_type=table, return_df=True) + if events.height == 0: + continue + rows = events.select( + pl.col(f"{table}/stay_id").cast(pl.Int64, strict=False), + pl.col(f"{table}/itemid").cast(pl.Int64, strict=False), + pl.col("timestamp"), + _parse_time(f"{table}/endtime"), + ) + for stay_id, itemid, start, end in rows.iter_rows(): + kind = kinds.get(itemid) + intime = intimes.get(stay_id) + if kind is None or intime is None or start is None: + continue + end = start if end is None or end < start else end + therapies.setdefault(stay_id, []).append( + (kind, _hours(start, intime), _hours(end, intime)) + ) + return therapies + + def _interval_flags( + self, therapies: list[tuple[str, float, float]], n_intervals: int + ) -> list[set[str]]: + """The therapies present in each interval.""" + flags: list[set[str]] = [set() for _ in range(n_intervals)] + w = self.window_hours + for kind, start, end in therapies: + if end < 0 or (end == start and start < 0): + continue # entirely before ICU admission + first = max(0, math.floor(start / w)) + # A period overlaps [lo, hi) when start < hi and end > lo; a + # point event (start == end) belongs to the interval holding it. + last = math.ceil(end / w) - 1 if end > start else first + for j in range(first, min(last, n_intervals - 1) + 1): + flags[j].add(kind) + return flags + + # ------------------------------------------------------------ outcomes + def _ends( + self, patient: Any + ) -> dict[int, tuple[datetime | None, bool, datetime | None]]: + """Per admission: death time (or None), discharged home, discharge time.""" + admissions = patient.get_events(event_type="admissions", return_df=True) + if admissions.height == 0: + return {} + rows = admissions.select( + pl.col("admissions/hadm_id").cast(pl.Int64, strict=False), + _parse_time("admissions/dischtime"), + _parse_time("admissions/deathtime"), + pl.col("admissions/hospital_expire_flag").cast(pl.Int64, strict=False), + pl.col("admissions/discharge_location") + if "admissions/discharge_location" in admissions.columns + else pl.lit(None, dtype=pl.String), + ) + ends = {} + for hadm_id, dischtime, deathtime, expired, location in rows.iter_rows(): + if hadm_id is None: + continue + death = None + if expired == 1: + death = deathtime or dischtime + ends[hadm_id] = (death, location == "HOME", dischtime) + return ends + + def _final_state( + self, + intime: datetime, + outtime: datetime, + end: tuple[datetime | None, bool, datetime | None] | None, + ) -> str | None: + """``deceased``, ``discharge`` or None for the last interval.""" + if end is None: + return "discharge" if not self.discharge_home_only else None + death, home, dischtime = end + tolerance = timedelta(hours=self.death_tolerance_hours) + if death is not None and intime < death <= outtime + tolerance: + return "deceased" + if death is not None and death <= intime: + return None + if not self.discharge_home_only: + return "discharge" + near = ( + dischtime is not None + and abs((dischtime - outtime).total_seconds()) <= 24 * 3600 + ) + return "discharge" if home and near else None + + # ------------------------------------------------------------ samples + def __call__(self, patient: Any) -> list[dict[str, Any]]: + stays = self._stays(patient) + if stays.height == 0: + return [] + stays = stays.with_columns( + ((pl.col("outtime") - pl.col("intime")).dt.total_seconds() / 3600) + .alias("los_hours") + ) + static = self._static(patient, stays) + events = self._measurements( + patient, stays, self._DYNAMIC_ITEMS, exact_hours=True + ) + therapies = self._therapies(patient, stays) + ends = self._ends(patient) + required = [self.DYNAMIC_FEATURES.index(name) for name in _REQUIRED_VITALS] + w = self.window_hours + + samples = [] + for stay_id, hadm_id, intime, outtime, los in stays.select( + "stay_id", "hadm_id", "intime", "outtime", "los_hours" + ).iter_rows(): + if not self.min_stay_hours <= los <= self.max_stay_days * 24: + continue + age = static[stay_id][0] + if not age >= 18: # also drops a missing (NaN) age + continue + stay_events = events.filter( + (pl.col("stay_id") == stay_id) + & (pl.col("hours") >= 0) + & (pl.col("hours") < los) + ).sort("hours") + seen = set(stay_events["feature"].unique().to_list()) + if not all(feature in seen for feature in required): + continue + + n_intervals = math.ceil(los / w) + flags = self._interval_flags(therapies.get(stay_id, []), n_intervals) + states = ["unstable" if f else "stable" for f in flags] + final = self._final_state(intime, outtime, ends.get(hadm_id)) + if final is not None: + states[-1] = final + + hours = stay_events["hours"].to_list() + features = stay_events["feature"].to_list() + values = stay_events["value"].to_list() + start = 0 + for j in range(1, n_intervals): + lo, hi = (j - 1) * w, j * w + while start < len(hours) and hours[start] < lo: + start += 1 + stop = start + while stop < len(hours) and hours[stop] < hi: + stop += 1 + if stop == start: + continue + samples.append( + { + "patient_id": patient.patient_id, + "stay_id": stay_id, + "window": j, + "events": { + "time": hours[start:stop], + "tokens": [ + self.DYNAMIC_FEATURES[f] for f in features[start:stop] + ], + "values": [[v] for v in values[start:stop]], + }, + "static": static[stay_id], + "acuity": self._labels_for(flags, states, j), + } + ) + return samples + + @staticmethod + def _labels_for(flags: list[set[str]], states: list[str], j: int) -> list[float]: + """The 12 labels of prediction interval ``j`` (see :attr:`LABELS`).""" + state, previous = states[j], states[j - 1] + labels = [float(state == name) for name in _STATES] + labels.append(float(previous == "unstable" and state == "stable")) + labels.append(float(previous == "stable" and state == "unstable")) + for therapy in ("mv", "vp", "crrt"): + before, after = therapy in flags[j - 1], therapy in flags[j] + labels.append(float(before and not after)) + labels.append(float(not before and after)) + return labels + + +def _hours(time: datetime, origin: datetime) -> float: + return (time - origin).total_seconds() / 3600.0 diff --git a/pyhealth/tasks/yaib_mimic4.py b/pyhealth/tasks/yaib_mimic4.py index d41d61c635..812056cc08 100644 --- a/pyhealth/tasks/yaib_mimic4.py +++ b/pyhealth/tasks/yaib_mimic4.py @@ -380,9 +380,17 @@ def _stays(self, patient: Any) -> pl.DataFrame: ) def _measurements( - self, patient: Any, stays: pl.DataFrame, items: pl.DataFrame + self, + patient: Any, + stays: pl.DataFrame, + items: pl.DataFrame, + exact_hours: bool = False, ) -> pl.DataFrame: - """Returns valid measurements as (stay_id, hour, feature, value, is_sum).""" + """Returns valid measurements as (stay_id, hour, feature, value, is_sum). + + With ``exact_hours``, a last column ``hours`` holds the fractional + hours since ICU admission (``hour`` is its floor). + """ frames = [] for table, value_column in _VALUE_COLUMNS.items(): table_items = items.filter(pl.col("table") == table) @@ -410,8 +418,11 @@ def _measurements( events = self._assign_stays(events, stays) frames.append(events.drop("hadm_id")) + schema = dict(_MEASUREMENT_SCHEMA) + if exact_hours: + schema["hours"] = pl.Float64 if not frames: - return pl.DataFrame(schema=_MEASUREMENT_SCHEMA) + return pl.DataFrame(schema=schema) converted = pl.col("unit").str.contains(pl.col("unit_regex")).fill_null(False) return ( @@ -423,6 +434,10 @@ def _measurements( .otherwise(pl.col("value")) .alias("value"), _hours_since("intime").alias("hour"), + ( + (pl.col("timestamp") - pl.col("intime")).dt.total_seconds() + / 3600 + ).alias("hours"), ) .filter( pl.col("value").is_not_null() @@ -430,7 +445,7 @@ def _measurements( & (pl.col("lower").is_null() | (pl.col("value") >= pl.col("lower"))) & (pl.col("upper").is_null() | (pl.col("value") <= pl.col("upper"))) ) - .select(list(_MEASUREMENT_SCHEMA)) + .select(list(schema)) ) @staticmethod diff --git a/tests/core/test_apricotm.py b/tests/core/test_apricotm.py new file mode 100644 index 0000000000..6f198f4ed8 --- /dev/null +++ b/tests/core/test_apricotm.py @@ -0,0 +1,350 @@ +import unittest +from datetime import datetime, timedelta + +import polars as pl +import torch + +from pyhealth.data import Patient +from pyhealth.datasets import create_sample_dataset, get_dataloader +from pyhealth.models import APRICOTM, SelectiveSSM +from pyhealth.models.apricotm import selective_scan +from pyhealth.tasks import ICUAcuityMIMIC4 + +T0 = datetime(2150, 1, 1, 8, 0, 0) # noqa: DTZ001 - MIMIC times are naive +LABELS = ICUAcuityMIMIC4.LABELS +VITALS = { # itemid: value, for the six vitals every stay needs + 220045: 80, # hr + 220210: 18, # resp + 220050: 120, # sbp + 220051: 70, # dbp + 223762: 37, # temp (Celsius) + 220277: 97, # o2sat +} + + +def _event(event_type, timestamp, **attrs): + row = {"event_type": event_type, "timestamp": timestamp} + for key, value in attrs.items(): + row[f"{event_type}/{key}"] = None if value is None else str(value) + return row + + +def _fmt(time): + return time.strftime("%Y-%m-%d %H:%M:%S") + + +def _hr(hour, stay_id=10, value=90): + return _event("chartevents", T0 + timedelta(hours=hour), stay_id=stay_id, + hadm_id=1, itemid=220045, valuenum=value, valueuom="bpm") + + +def _procedure(itemid, start, end, stay_id=10): + return _event("procedureevents", T0 + timedelta(hours=start), stay_id=stay_id, + hadm_id=1, itemid=itemid, endtime=_fmt(T0 + timedelta(hours=end))) + + +def _input(itemid, start, end, stay_id=10): + return _event("inputevents", T0 + timedelta(hours=start), stay_id=stay_id, + hadm_id=1, itemid=itemid, endtime=_fmt(T0 + timedelta(hours=end))) + + +def _patient(*, hours=18.0, age=60, deathtime=None, location="HOME", + vitals=True, hr_hours=(4.5, 8.5, 12.5), extra=()): + """One admission with one ICU stay (stay_id 10) of ``hours`` hours. + + The six vitals are charted at hour 0.5 and a heart rate at ``hr_hours``. + """ + outtime = T0 + timedelta(hours=hours) + rows = [ + _event("patients", None, anchor_age=age, gender="F"), + _event("admissions", T0 - timedelta(hours=5), hadm_id=1, + dischtime=_fmt(outtime + timedelta(hours=2)), + deathtime=None if deathtime is None else _fmt(deathtime), + hospital_expire_flag=int(deathtime is not None), + discharge_location="DIED" if deathtime else location), + _event("icustays", T0, stay_id=10, hadm_id=1, outtime=_fmt(outtime)), + ] + if vitals: + for itemid, value in VITALS.items(): + rows.append( + _event("chartevents", T0 + timedelta(hours=0.5), stay_id=10, + hadm_id=1, itemid=itemid, valuenum=value, valueuom="x") + ) + rows += [_hr(hour) for hour in hr_hours] + rows += list(extra) + df = pl.from_dicts(rows, infer_schema_length=None) + df = df.with_columns( + pl.lit("p1").alias("patient_id"), + pl.col("timestamp").cast(pl.Datetime("ms")), + *(pl.col(c).cast(pl.String) for c in df.columns if "/" in c), + ) + return Patient(patient_id="p1", data_source=df) + + +def _positives(sample): + return {name for name, y in zip(LABELS, sample["acuity"]) if y} + + +class TestICUAcuityMIMIC4(unittest.TestCase): + def setUp(self): + self.task = ICUAcuityMIMIC4() + # Ventilation in hours 5-10 (intervals 1 and 2) and a vasopressor in + # hours 13-14 (interval 3) of an 18-hour stay (intervals 0-4). + self.therapies = [_procedure(225792, 5, 10), _input(221906, 13, 14)] + + def test_labels_of_each_window(self): + samples = self.task( + _patient(hr_hours=(4.5, 8.5, 12.5, 15.0), extra=self.therapies) + ) + self.assertEqual([s["window"] for s in samples], [1, 2, 3, 4]) + self.assertEqual( + [_positives(s) for s in samples], + [ + {"unstable", "stable_to_unstable", "mv_onset"}, + {"unstable"}, + {"unstable", "mv_stop", "vp_onset"}, + {"discharge", "vp_stop"}, + ], + ) + self.assertEqual(len(samples[0]["acuity"]), 12) + + def test_events_are_the_observation_window_triplets(self): + samples = self.task(_patient(extra=self.therapies)) + first = samples[0]["events"] + self.assertEqual(len(first["time"]), 6) + self.assertTrue(all(t == 0.5 for t in first["time"])) + self.assertEqual( + sorted(first["tokens"]), ["dbp", "hr", "o2sat", "resp", "sbp", "temp"] + ) + second = samples[1]["events"] + self.assertEqual(second["time"], [4.5]) + self.assertEqual(second["tokens"], ["hr"]) + self.assertEqual(second["values"], [[90.0]]) + self.assertEqual(samples[0]["static"][0], 60.0) + + def test_window_without_events_is_skipped(self): + samples = self.task(_patient(hr_hours=(8.5,), extra=self.therapies)) + self.assertEqual([s["window"] for s in samples], [1, 3]) + + def test_icu_death(self): + death = T0 + timedelta(hours=18) + samples = self.task( + _patient(deathtime=death, hr_hours=(4.5, 8.5, 12.5, 15.0)) + ) + self.assertEqual(_positives(samples[-1]), {"deceased"}) + self.assertEqual(_positives(samples[0]), {"stable"}) + + def test_death_after_icu_discharge_is_a_discharge(self): + death = T0 + timedelta(hours=30) + samples = self.task(_patient(deathtime=death, hr_hours=(4.5, 8.5, 12.5, 15.0))) + self.assertEqual(_positives(samples[-1]), {"discharge"}) + + def test_discharge_home_only(self): + task = ICUAcuityMIMIC4(discharge_home_only=True) + hr = (4.5, 8.5, 12.5, 15.0) + home = task(_patient(location="HOME", hr_hours=hr)) + self.assertEqual(_positives(home[-1]), {"discharge"}) + rehab = task(_patient(location="REHAB", hr_hours=hr)) + self.assertEqual(_positives(rehab[-1]), {"stable"}) + + def test_massive_transfusion_only_sets_the_state(self): + extra = [_procedure(229620, 5, 6)] + samples = self.task(_patient(extra=extra)) + self.assertEqual(_positives(samples[0]), {"unstable", "stable_to_unstable"}) + task = ICUAcuityMIMIC4(include_massive_transfusion=False) + self.assertEqual(_positives(task(_patient(extra=extra))[0]), {"stable"}) + + def test_point_event_and_therapy_before_admission(self): + extra = [ + _input(221906, 4.5, 4.5), # push: interval 1 only + _procedure(225792, -10, -1), # before the stay: ignored + _procedure(225802, -10, 4.5), # CRRT running at admission + ] + samples = self.task(_patient(extra=extra)) + self.assertEqual( + _positives(samples[0]), {"unstable", "vp_onset"} + ) + self.assertEqual( + _positives(samples[1]), {"unstable_to_stable", "stable", "vp_stop", + "crrt_stop"} + ) + + def test_exclusions(self): + self.assertEqual(self.task(_patient(hours=6)), []) + self.assertEqual(self.task(_patient(hours=31 * 24)), []) + self.assertEqual(self.task(_patient(age=17)), []) + self.assertEqual(self.task(_patient(vitals=False)), []) + + def test_invalid_arguments(self): + with self.assertRaises(ValueError): + ICUAcuityMIMIC4(window_hours=0) + with self.assertRaises(ValueError): + ICUAcuityMIMIC4(window_hours=4, min_stay_hours=6) + + def test_pre_filter_requires_therapy_tables(self): + df = pl.DataFrame( + {"event_type": ["chartevents"], "chartevents/itemid": ["220045"], + "labevents/itemid": [None], "outputevents/itemid": [None], + "admissions/hadm_id": [None]} + ).lazy() + with self.assertRaisesRegex(ValueError, "procedureevents"): + self.task.pre_filter(df) + + def test_samples_feed_the_model(self): + patient = _patient(hr_hours=(4.5, 8.5, 12.5, 15.0), extra=self.therapies) + samples = self.task(patient) + dataset = create_sample_dataset( + samples=samples, + input_schema=ICUAcuityMIMIC4.input_schema, + output_schema=ICUAcuityMIMIC4.output_schema, + dataset_name="acuity", + ) + model = APRICOTM(dataset, static_key="static", embedding_dim=8, + hidden_dim=4, state_size=4) + batch = next(iter(get_dataloader(dataset, batch_size=4))) + out = model(**batch) + self.assertEqual(out["y_prob"].shape, (4, 12)) + torch.testing.assert_close(out["y_true"], batch["acuity"]) + + +def _toy_dataset(n=6, long_index=None): + samples = [] + for i in range(n): + steps = 12 if i == long_index else 2 + i % 3 + samples.append( + { + "patient_id": f"p{i}", + "events": { + "time": [0.5 * t for t in range(steps)], + "tokens": ["hr" if t % 2 else "sbp" for t in range(steps)], + "values": [[80.0 + i + t] for t in range(steps)], + }, + "static": [50.0 + i, float(i % 2)], + "acuity": [float(i % 2), float(i % 3 == 0), 0.0, 1.0], + } + ) + levels = [{"ordering": "series", "tokens": 1, "values": [1], + "normalize": {"method": "minmax", "by_tokens": [0]}}] + return create_sample_dataset( + samples=samples, + input_schema={"events": ("sequence_v2", {"levels": levels}), + "static": "tensor"}, + output_schema={"acuity": "tensor"}, + dataset_name="toy", + ) + + +class TestAPRICOTM(unittest.TestCase): + def setUp(self): + torch.manual_seed(0) + self.dataset = _toy_dataset(long_index=5) + self.model = APRICOTM(self.dataset, static_key="static", embedding_dim=16, + hidden_dim=8, state_size=4, top_k=3) + + def _batch(self, indices): + return get_dataloader(self.dataset, batch_size=len(indices)).collate_fn( + [self.dataset[i] for i in indices] + ) + + def test_output_contract(self): + out = self.model(**self._batch(range(6))) + self.assertEqual(self.model.mode, "multilabel") + self.assertEqual(out["logit"].shape, (6, 4)) + self.assertEqual(out["y_true"].shape, (6, 4)) + torch.testing.assert_close(out["y_prob"], torch.sigmoid(out["logit"])) + out["loss"].backward() + grads = [p.grad for name, p in self.model.named_parameters() + if name != "_dummy_param"] + self.assertTrue(all(g is not None and torch.isfinite(g).all() for g in grads)) + + def test_inference_without_labels(self): + batch = self._batch(range(3)) + batch.pop("acuity") + out = self.model(**batch, embed=True) + self.assertNotIn("loss", out) + self.assertNotIn("y_true", out) + self.assertEqual(out["embed"].shape, (3, 16)) + + def test_prediction_does_not_depend_on_the_batch(self): + self.model.eval() + with torch.no_grad(): + alone = self.model(**self._batch([0]))["logit"] + batched = self.model(**self._batch([0, 5, 1]))["logit"][:1] + torch.testing.assert_close(alone, batched, atol=1e-5, rtol=1e-5) + + def test_only_the_last_events_are_read(self): + model = APRICOTM(self.dataset, static_key="static", embedding_dim=16, + hidden_dim=8, state_size=4, top_k=3, max_seq_len=4) + model.eval() + batch = self._batch([5]) + tokens, values, time, _ = batch["events"] + cut = (tokens[-4:], values[-4:], time[-4:], torch.tensor([0, 4])) + with torch.no_grad(): + full = model(**batch)["logit"] + last = model(**{**batch, "events": cut})["logit"] + changed = model(**{**batch, "events": ( + tokens[-5:], values[-5:].clone().fill_(0.9), time[-5:], + torch.tensor([0, 5]))})["logit"] + torch.testing.assert_close(full, last) + self.assertFalse(torch.allclose(full, changed)) + + def test_short_sequence_and_no_static(self): + model = APRICOTM(self.dataset, embedding_dim=8, hidden_dim=4, + state_size=4, top_k=10) + out = model(**self._batch([0, 1])) + self.assertTrue(torch.isfinite(out["logit"]).all()) + + def test_balanced_pos_weight(self): + batch = self._batch(range(6)) + plain = self.model(**batch)["loss"] + self.model.set_pos_weight("balanced", [self.dataset[i] for i in range(6)]) + torch.testing.assert_close(self.model.pos_weight, + torch.tensor([1.0, 2.0, 1.0, 0.0])) + self.assertFalse(torch.allclose(plain, self.model(**batch)["loss"])) + + def test_invalid_arguments(self): + with self.assertRaises(ValueError): + APRICOTM(self.dataset, feature_key="missing") + with self.assertRaises(ValueError): + APRICOTM(self.dataset, feature_key="static") + with self.assertRaises(ValueError): + APRICOTM(self.dataset, top_k=0) + + +class TestSelectiveScan(unittest.TestCase): + def test_matches_the_recurrence(self): + torch.manual_seed(0) + log_decay = -torch.rand(2, 50, 3, 4) * 3 + drive = torch.randn(2, 50, 3, 4) + state = torch.zeros(2, 3, 4) + expected = [] + for t in range(50): + state = torch.exp(log_decay[:, t]) * state + drive[:, t] + expected.append(state) + for chunk_size in (1, 7, 32, 64): + torch.testing.assert_close( + selective_scan(log_decay, drive, chunk_size), + torch.stack(expected, 1), atol=1e-4, rtol=1e-4, + ) + + def test_strong_decay_stays_finite(self): + log_decay = torch.full((1, 400, 2), -20.0, requires_grad=True) + drive = torch.randn(1, 400, 2, requires_grad=True) + states = selective_scan(log_decay, drive) + torch.testing.assert_close(states, drive.detach(), atol=1e-4, rtol=1e-3) + states.sum().backward() + self.assertTrue(torch.isfinite(log_decay.grad).all()) + self.assertTrue(torch.isfinite(drive.grad).all()) + + def test_mixer_is_causal(self): + torch.manual_seed(0) + mixer = SelectiveSSM(d_model=8, d_state=4) + x = torch.randn(1, 10, 8) + changed = x.clone() + changed[:, 6:] = torch.randn(1, 4, 8) + with torch.no_grad(): + torch.testing.assert_close(mixer(x)[:, :6], mixer(changed)[:, :6]) + + +if __name__ == "__main__": + unittest.main() From 51beab522274647d9c1c199fa51463e9812e42c2 Mon Sep 17 00:00:00 2001 From: solarsys Date: Wed, 4 Nov 2026 13:15:41 -0800 Subject: [PATCH 2/6] Address review: unknown outcome, death tolerance test, notebook notes - ICUAcuityMIMIC4: a stay whose admission has no admissions row no longer gets a "discharge" final state. Its outcome is unknown, so the sample predicting the last interval is dropped; earlier windows stay. Documented in the class docstring. - Tests for the missing-admission case and for the death tolerance (death within death_tolerance_hours of ICU discharge is deceased). - Notebook: the setup text matches the install cell (GitHub master), and a note on lowering batch_size or max_seq_len on small machines. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BdtuVKBLhWpYbhTQbaZaTt --- examples/apricotm_mimic4_acuity.ipynb | 6 ++-- pyhealth/tasks/acuity_mimic4.py | 21 ++++++++---- tests/core/test_apricotm.py | 49 +++++++++++++++++++++------ 3 files changed, 57 insertions(+), 19 deletions(-) diff --git a/examples/apricotm_mimic4_acuity.ipynb b/examples/apricotm_mimic4_acuity.ipynb index 5b980b72ef..3dffd060bc 100644 --- a/examples/apricotm_mimic4_acuity.ipynb +++ b/examples/apricotm_mimic4_acuity.ipynb @@ -28,7 +28,7 @@ "source": [ "## Setup\n", "\n", - "Until the PR is merged, install PyHealth from its branch. After the merge, install from `sunlabuiuc/PyHealth` master instead (`pip install \"git+https://github.com/sunlabuiuc/PyHealth\"`), or `pip install pyhealth` once it is released. The cell only installs on Colab." + "On Colab, the next cell installs PyHealth from GitHub master (`sunlabuiuc/PyHealth`), which has APRICOT-M once this PR is merged. After the next PyPI release, `pip install pyhealth` is enough. Elsewhere the cell does nothing." ] }, { @@ -272,7 +272,9 @@ "source": [ "### Train and evaluate on the demo\n", "\n", - "The demo gives about 3,000 four-hour windows from about 130 ICU stays. Ten epochs took about 15 minutes on a laptop CPU (much less on a GPU)." + "The demo gives about 3,000 four-hour windows from about 130 ICU stays. Ten epochs took about 15 minutes on a laptop CPU (much less on a GPU).\n", + "\n", + "**Memory.** The selective scan keeps a state for every event, so batch size 128 with up to 512 events per sample can need a lot of memory. On a small machine or GPU, pass a smaller `batch_size` to `run` (e.g. 32), or read fewer events per sample with `APRICOTM(..., max_seq_len=256)` in `run`." ] }, { diff --git a/pyhealth/tasks/acuity_mimic4.py b/pyhealth/tasks/acuity_mimic4.py index d1bcc59946..16690c5ec2 100644 --- a/pyhealth/tasks/acuity_mimic4.py +++ b/pyhealth/tasks/acuity_mimic4.py @@ -64,7 +64,12 @@ class ICUAcuityMIMIC4(_YAIBMIMIC4Task): ``stable`` otherwise. The last interval of the stay is ``deceased`` when the patient died in the ICU, and ``discharge`` when the patient left the ICU alive (with ``discharge_home_only``, only when the hospital - discharged the patient home within 24 hours of leaving the ICU). + discharged the patient home within 24 hours of leaving the ICU; + otherwise it keeps its stable or unstable state). A death up to + ``death_tolerance_hours`` after the recorded ICU discharge counts as an + ICU death. When the stay's admission has no ``admissions`` row, the + outcome is unknown, so the stay's last interval gets no label: the + sample predicting it is dropped, and the earlier windows are kept. One sample per stay and interval ``j >= 1`` (the prediction window) whose observation window, hours ``[4(j - 1), 4j)``, has at least one event: @@ -274,11 +279,9 @@ def _final_state( self, intime: datetime, outtime: datetime, - end: tuple[datetime | None, bool, datetime | None] | None, + end: tuple[datetime | None, bool, datetime | None], ) -> str | None: - """``deceased``, ``discharge`` or None for the last interval.""" - if end is None: - return "discharge" if not self.discharge_home_only else None + """``deceased``, ``discharge`` or None (keep the therapy state).""" death, home, dischtime = end tolerance = timedelta(hours=self.death_tolerance_hours) if death is not None and intime < death <= outtime + tolerance: @@ -332,7 +335,11 @@ def __call__(self, patient: Any) -> list[dict[str, Any]]: n_intervals = math.ceil(los / w) flags = self._interval_flags(therapies.get(stay_id, []), n_intervals) states = ["unstable" if f else "stable" for f in flags] - final = self._final_state(intime, outtime, ends.get(hadm_id)) + end = ends.get(hadm_id) + # Without an admissions row the outcome is unknown: no sample + # predicts the last interval. + n_windows = n_intervals if end is not None else n_intervals - 1 + final = None if end is None else self._final_state(intime, outtime, end) if final is not None: states[-1] = final @@ -340,7 +347,7 @@ def __call__(self, patient: Any) -> list[dict[str, Any]]: features = stay_events["feature"].to_list() values = stay_events["value"].to_list() start = 0 - for j in range(1, n_intervals): + for j in range(1, n_windows): lo, hi = (j - 1) * w, j * w while start < len(hours) and hours[start] < lo: start += 1 diff --git a/tests/core/test_apricotm.py b/tests/core/test_apricotm.py index 6f198f4ed8..59226d9b24 100644 --- a/tests/core/test_apricotm.py +++ b/tests/core/test_apricotm.py @@ -49,21 +49,25 @@ def _input(itemid, start, end, stay_id=10): def _patient(*, hours=18.0, age=60, deathtime=None, location="HOME", - vitals=True, hr_hours=(4.5, 8.5, 12.5), extra=()): + vitals=True, hr_hours=(4.5, 8.5, 12.5), extra=(), admission=True): """One admission with one ICU stay (stay_id 10) of ``hours`` hours. The six vitals are charted at hour 0.5 and a heart rate at ``hr_hours``. + With ``admission=False`` the admission has no ``admissions`` row. """ outtime = T0 + timedelta(hours=hours) - rows = [ - _event("patients", None, anchor_age=age, gender="F"), - _event("admissions", T0 - timedelta(hours=5), hadm_id=1, - dischtime=_fmt(outtime + timedelta(hours=2)), - deathtime=None if deathtime is None else _fmt(deathtime), - hospital_expire_flag=int(deathtime is not None), - discharge_location="DIED" if deathtime else location), - _event("icustays", T0, stay_id=10, hadm_id=1, outtime=_fmt(outtime)), - ] + rows = [_event("patients", None, anchor_age=age, gender="F")] + if admission: + rows.append( + _event("admissions", T0 - timedelta(hours=5), hadm_id=1, + dischtime=_fmt(outtime + timedelta(hours=2)), + deathtime=None if deathtime is None else _fmt(deathtime), + hospital_expire_flag=int(deathtime is not None), + discharge_location="DIED" if deathtime else location) + ) + rows.append( + _event("icustays", T0, stay_id=10, hadm_id=1, outtime=_fmt(outtime)) + ) if vitals: for itemid, value in VITALS.items(): rows.append( @@ -139,6 +143,31 @@ def test_death_after_icu_discharge_is_a_discharge(self): samples = self.task(_patient(deathtime=death, hr_hours=(4.5, 8.5, 12.5, 15.0))) self.assertEqual(_positives(samples[-1]), {"discharge"}) + def test_death_within_tolerance_of_icu_discharge(self): + hr = (4.5, 8.5, 12.5, 15.0) + outtime = T0 + timedelta(hours=18) + within = self.task( + _patient(deathtime=outtime + timedelta(minutes=50), hr_hours=hr) + ) + self.assertEqual(_positives(within[-1]), {"deceased"}) + beyond = self.task( + _patient(deathtime=outtime + timedelta(minutes=70), hr_hours=hr) + ) + self.assertEqual(_positives(beyond[-1]), {"discharge"}) + strict = ICUAcuityMIMIC4(death_tolerance_hours=0) + late = strict(_patient(deathtime=outtime + timedelta(minutes=50), hr_hours=hr)) + self.assertEqual(_positives(late[-1]), {"discharge"}) + + def test_missing_admission_row_drops_the_last_window(self): + samples = self.task( + _patient(admission=False, hr_hours=(4.5, 8.5, 12.5, 15.0), + extra=self.therapies) + ) + self.assertEqual([s["window"] for s in samples], [1, 2, 3]) + self.assertEqual( + _positives(samples[-1]), {"unstable", "mv_stop", "vp_onset"} + ) + def test_discharge_home_only(self): task = ICUAcuityMIMIC4(discharge_home_only=True) hr = (4.5, 8.5, 12.5, 15.0) From 29408c5bf57b913d1958dd38469d0dcb8b31c6f9 Mon Sep 17 00:00:00 2001 From: solarsys Date: Thu, 5 Nov 2026 16:16:22 -0800 Subject: [PATCH 3/6] Share one SelectiveSSM between ARMR and APRICOT-M Address review on #1383: - Move ARMR's SelectiveSSM to pyhealth/models/selective_ssm.py (still importable from pyhealth.models.armr) and remove APRICOT-M's near-copy. The block gains backwards-compatible options: a padding mask in forward and scan="parallel" (the chunked log-space selective_scan). The default path is unchanged; a test checks it is bit-identical to the previous ARMR block, and that the parallel scan and masking agree with the loop. - Comment that time_scale=720 follows the authors' min-max scaling of absolute hours over stays of at most 30 days. - ICUAcuityMIMIC4 reuses the vasopressor and invasive-ventilation item IDs of the YAIB sepsis task instead of re-declaring them. - Notebook: run/train_apricotm take max_seq_len; Part 2 mentions a smaller batch size. - Explain the pos_weight of 0 for an always-positive label in the test. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BdtuVKBLhWpYbhTQbaZaTt --- docs/api/models/pyhealth.models.APRICOTM.rst | 9 +- examples/apricotm_mimic4_acuity.ipynb | 15 +- pyhealth/models/__init__.py | 2 + pyhealth/models/apricotm.py | 195 +++---------------- pyhealth/models/armr.py | 66 +------ pyhealth/models/selective_ssm.py | 182 +++++++++++++++++ pyhealth/tasks/acuity_mimic4.py | 19 +- pyhealth/tasks/yaib_mimic4.py | 24 ++- tests/core/test_apricotm.py | 41 +--- tests/core/test_selective_ssm.py | 133 +++++++++++++ 10 files changed, 390 insertions(+), 296 deletions(-) create mode 100644 pyhealth/models/selective_ssm.py create mode 100644 tests/core/test_selective_ssm.py diff --git a/docs/api/models/pyhealth.models.APRICOTM.rst b/docs/api/models/pyhealth.models.APRICOTM.rst index 07973e2698..96fec7293a 100644 --- a/docs/api/models/pyhealth.models.APRICOTM.rst +++ b/docs/api/models/pyhealth.models.APRICOTM.rst @@ -22,9 +22,10 @@ probability. This is a clean reimplementation from the paper. The authors' code (https://github.com/iheallab/apricotM) is GPL-3.0, so none of it was -copied; it was only read to confirm details. The Mamba blocks are written in -pure PyTorch (a chunked parallel selective scan), so the CUDA ``mamba_ssm`` -package is not needed and the model runs on CPU. +copied; it was only read to confirm details. The Mamba blocks are +:class:`~pyhealth.models.SelectiveSSM`, the pure PyTorch block shared with +:class:`~pyhealth.models.ARMR`, run with its chunked parallel selective scan, +so the CUDA ``mamba_ssm`` package is not needed and the model runs on CPU. Inputs and outputs ------------------ @@ -50,4 +51,4 @@ API :members: :show-inheritance: -.. autofunction:: pyhealth.models.apricotm.selective_scan +.. autofunction:: pyhealth.models.selective_ssm.selective_scan diff --git a/examples/apricotm_mimic4_acuity.ipynb b/examples/apricotm_mimic4_acuity.ipynb index 3dffd060bc..814a0165c7 100644 --- a/examples/apricotm_mimic4_acuity.ipynb +++ b/examples/apricotm_mimic4_acuity.ipynb @@ -172,8 +172,10 @@ " return float(np.mean(values)) if values else float(\"nan\")\n", "\n", "\n", - "def train_apricotm(train_part, train_dl, val_dl, epochs, patience=5):\n", - " model = APRICOTM(train_part, static_key=\"static\").to(device)\n", + "def train_apricotm(train_part, train_dl, val_dl, epochs, patience=5,\n", + " max_seq_len=512):\n", + " model = APRICOTM(train_part, static_key=\"static\",\n", + " max_seq_len=max_seq_len).to(device)\n", " model.set_pos_weight(\"balanced\", train_part)\n", " optimizer = torch.optim.Adam(model.parameters(), lr=3e-4, weight_decay=1e-5)\n", " best, best_state, waited = -1.0, None, 0\n", @@ -231,7 +233,7 @@ " return auroc_auprc(y_test, y_prob)\n", "\n", "\n", - "def run(root, cache_dir, epochs, batch_size=128, num_workers=1):\n", + "def run(root, cache_dir, epochs, batch_size=128, num_workers=1, max_seq_len=512):\n", " dataset = MIMIC4EHRDataset(root=root, tables=TABLES_NEEDED, cache_dir=cache_dir,\n", " num_workers=num_workers)\n", " parts = dataset.set_task(ICUAcuityMIMIC4(), num_workers=num_workers,\n", @@ -244,7 +246,8 @@ " for i, p in enumerate(parts)\n", " )\n", " start = time.time()\n", - " model = train_apricotm(parts[0], train_dl, val_dl, epochs)\n", + " model = train_apricotm(parts[0], train_dl, val_dl, epochs,\n", + " max_seq_len=max_seq_len)\n", " print(f\"APRICOT-M trained in {time.time() - start:.0f}s\")\n", " return {\"APRICOT-M\": auroc_auprc(*predict(model, test_dl)),\n", " \"LogReg (window stats)\": logistic_baseline(parts)}\n", @@ -274,7 +277,7 @@ "\n", "The demo gives about 3,000 four-hour windows from about 130 ICU stays. Ten epochs took about 15 minutes on a laptop CPU (much less on a GPU).\n", "\n", - "**Memory.** The selective scan keeps a state for every event, so batch size 128 with up to 512 events per sample can need a lot of memory. On a small machine or GPU, pass a smaller `batch_size` to `run` (e.g. 32), or read fewer events per sample with `APRICOTM(..., max_seq_len=256)` in `run`." + "**Memory.** The selective scan keeps a state for every event, so batch size 128 with up to 512 events per sample can need a lot of memory. On a small machine or GPU, pass a smaller `batch_size` to `run` (e.g. 32), or read fewer events per sample with `run(..., max_seq_len=256)`." ] }, { @@ -301,7 +304,7 @@ "source": [ "## Part 2: full MIMIC-IV (credentialed)\n", "\n", - "MIMIC-IV requires PhysioNet credentialing ([physionet.org/content/mimiciv](https://physionet.org/content/mimiciv/)). Point `MIMIC4_ROOT` at your copy (the folder with `hosp/` and `icu/`), e.g. on a mounted Google Drive, and use a GPU runtime. Building the event table reads `chartevents` once and caches it in `cache_dir`; MIMIC-IV gives several hundred thousand windows, so expect a long first run. The authors train up to 100 epochs with early stopping." + "MIMIC-IV requires PhysioNet credentialing ([physionet.org/content/mimiciv](https://physionet.org/content/mimiciv/)). Point `MIMIC4_ROOT` at your copy (the folder with `hosp/` and `icu/`), e.g. on a mounted Google Drive, and use a GPU runtime. Building the event table reads `chartevents` once and caches it in `cache_dir`; MIMIC-IV gives several hundred thousand windows, so expect a long first run. The authors train up to 100 epochs with early stopping. If training runs out of GPU memory, pass a smaller `batch_size` (e.g. `run(..., batch_size=32)`) or `max_seq_len`." ] }, { diff --git a/pyhealth/models/__init__.py b/pyhealth/models/__init__.py index 3b1c7ab204..2af7c27535 100644 --- a/pyhealth/models/__init__.py +++ b/pyhealth/models/__init__.py @@ -82,6 +82,8 @@ from .trajsurv import TrajSurv as TrajSurv from .knowrare import KnowRare as KnowRare from .apricotm import APRICOTM as APRICOTM, SelectiveSSM as SelectiveSSM +from .apricotm import APRICOTM as APRICOTM +from .selective_ssm import SelectiveSSM as SelectiveSSM from .heartlang import ( HeartLang as HeartLang, HeartLangBackbone as HeartLangBackbone, diff --git a/pyhealth/models/apricotm.py b/pyhealth/models/apricotm.py index 3c2438679f..aa3a6fe869 100644 --- a/pyhealth/models/apricotm.py +++ b/pyhealth/models/apricotm.py @@ -21,10 +21,11 @@ here; it was only read to confirm details (the default sizes below are the ones it trains with). Differences: -- The Mamba blocks are written in pure PyTorch (the selective scan of Gu - and Dao, 2023, computed in parallel in log space), so the CUDA - ``mamba_ssm`` package is not needed and the model runs on CPU. It uses - more memory than the fused kernel on long sequences. +- The Mamba blocks are :class:`~pyhealth.models.SelectiveSSM`, the pure + PyTorch block shared with ARMR, with its parallel log-space scan (Gu and + Dao, 2023), so the CUDA ``mamba_ssm`` package is not needed and the + model runs on CPU. It uses more memory than the fused kernel on long + sequences. - Padding is masked: padded positions do not update the state and are excluded from top-k pooling, so a sample's prediction does not depend on the other samples in its batch. @@ -47,173 +48,9 @@ from pyhealth.datasets import SampleDataset from pyhealth.models.base_model import BaseModel +from pyhealth.models.selective_ssm import SelectiveSSM -__all__ = ["APRICOTM", "SelectiveSSM", "selective_scan"] - - -def selective_scan(log_decay: Tensor, drive: Tensor, chunk_size: int = 32) -> Tensor: - """Parallel scan of ``h_t = exp(log_decay_t) * h_{t-1} + drive_t``, ``h_0 = 0``. - - Computed along dimension 1 in log space: within a chunk, with ``S_t`` - the cumulative sum of ``log_decay`` since the chunk start, - ``h_t = exp(S_t) h_start + sum_{s <= t} exp(S_t - S_s) drive_s``. The - positive and negative parts of ``drive`` are summed separately with - ``logcumsumexp``, so no ``exp(-S)`` can overflow; chunking keeps ``S`` - small enough for float32 precision. - - Args: - log_decay: Non-positive log decay factors, shape ``[B, L, ...]``. - drive: Inputs, same shape. - chunk_size: Steps per chunk. - - Returns: - The states ``h``, same shape. - - Examples: - >>> import torch - >>> log_decay = torch.log(torch.tensor([[0.5, 0.5, 0.5]])) - >>> drive = torch.tensor([[1.0, -2.0, 4.0]]) - >>> selective_scan(log_decay, drive) # h = 1, 0.5 - 2, -0.75 + 4 - tensor([[ 1.0000, -1.5000, 3.2500]]) - """ - very_negative = -1e30 - - def part(values: Tensor, cumulative: Tensor) -> Tensor: - positive = values > 0 - log_values = torch.where( - positive, torch.log(torch.where(positive, values, 1.0)), very_negative - ) - return torch.exp( - torch.logcumsumexp(log_values - cumulative, dim=1) + cumulative - ) - - chunks = [] - carry = None - for begin in range(0, log_decay.shape[1], chunk_size): - decay = log_decay[:, begin : begin + chunk_size] - inputs = drive[:, begin : begin + chunk_size] - cumulative = torch.cumsum(decay, dim=1) - states = part(inputs, cumulative) - part(-inputs, cumulative) - if carry is not None: - states = states + torch.exp(cumulative) * carry.unsqueeze(1) - carry = states[:, -1] - chunks.append(states) - if not chunks: - return drive.clone() - return torch.cat(chunks, dim=1) - - -class SelectiveSSM(nn.Module): - """A Mamba (selective state-space) mixer, in pure PyTorch. - - Follows Gu and Dao, "Mamba: Linear-Time Sequence Modeling with Selective - State Spaces" (2023): an input projection into a gated branch and an SSM - branch, a causal depthwise convolution, input-dependent step size - ``dt`` and matrices ``B`` and ``C``, a diagonal state matrix ``A``, and - the scan ``h_t = exp(dt_t A) h_{t-1} + dt_t B_t x_t``, - ``y_t = C_t h_t + D x_t``, computed in parallel by - :func:`selective_scan`. - - Args: - d_model: Input and output width. - d_state: State size ``N`` per channel. - d_conv: Kernel size of the causal depthwise convolution. - expand: Inner width is ``expand * d_model``. - dt_rank: Rank of the ``dt`` projection; ``ceil(d_model / 16)`` when - None. - - Examples: - >>> import torch - >>> mixer = SelectiveSSM(d_model=8, d_state=4) - >>> x = torch.randn(2, 5, 8) - >>> mixer(x).shape - torch.Size([2, 5, 8]) - >>> mask = torch.tensor([[1, 1, 1, 0, 0], [1, 1, 1, 1, 1]]).bool() - >>> y = mixer(x, mask) - >>> torch.allclose(y[0, :3], mixer(x[:1, :3])[0], atol=1e-6) - True - """ - - def __init__( - self, - d_model: int, - d_state: int = 16, - d_conv: int = 4, - expand: int = 2, - dt_rank: int | None = None, - ) -> None: - super().__init__() - self.d_model = d_model - self.d_state = d_state - self.d_inner = expand * d_model - self.dt_rank = dt_rank or math.ceil(d_model / 16) - self.in_proj = nn.Linear(d_model, 2 * self.d_inner, bias=False) - # Causal depthwise convolution, weight [D, d_conv] (last tap = now). - bound = 1.0 / math.sqrt(d_conv) - self.conv_weight = nn.Parameter( - torch.empty(self.d_inner, d_conv).uniform_(-bound, bound) - ) - self.conv_bias = nn.Parameter( - torch.empty(self.d_inner).uniform_(-bound, bound) - ) - self.x_proj = nn.Linear(self.d_inner, self.dt_rank + 2 * d_state, bias=False) - self.dt_proj = nn.Linear(self.dt_rank, self.d_inner) - # dt initialized log-uniformly in [1e-3, 1e-1] (Mamba's default). - dt = torch.exp( - torch.rand(self.d_inner) * (math.log(0.1) - math.log(1e-3)) - + math.log(1e-3) - ) - with torch.no_grad(): - self.dt_proj.bias.copy_(dt + torch.log(-torch.expm1(-dt))) - a = torch.arange(1, d_state + 1, dtype=torch.float32) - self.A_log = nn.Parameter(torch.log(a).repeat(self.d_inner, 1)) - self.D = nn.Parameter(torch.ones(self.d_inner)) - self.out_proj = nn.Linear(self.d_inner, d_model, bias=False) - - def _causal_conv(self, u: Tensor) -> Tensor: - """Depthwise causal convolution over time of ``u`` ``[B, L, D]``. - - Written as shifted sums: on CPU this is much faster to train than a - grouped ``nn.Conv1d``. - """ - taps = self.conv_weight.shape[1] - padded = F.pad(u, (0, 0, taps - 1, 0)) - length = u.shape[1] - out = self.conv_bias.expand_as(u) - for k in range(taps): - out = out + padded[:, k : k + length] * self.conv_weight[:, k] - return out - - def forward(self, x: Tensor, mask: Tensor | None = None) -> Tensor: - """Mixes a sequence. - - Args: - x: Shape ``[B, L, d_model]``. - mask: Optional bool ``[B, L]``, True for real positions. Padded - positions do not change the state; use right padding. - - Returns: - Shape ``[B, L, d_model]``; padded positions are zero. - """ - u, gate = self.in_proj(x).chunk(2, dim=-1) - if mask is not None: - u = u * mask.unsqueeze(-1) - u = F.silu(self._causal_conv(u)) - dt, b, c = self.x_proj(u).split( - [self.dt_rank, self.d_state, self.d_state], dim=-1 - ) - dt = F.softplus(self.dt_proj(dt)) # [B, L, D] - if mask is not None: - dt = dt * mask.unsqueeze(-1) - a = -torch.exp(self.A_log.float()) # [D, N] - log_decay = dt.unsqueeze(-1) * a # [B, L, D, N] - drive = (dt * u).unsqueeze(-1) * b.unsqueeze(2) # [B, L, D, N] - states = selective_scan(log_decay, drive) - y = torch.einsum("bldn,bln->bld", states, c) + u * self.D - y = self.out_proj(y * F.silu(gate)) - if mask is not None: - y = y * mask.unsqueeze(-1) - return y +__all__ = ["APRICOTM"] class _MambaStack(nn.Module): @@ -223,8 +60,18 @@ def __init__(self, d_model: int, n_layers: int, **ssm_kwargs) -> None: super().__init__() self.norms = nn.ModuleList(nn.LayerNorm(d_model) for _ in range(n_layers)) self.mixers = nn.ModuleList( - SelectiveSSM(d_model, **ssm_kwargs) for _ in range(n_layers) + SelectiveSSM(d_model, scan="parallel", **ssm_kwargs) + for _ in range(n_layers) ) + for mixer in self.mixers: + # dt initialized log-uniformly in [1e-3, 1e-1], as mamba_ssm does. + dt = torch.exp( + torch.rand(mixer.dt_proj.bias.shape) + * (math.log(0.1) - math.log(1e-3)) + + math.log(1e-3) + ) + with torch.no_grad(): + mixer.dt_proj.bias.copy_(dt + torch.log(-torch.expm1(-dt))) self.final_norm = nn.LayerNorm(d_model) def forward(self, x: Tensor, mask: Tensor) -> Tensor: @@ -350,8 +197,8 @@ def __init__( self.encoder = _MambaStack( embedding_dim, num_layers, - d_state=state_size, - d_conv=conv_kernel, + state_size=state_size, + conv_size=conv_kernel, expand=expand, ) self.pool_mlp = nn.Sequential( @@ -417,6 +264,8 @@ def _dense(self, value) -> tuple[Tensor, Tensor, Tensor, Tensor]: index = (starts[:, None] + position[None, :]).clamp(max=tokens.shape[0] - 1) dense_tokens = torch.where(mask, tokens[index], 0) dense_values = torch.where(mask, torch.nan_to_num(values[index]), 0.0) + # Times stay absolute (hours since ICU admission), as in the authors' + # code, which min-max scales them over the training stays (<= 30 days). dense_times = torch.where(mask, times[index] / self.time_scale, 0.0) return dense_tokens, dense_values, dense_times, mask diff --git a/pyhealth/models/armr.py b/pyhealth/models/armr.py index 014fea27aa..319bb5fba8 100644 --- a/pyhealth/models/armr.py +++ b/pyhealth/models/armr.py @@ -24,6 +24,7 @@ from pyhealth.datasets import SampleDataset from pyhealth.models.base_model import BaseModel from pyhealth.models.embedding import EmbeddingModel +from pyhealth.models.selective_ssm import SelectiveSSM from pyhealth.models.utils import ( ddi_adjacency, ehr_cooccurrence_adjacency, @@ -49,71 +50,6 @@ def _reverse_padded(x: torch.Tensor, lengths: torch.Tensor) -> torch.Tensor: return x.gather(1, idx.unsqueeze(-1).expand_as(x)) -class SelectiveSSM(nn.Module): - """A Mamba block (selective state-space model) in pure PyTorch. - - Paper: Albert Gu and Tri Dao. "Mamba: Linear-Time Sequence Modeling with - Selective State Spaces." 2023. The scan is a plain loop over time, which - is fast enough for visit sequences (tens of steps). - - This differs from :class:`pyhealth.models.ehrmamba.MambaBlock`: there the - step size and the ``B`` and ``C`` matrices are fixed per channel (a - time-invariant SSM computed as a convolution), while here they are - computed from each input step (Mamba's selection mechanism), which ARMR's - Eq. 2 relies on. Hence the separate block. - - Args: - dim: input and output size. - state_size: SSM state size per channel. Default is 16. - expand: inner width as a multiple of ``dim``. Default is 2. - conv_size: width of the causal depthwise convolution. Default is 4. - - Examples: - >>> block = SelectiveSSM(dim=8) - >>> block(torch.randn(2, 5, 8)).shape - torch.Size([2, 5, 8]) - """ - - def __init__( - self, dim: int, state_size: int = 16, expand: int = 2, conv_size: int = 4 - ): - super().__init__() - inner = expand * dim - self.dt_rank = math.ceil(dim / 16) - self.state_size = state_size - self.in_proj = nn.Linear(dim, 2 * inner) - self.conv = nn.Conv1d( - inner, inner, conv_size, groups=inner, padding=conv_size - 1 - ) - self.x_proj = nn.Linear(inner, self.dt_rank + 2 * state_size, bias=False) - self.dt_proj = nn.Linear(self.dt_rank, inner) - a = torch.arange(1, state_size + 1, dtype=torch.float).repeat(inner, 1) - self.a_log = nn.Parameter(torch.log(a)) - self.d = nn.Parameter(torch.ones(inner)) - self.out_proj = nn.Linear(inner, dim) - - def forward(self, x: torch.Tensor) -> torch.Tensor: - """Runs the block over ``x`` of shape [batch, steps, dim].""" - steps = x.size(1) - u, gate = self.in_proj(x).chunk(2, dim=-1) - u = self.conv(u.transpose(1, 2))[..., :steps].transpose(1, 2) - u = F.silu(u) - dt, b, c = self.x_proj(u).split( - [self.dt_rank, self.state_size, self.state_size], dim=-1 - ) - dt = F.softplus(self.dt_proj(dt)) # [batch, steps, inner] - a = -torch.exp(self.a_log) # [inner, state] - da = torch.exp(dt.unsqueeze(-1) * a) # [batch, steps, inner, state] - dbu = dt.unsqueeze(-1) * b.unsqueeze(2) * u.unsqueeze(-1) - h = torch.zeros_like(da[:, 0]) - ys = [] - for t in range(steps): - h = da[:, t] * h + dbu[:, t] - ys.append((h * c[:, t].unsqueeze(1)).sum(-1)) - y = torch.stack(ys, dim=1) + u * self.d - return self.out_proj(y * F.silu(gate)) - - class PiecewiseTemporalLearning(nn.Module): """Piecewise Temporal Learning (PTL), ARMR Eq. 1-4. diff --git a/pyhealth/models/selective_ssm.py b/pyhealth/models/selective_ssm.py new file mode 100644 index 0000000000..e4c6e67ce8 --- /dev/null +++ b/pyhealth/models/selective_ssm.py @@ -0,0 +1,182 @@ +"""A selective state-space (Mamba) block in pure PyTorch. + +Shared by :class:`~pyhealth.models.ARMR` (over visits) and +:class:`~pyhealth.models.APRICOTM` (over clinical events). +""" + +from __future__ import annotations + +import math + +import torch +import torch.nn.functional as F +from torch import Tensor, nn + +__all__ = ["SelectiveSSM", "selective_scan"] + + +def selective_scan(log_decay: Tensor, drive: Tensor, chunk_size: int = 32) -> Tensor: + """Parallel scan of ``h_t = exp(log_decay_t) * h_{t-1} + drive_t``, ``h_0 = 0``. + + Computed along dimension 1 in log space: within a chunk, with ``S_t`` + the cumulative sum of ``log_decay`` since the chunk start, + ``h_t = exp(S_t) h_start + sum_{s <= t} exp(S_t - S_s) drive_s``. The + positive and negative parts of ``drive`` are summed separately with + ``logcumsumexp``, so no ``exp(-S)`` can overflow; chunking keeps ``S`` + small enough for float32 precision. + + Args: + log_decay: Non-positive log decay factors, shape ``[B, L, ...]``. + drive: Inputs, same shape. + chunk_size: Steps per chunk. + + Returns: + The states ``h``, same shape. + + Examples: + >>> import torch + >>> log_decay = torch.log(torch.tensor([[0.5, 0.5, 0.5]])) + >>> drive = torch.tensor([[1.0, -2.0, 4.0]]) + >>> selective_scan(log_decay, drive) # h = 1, 0.5 - 2, -0.75 + 4 + tensor([[ 1.0000, -1.5000, 3.2500]]) + """ + very_negative = -1e30 + + def part(values: Tensor, cumulative: Tensor) -> Tensor: + positive = values > 0 + log_values = torch.where( + positive, torch.log(torch.where(positive, values, 1.0)), very_negative + ) + return torch.exp( + torch.logcumsumexp(log_values - cumulative, dim=1) + cumulative + ) + + chunks = [] + carry = None + for begin in range(0, log_decay.shape[1], chunk_size): + decay = log_decay[:, begin : begin + chunk_size] + inputs = drive[:, begin : begin + chunk_size] + cumulative = torch.cumsum(decay, dim=1) + states = part(inputs, cumulative) - part(-inputs, cumulative) + if carry is not None: + states = states + torch.exp(cumulative) * carry.unsqueeze(1) + carry = states[:, -1] + chunks.append(states) + if not chunks: + return drive.clone() + return torch.cat(chunks, dim=1) + + +class SelectiveSSM(nn.Module): + """A Mamba block (selective state-space model) in pure PyTorch. + + Paper: Albert Gu and Tri Dao. "Mamba: Linear-Time Sequence Modeling with + Selective State Spaces." 2023. An input projection into a gated branch + and an SSM branch, a causal depthwise convolution, input-dependent step + size ``dt`` and matrices ``B`` and ``C``, a diagonal state matrix ``A``, + and the scan ``h_t = exp(dt_t A) h_{t-1} + dt_t B_t x_t``, + ``y_t = C_t h_t + D x_t``. + + By default (``scan="loop"``) the scan is a plain loop over time, which + is fast enough for short sequences such as visits (tens of steps). + ``scan="parallel"`` computes it with :func:`selective_scan` instead, + which is much faster on long sequences (hundreds of events) and gives + the same result up to floating-point rounding. + + This differs from :class:`pyhealth.models.ehrmamba.MambaBlock`: there the + step size and the ``B`` and ``C`` matrices are fixed per channel (a + time-invariant SSM computed as a convolution), while here they are + computed from each input step (Mamba's selection mechanism), which ARMR's + Eq. 2 and APRICOT-M rely on. Hence the separate block. + + Args: + dim: input and output size. + state_size: SSM state size per channel. Default is 16. + expand: inner width as a multiple of ``dim``. Default is 2. + conv_size: width of the causal depthwise convolution. Default is 4. + scan: ``"loop"`` (default) or ``"parallel"``. + chunk_size: steps per chunk of the parallel scan. Default is 32. + + Examples: + >>> import torch + >>> block = SelectiveSSM(dim=8) + >>> block(torch.randn(2, 5, 8)).shape + torch.Size([2, 5, 8]) + >>> block = SelectiveSSM(dim=8, scan="parallel") + >>> x = torch.randn(2, 5, 8) + >>> mask = torch.tensor([[1, 1, 1, 0, 0], [1, 1, 1, 1, 1]]).bool() + >>> y = block(x, mask) + >>> torch.allclose(y[0, :3], block(x[:1, :3])[0], atol=1e-6) + True + """ + + def __init__( + self, + dim: int, + state_size: int = 16, + expand: int = 2, + conv_size: int = 4, + scan: str = "loop", + chunk_size: int = 32, + ): + super().__init__() + if scan not in ("loop", "parallel"): + raise ValueError(f"scan must be 'loop' or 'parallel', got {scan!r}") + inner = expand * dim + self.dt_rank = math.ceil(dim / 16) + self.state_size = state_size + self.scan = scan + self.chunk_size = chunk_size + self.in_proj = nn.Linear(dim, 2 * inner) + self.conv = nn.Conv1d( + inner, inner, conv_size, groups=inner, padding=conv_size - 1 + ) + self.x_proj = nn.Linear(inner, self.dt_rank + 2 * state_size, bias=False) + self.dt_proj = nn.Linear(self.dt_rank, inner) + a = torch.arange(1, state_size + 1, dtype=torch.float).repeat(inner, 1) + self.a_log = nn.Parameter(torch.log(a)) + self.d = nn.Parameter(torch.ones(inner)) + self.out_proj = nn.Linear(inner, dim) + + def forward(self, x: Tensor, mask: Tensor | None = None) -> Tensor: + """Runs the block over ``x`` of shape [batch, steps, dim]. + + Args: + x: input sequences, shape [batch, steps, dim]. + mask: optional bool tensor [batch, steps], True for real steps. + Padded steps do not change the state and their outputs are + zero; use right padding (the convolution is causal, so real + steps never see later padding). + + Returns: + Tensor of shape [batch, steps, dim]. + """ + steps = x.size(1) + u, gate = self.in_proj(x).chunk(2, dim=-1) + u = self.conv(u.transpose(1, 2))[..., :steps].transpose(1, 2) + u = F.silu(u) + dt, b, c = self.x_proj(u).split( + [self.dt_rank, self.state_size, self.state_size], dim=-1 + ) + dt = F.softplus(self.dt_proj(dt)) # [batch, steps, inner] + if mask is not None: + dt = dt * mask.unsqueeze(-1) # dt = 0: state kept, no input + a = -torch.exp(self.a_log) # [inner, state] + if self.scan == "parallel": + log_decay = dt.unsqueeze(-1) * a # [batch, steps, inner, state] + drive = (dt * u).unsqueeze(-1) * b.unsqueeze(2) + states = selective_scan(log_decay, drive, self.chunk_size) + y = torch.einsum("bldn,bln->bld", states, c) + else: + da = torch.exp(dt.unsqueeze(-1) * a) # [batch, steps, inner, state] + dbu = dt.unsqueeze(-1) * b.unsqueeze(2) * u.unsqueeze(-1) + h = torch.zeros_like(da[:, 0]) + ys = [] + for t in range(steps): + h = da[:, t] * h + dbu[:, t] + ys.append((h * c[:, t].unsqueeze(1)).sum(-1)) + y = torch.stack(ys, dim=1) + y = self.out_proj((y + u * self.d) * F.silu(gate)) + if mask is not None: + y = y * mask.unsqueeze(-1) + return y diff --git a/pyhealth/tasks/acuity_mimic4.py b/pyhealth/tasks/acuity_mimic4.py index 16690c5ec2..184e361fc2 100644 --- a/pyhealth/tasks/acuity_mimic4.py +++ b/pyhealth/tasks/acuity_mimic4.py @@ -26,17 +26,26 @@ import polars as pl -from .yaib_mimic4 import _parse_time, _YAIBMIMIC4Task +from .yaib_mimic4 import ( + _VASOPRESSOR_ITEMIDS, + _VENTILATION_ITEMIDS, + _parse_time, + _YAIBMIMIC4Task, +) # MIMIC-IV item IDs of the life-sustaining therapies (MetaVision items). -MECHANICAL_VENTILATION_ITEMIDS = (225792,) # procedureevents: Invasive Ventilation +# Invasive ventilation and the vasopressors shared with the YAIB sepsis task +# come from yaib_mimic4; the rest are only used here. +MECHANICAL_VENTILATION_ITEMIDS = ( # procedureevents: Invasive Ventilation + _VENTILATION_ITEMIDS["invasive"], +) CRRT_ITEMIDS = (225802, 225803, 225809) # procedureevents: CRRT, CVVHD, CVVHDF MASSIVE_TRANSFUSION_ITEMIDS = (229620,) # procedureevents: Massive Transfusion VASOPRESSOR_ITEMIDS = ( # inputevents - 221906, # norepinephrine - 221289, # epinephrine + _VASOPRESSOR_ITEMIDS["norepi"], # norepinephrine + _VASOPRESSOR_ITEMIDS["epi"], # epinephrine 229617, # epinephrine (second item) - 221662, # dopamine + _VASOPRESSOR_ITEMIDS["dopa"], # dopamine 222315, # vasopressin 221749, # phenylephrine ) diff --git a/pyhealth/tasks/yaib_mimic4.py b/pyhealth/tasks/yaib_mimic4.py index 812056cc08..a805d451fb 100644 --- a/pyhealth/tasks/yaib_mimic4.py +++ b/pyhealth/tasks/yaib_mimic4.py @@ -147,6 +147,18 @@ def _chart(*itemids: int, **kwargs: Any) -> _Item: _TIME_FORMAT = "%Y-%m-%d %H:%M:%S" +# MIMIC-IV MetaVision therapy item IDs, shared with ICUAcuityMIMIC4. +_VASOPRESSOR_ITEMIDS = { # inputevents + "dopa": 221662, + "norepi": 221906, + "dobu": 221653, + "epi": 221289, +} +_VENTILATION_ITEMIDS = { # procedureevents + "invasive": 225792, + "noninvasive": 225794, +} + def _item_lookup( features: dict[str, tuple[float | None, float | None, list[_Item]]], @@ -1132,10 +1144,10 @@ class YAIBSepsisMIMIC4(_YAIBMIMIC4Task): _SOFA_ITEMS: ClassVar[pl.DataFrame] = _item_lookup(_SOFA_INPUTS) # Vasopressor: (inputevents item ID, minimum rate, maximum rate). _VASOPRESSORS: ClassVar[dict[str, tuple[int, float, float]]] = { - "dopa": (221662, 0, 50), - "norepi": (221906, 0, 3), - "dobu": (221653, 0, 50), - "epi": (221289, 0, 1.5), + "dopa": (_VASOPRESSOR_ITEMIDS["dopa"], 0, 50), + "norepi": (_VASOPRESSOR_ITEMIDS["norepi"], 0, 3), + "dobu": (_VASOPRESSOR_ITEMIDS["dobu"], 0, 50), + "epi": (_VASOPRESSOR_ITEMIDS["epi"], 0, 1.5), } _ANTIBIOTICS: ClassVar[tuple[int, ...]] = ( 225798, 225837, 225838, 225840, 225842, 225843, 225844, 225845, 225847, @@ -1146,12 +1158,12 @@ class YAIBSepsisMIMIC4(_YAIBMIMIC4Task): 225900, 225902, 225903, 225905, 227691, 228003, ) # Invasive and non-invasive ventilation (procedureevents). - _VENTILATION: ClassVar[tuple[int, ...]] = (225792, 225794) + _VENTILATION: ClassVar[tuple[int, ...]] = tuple(_VENTILATION_ITEMIDS.values()) _INTUBATED_GCS: ClassVar[str] = "No Response-ETT" _EXTRA_ITEMIDS: ClassVar[dict[str, tuple[int, ...]]] = { "chartevents": (220739, 223901, 223900), - "inputevents": (221662, 221906, 221653, 221289, *_ANTIBIOTICS), + "inputevents": (*_VASOPRESSOR_ITEMIDS.values(), *_ANTIBIOTICS), "procedureevents": _VENTILATION, } _EXTRA_TABLES: ClassVar[tuple[str, ...]] = ( diff --git a/tests/core/test_apricotm.py b/tests/core/test_apricotm.py index 59226d9b24..8c559835bd 100644 --- a/tests/core/test_apricotm.py +++ b/tests/core/test_apricotm.py @@ -6,8 +6,7 @@ from pyhealth.data import Patient from pyhealth.datasets import create_sample_dataset, get_dataloader -from pyhealth.models import APRICOTM, SelectiveSSM -from pyhealth.models.apricotm import selective_scan +from pyhealth.models import APRICOTM from pyhealth.tasks import ICUAcuityMIMIC4 T0 = datetime(2150, 1, 1, 8, 0, 0) # noqa: DTZ001 - MIMIC times are naive @@ -327,6 +326,9 @@ def test_balanced_pos_weight(self): batch = self._batch(range(6)) plain = self.model(**batch)["loss"] self.model.set_pos_weight("balanced", [self.dataset[i] for i in range(6)]) + # BaseModel.set_pos_weight("balanced") gives negatives / positives, so + # the last label, positive in every sample, gets weight 0 (only labels + # with no positive at all fall back to 1). torch.testing.assert_close(self.model.pos_weight, torch.tensor([1.0, 2.0, 1.0, 0.0])) self.assertFalse(torch.allclose(plain, self.model(**batch)["loss"])) @@ -340,40 +342,5 @@ def test_invalid_arguments(self): APRICOTM(self.dataset, top_k=0) -class TestSelectiveScan(unittest.TestCase): - def test_matches_the_recurrence(self): - torch.manual_seed(0) - log_decay = -torch.rand(2, 50, 3, 4) * 3 - drive = torch.randn(2, 50, 3, 4) - state = torch.zeros(2, 3, 4) - expected = [] - for t in range(50): - state = torch.exp(log_decay[:, t]) * state + drive[:, t] - expected.append(state) - for chunk_size in (1, 7, 32, 64): - torch.testing.assert_close( - selective_scan(log_decay, drive, chunk_size), - torch.stack(expected, 1), atol=1e-4, rtol=1e-4, - ) - - def test_strong_decay_stays_finite(self): - log_decay = torch.full((1, 400, 2), -20.0, requires_grad=True) - drive = torch.randn(1, 400, 2, requires_grad=True) - states = selective_scan(log_decay, drive) - torch.testing.assert_close(states, drive.detach(), atol=1e-4, rtol=1e-3) - states.sum().backward() - self.assertTrue(torch.isfinite(log_decay.grad).all()) - self.assertTrue(torch.isfinite(drive.grad).all()) - - def test_mixer_is_causal(self): - torch.manual_seed(0) - mixer = SelectiveSSM(d_model=8, d_state=4) - x = torch.randn(1, 10, 8) - changed = x.clone() - changed[:, 6:] = torch.randn(1, 4, 8) - with torch.no_grad(): - torch.testing.assert_close(mixer(x)[:, :6], mixer(changed)[:, :6]) - - if __name__ == "__main__": unittest.main() diff --git a/tests/core/test_selective_ssm.py b/tests/core/test_selective_ssm.py new file mode 100644 index 0000000000..7e9aec41b0 --- /dev/null +++ b/tests/core/test_selective_ssm.py @@ -0,0 +1,133 @@ +import math +import unittest + +import torch +import torch.nn.functional as F +from torch import nn + +from pyhealth.models import SelectiveSSM +from pyhealth.models.armr import SelectiveSSM as ARMRSelectiveSSM +from pyhealth.models.selective_ssm import selective_scan + + +class _ARMRReferenceSSM(nn.Module): + """ARMR's SelectiveSSM before it moved to selective_ssm.py (#1371).""" + + def __init__(self, dim, state_size=16, expand=2, conv_size=4): + super().__init__() + inner = expand * dim + self.dt_rank = math.ceil(dim / 16) + self.state_size = state_size + self.in_proj = nn.Linear(dim, 2 * inner) + self.conv = nn.Conv1d( + inner, inner, conv_size, groups=inner, padding=conv_size - 1 + ) + self.x_proj = nn.Linear(inner, self.dt_rank + 2 * state_size, bias=False) + self.dt_proj = nn.Linear(self.dt_rank, inner) + a = torch.arange(1, state_size + 1, dtype=torch.float).repeat(inner, 1) + self.a_log = nn.Parameter(torch.log(a)) + self.d = nn.Parameter(torch.ones(inner)) + self.out_proj = nn.Linear(inner, dim) + + def forward(self, x): + steps = x.size(1) + u, gate = self.in_proj(x).chunk(2, dim=-1) + u = self.conv(u.transpose(1, 2))[..., :steps].transpose(1, 2) + u = F.silu(u) + dt, b, c = self.x_proj(u).split( + [self.dt_rank, self.state_size, self.state_size], dim=-1 + ) + dt = F.softplus(self.dt_proj(dt)) + a = -torch.exp(self.a_log) + da = torch.exp(dt.unsqueeze(-1) * a) + dbu = dt.unsqueeze(-1) * b.unsqueeze(2) * u.unsqueeze(-1) + h = torch.zeros_like(da[:, 0]) + ys = [] + for t in range(steps): + h = da[:, t] * h + dbu[:, t] + ys.append((h * c[:, t].unsqueeze(1)).sum(-1)) + y = torch.stack(ys, dim=1) + u * self.d + return self.out_proj(y * F.silu(gate)) + + +class TestSelectiveSSM(unittest.TestCase): + def setUp(self): + torch.manual_seed(0) + self.block = SelectiveSSM(dim=8, state_size=4) + self.x = torch.randn(3, 12, 8) + self.mask = torch.arange(12)[None, :] < torch.tensor([[12], [7], [1]]) + + def _parallel(self): + block = SelectiveSSM(dim=8, state_size=4, scan="parallel", chunk_size=5) + block.load_state_dict(self.block.state_dict()) + return block + + def test_one_class_shared_with_armr(self): + self.assertIs(ARMRSelectiveSSM, SelectiveSSM) + + def test_default_matches_the_previous_armr_block(self): + reference = _ARMRReferenceSSM(dim=8, state_size=4) + reference.load_state_dict(self.block.state_dict()) + with torch.no_grad(): + self.assertTrue(torch.equal(self.block(self.x), reference(self.x))) + + def test_parallel_scan_matches_the_loop(self): + parallel = self._parallel() + with torch.no_grad(): + torch.testing.assert_close(parallel(self.x), self.block(self.x), + atol=1e-5, rtol=1e-4) + torch.testing.assert_close(parallel(self.x, self.mask), + self.block(self.x, self.mask), + atol=1e-5, rtol=1e-4) + + def test_mask_ignores_padding(self): + for block in (self.block, self._parallel()): + with torch.no_grad(): + out = block(self.x, self.mask) + self.assertTrue((out[~self.mask] == 0).all()) + for i, length in enumerate((12, 7, 1)): + alone = block(self.x[i : i + 1, :length]) + torch.testing.assert_close(out[i : i + 1, :length], alone, + atol=1e-5, rtol=1e-4) + + def test_mixer_is_causal(self): + changed = self.x.clone() + changed[:, 6:] = torch.randn(3, 6, 8) + for block in (self.block, self._parallel()): + with torch.no_grad(): + torch.testing.assert_close(block(self.x)[:, :6], + block(changed)[:, :6]) + + def test_invalid_scan(self): + with self.assertRaises(ValueError): + SelectiveSSM(dim=8, scan="fast") + + +class TestSelectiveScan(unittest.TestCase): + def test_matches_the_recurrence(self): + torch.manual_seed(0) + log_decay = -torch.rand(2, 50, 3, 4) * 3 + drive = torch.randn(2, 50, 3, 4) + state = torch.zeros(2, 3, 4) + expected = [] + for t in range(50): + state = torch.exp(log_decay[:, t]) * state + drive[:, t] + expected.append(state) + for chunk_size in (1, 7, 32, 64): + torch.testing.assert_close( + selective_scan(log_decay, drive, chunk_size), + torch.stack(expected, 1), atol=1e-4, rtol=1e-4, + ) + + def test_strong_decay_stays_finite(self): + log_decay = torch.full((1, 400, 2), -20.0, requires_grad=True) + drive = torch.randn(1, 400, 2, requires_grad=True) + states = selective_scan(log_decay, drive) + torch.testing.assert_close(states, drive.detach(), atol=1e-4, rtol=1e-3) + states.sum().backward() + self.assertTrue(torch.isfinite(log_decay.grad).all()) + self.assertTrue(torch.isfinite(drive.grad).all()) + + +if __name__ == "__main__": + unittest.main() From 51997219fceda0643877d503089e962ab1b78e18 Mon Sep 17 00:00:00 2001 From: solarsys Date: Sun, 8 Nov 2026 23:32:38 -0500 Subject: [PATCH 4/6] Keep therapy item IDs local to each MIMIC-IV task YAIBSepsisMIMIC4 goes back to its own vasopressor and ventilation literals, and ICUAcuityMIMIC4 defines its own, so extending the acuity lists cannot change the sepsis labels (review on #1383). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BdtuVKBLhWpYbhTQbaZaTt --- pyhealth/tasks/acuity_mimic4.py | 21 +++++++-------------- pyhealth/tasks/yaib_mimic4.py | 24 ++++++------------------ 2 files changed, 13 insertions(+), 32 deletions(-) diff --git a/pyhealth/tasks/acuity_mimic4.py b/pyhealth/tasks/acuity_mimic4.py index 184e361fc2..1fed6ee1e7 100644 --- a/pyhealth/tasks/acuity_mimic4.py +++ b/pyhealth/tasks/acuity_mimic4.py @@ -26,26 +26,19 @@ import polars as pl -from .yaib_mimic4 import ( - _VASOPRESSOR_ITEMIDS, - _VENTILATION_ITEMIDS, - _parse_time, - _YAIBMIMIC4Task, -) +from .yaib_mimic4 import _parse_time, _YAIBMIMIC4Task # MIMIC-IV item IDs of the life-sustaining therapies (MetaVision items). -# Invasive ventilation and the vasopressors shared with the YAIB sepsis task -# come from yaib_mimic4; the rest are only used here. -MECHANICAL_VENTILATION_ITEMIDS = ( # procedureevents: Invasive Ventilation - _VENTILATION_ITEMIDS["invasive"], -) +# Kept local to this task on purpose: YAIBSepsisMIMIC4 holds its own copies +# of the shared IDs, so extending these lists cannot move the sepsis labels. +MECHANICAL_VENTILATION_ITEMIDS = (225792,) # procedureevents: Invasive Ventilation CRRT_ITEMIDS = (225802, 225803, 225809) # procedureevents: CRRT, CVVHD, CVVHDF MASSIVE_TRANSFUSION_ITEMIDS = (229620,) # procedureevents: Massive Transfusion VASOPRESSOR_ITEMIDS = ( # inputevents - _VASOPRESSOR_ITEMIDS["norepi"], # norepinephrine - _VASOPRESSOR_ITEMIDS["epi"], # epinephrine + 221906, # norepinephrine + 221289, # epinephrine 229617, # epinephrine (second item) - _VASOPRESSOR_ITEMIDS["dopa"], # dopamine + 221662, # dopamine 222315, # vasopressin 221749, # phenylephrine ) diff --git a/pyhealth/tasks/yaib_mimic4.py b/pyhealth/tasks/yaib_mimic4.py index a805d451fb..812056cc08 100644 --- a/pyhealth/tasks/yaib_mimic4.py +++ b/pyhealth/tasks/yaib_mimic4.py @@ -147,18 +147,6 @@ def _chart(*itemids: int, **kwargs: Any) -> _Item: _TIME_FORMAT = "%Y-%m-%d %H:%M:%S" -# MIMIC-IV MetaVision therapy item IDs, shared with ICUAcuityMIMIC4. -_VASOPRESSOR_ITEMIDS = { # inputevents - "dopa": 221662, - "norepi": 221906, - "dobu": 221653, - "epi": 221289, -} -_VENTILATION_ITEMIDS = { # procedureevents - "invasive": 225792, - "noninvasive": 225794, -} - def _item_lookup( features: dict[str, tuple[float | None, float | None, list[_Item]]], @@ -1144,10 +1132,10 @@ class YAIBSepsisMIMIC4(_YAIBMIMIC4Task): _SOFA_ITEMS: ClassVar[pl.DataFrame] = _item_lookup(_SOFA_INPUTS) # Vasopressor: (inputevents item ID, minimum rate, maximum rate). _VASOPRESSORS: ClassVar[dict[str, tuple[int, float, float]]] = { - "dopa": (_VASOPRESSOR_ITEMIDS["dopa"], 0, 50), - "norepi": (_VASOPRESSOR_ITEMIDS["norepi"], 0, 3), - "dobu": (_VASOPRESSOR_ITEMIDS["dobu"], 0, 50), - "epi": (_VASOPRESSOR_ITEMIDS["epi"], 0, 1.5), + "dopa": (221662, 0, 50), + "norepi": (221906, 0, 3), + "dobu": (221653, 0, 50), + "epi": (221289, 0, 1.5), } _ANTIBIOTICS: ClassVar[tuple[int, ...]] = ( 225798, 225837, 225838, 225840, 225842, 225843, 225844, 225845, 225847, @@ -1158,12 +1146,12 @@ class YAIBSepsisMIMIC4(_YAIBMIMIC4Task): 225900, 225902, 225903, 225905, 227691, 228003, ) # Invasive and non-invasive ventilation (procedureevents). - _VENTILATION: ClassVar[tuple[int, ...]] = tuple(_VENTILATION_ITEMIDS.values()) + _VENTILATION: ClassVar[tuple[int, ...]] = (225792, 225794) _INTUBATED_GCS: ClassVar[str] = "No Response-ETT" _EXTRA_ITEMIDS: ClassVar[dict[str, tuple[int, ...]]] = { "chartevents": (220739, 223901, 223900), - "inputevents": (*_VASOPRESSOR_ITEMIDS.values(), *_ANTIBIOTICS), + "inputevents": (221662, 221906, 221653, 221289, *_ANTIBIOTICS), "procedureevents": _VENTILATION, } _EXTRA_TABLES: ClassVar[tuple[str, ...]] = ( From d1bf2070455c6af2725936c2dc54ca9fabb5ecd5 Mon Sep 17 00:00:00 2001 From: solarsys Date: Mon, 9 Nov 2026 10:56:17 -0500 Subject: [PATCH 5/6] Port APRICOT-M to the label processor API and the t = 0 YAIB static #1389 removed BaseModel.set_pos_weight and the mode setter: APRICOT-M now supplies a fixed MultiLabelProcessor for its K tensor labels, and the class weighting is a pos_weight constructor argument ('balanced' learned from the dataset passed in, i.e. the training split). #1410 made the YAIB static features a t = 0 series; the acuity task keeps static a flat tensor, as InHospitalSurvivalMIMIC4 does, because APRICOT-M fuses it as one vector. Also drops a duplicate export left by the rebase. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BdtuVKBLhWpYbhTQbaZaTt --- docs/api/models/pyhealth.models.APRICOTM.rst | 4 +- examples/apricotm_mimic4_acuity.ipynb | 5 +- pyhealth/models/__init__.py | 1 - pyhealth/models/apricotm.py | 54 +++++++++++++++----- pyhealth/tasks/acuity_mimic4.py | 11 +++- tests/core/test_apricotm.py | 16 +++--- 6 files changed, 64 insertions(+), 27 deletions(-) diff --git a/docs/api/models/pyhealth.models.APRICOTM.rst b/docs/api/models/pyhealth.models.APRICOTM.rst index 96fec7293a..6910b82212 100644 --- a/docs/api/models/pyhealth.models.APRICOTM.rst +++ b/docs/api/models/pyhealth.models.APRICOTM.rst @@ -36,8 +36,8 @@ event, such as the ``events`` field of field. The label is a tensor of ``K`` binary labels (12 for that task, in the order of ``ICUAcuityMIMIC4.LABELS``). ``mode`` is ``"multilabel"``; the model returns ``logit``, ``y_prob`` and, with labels, ``loss`` (binary -cross-entropy) and ``y_true``. Use ``set_pos_weight("balanced", -train_samples)`` for the class weighting of the paper. The example notebook +cross-entropy) and ``y_true``. Pass ``pos_weight="balanced"`` with the +training split for the class weighting of the paper. The example notebook ``examples/apricotm_mimic4_acuity.ipynb`` trains it on MIMIC-IV. API diff --git a/examples/apricotm_mimic4_acuity.ipynb b/examples/apricotm_mimic4_acuity.ipynb index 814a0165c7..7e5301973f 100644 --- a/examples/apricotm_mimic4_acuity.ipynb +++ b/examples/apricotm_mimic4_acuity.ipynb @@ -174,9 +174,8 @@ "\n", "def train_apricotm(train_part, train_dl, val_dl, epochs, patience=5,\n", " max_seq_len=512):\n", - " model = APRICOTM(train_part, static_key=\"static\",\n", - " max_seq_len=max_seq_len).to(device)\n", - " model.set_pos_weight(\"balanced\", train_part)\n", + " model = APRICOTM(train_part, static_key=\"static\", max_seq_len=max_seq_len,\n", + " pos_weight=\"balanced\").to(device)\n", " optimizer = torch.optim.Adam(model.parameters(), lr=3e-4, weight_decay=1e-5)\n", " best, best_state, waited = -1.0, None, 0\n", " for epoch in range(epochs):\n", diff --git a/pyhealth/models/__init__.py b/pyhealth/models/__init__.py index 2af7c27535..ae3ffb8940 100644 --- a/pyhealth/models/__init__.py +++ b/pyhealth/models/__init__.py @@ -81,7 +81,6 @@ from .survival_mdn import SurvivalMDN as SurvivalMDN from .trajsurv import TrajSurv as TrajSurv from .knowrare import KnowRare as KnowRare -from .apricotm import APRICOTM as APRICOTM, SelectiveSSM as SelectiveSSM from .apricotm import APRICOTM as APRICOTM from .selective_ssm import SelectiveSSM as SelectiveSSM from .heartlang import ( diff --git a/pyhealth/models/apricotm.py b/pyhealth/models/apricotm.py index aa3a6fe869..5023c3918c 100644 --- a/pyhealth/models/apricotm.py +++ b/pyhealth/models/apricotm.py @@ -31,9 +31,9 @@ the other samples in its batch. - No positional encoding is added (the authors' code has it disabled; the scan is order-aware). -- Class imbalance: the paper weights each label's loss term; here - :meth:`~pyhealth.models.BaseModel.set_pos_weight` (e.g. ``"balanced"``) - weights the positive examples of each label. +- Class imbalance: the paper weights each label's loss term; here the + ``pos_weight`` argument (e.g. ``"balanced"``) weights the positive + examples of each label. - The isotonic recalibration and the overall-acuity logic of the paper are evaluation steps and are not part of the model. """ @@ -41,6 +41,7 @@ from __future__ import annotations import math +from collections.abc import Sequence import torch import torch.nn.functional as F @@ -49,6 +50,7 @@ from pyhealth.datasets import SampleDataset from pyhealth.models.base_model import BaseModel from pyhealth.models.selective_ssm import SelectiveSSM +from pyhealth.processors import LabelProcessor, MultiLabelProcessor __all__ = ["APRICOTM"] @@ -94,8 +96,8 @@ class APRICOTM(BaseModel): field of :class:`~pyhealth.tasks.ICUAcuityMIMIC4`, ``K = 12``). The model is a multilabel classifier: one two-layer head per label, ``mode`` is ``"multilabel"``, and the loss is the binary cross-entropy - averaged over labels. Use :meth:`set_pos_weight` (e.g. ``"balanced"`` - with the training samples) for the class weighting of the paper. + averaged over labels. Pass ``pos_weight="balanced"`` with the training + split for the class weighting of the paper. Args: dataset: The dataset (schemas, vocabulary and static width). @@ -113,6 +115,10 @@ class APRICOTM(BaseModel): max_seq_len: Events read per sample, the most recent ones (512). time_scale: Divides the event times (720 hours = 30 days, the longest stay in the paper's cohort, maps them to [0, 1]). + pos_weight: Weight of the positive examples of each label in the + loss: a number, one number per label, ``"balanced"`` + (negatives / positives of each label in ``dataset``, so pass the + training split) or None. Examples: >>> from pyhealth.datasets import create_sample_dataset @@ -157,6 +163,7 @@ def __init__( dropout: float = 0.2, max_seq_len: int = 512, time_scale: float = 720.0, + pos_weight: float | Sequence[float] | str | None = None, ) -> None: super().__init__(dataset) if feature_key not in dataset.input_schema: @@ -178,12 +185,22 @@ def __init__( self.top_k = top_k self.max_seq_len = max_seq_len self.time_scale = float(time_scale) - self.mode = "multilabel" processor = dataset.input_processors[feature_key] self._roles = self._event_roles(processor, feature_key) sample = dataset[0] self.num_labels = int(torch.as_tensor(sample[label_key]).numel()) + # The label is a tensor field, which is not a label processor, so the + # model supplies one: K fixed binary labels with BCE (see + # label_processors). "balanced" is learned from ``dataset``. + self._label = MultiLabelProcessor(labels=self.num_labels, pos_weight=pos_weight) + if pos_weight == "balanced": + self._label._fit_pos_weight( + [ + torch.as_tensor(dataset[i][label_key], dtype=torch.float32) + for i in range(len(dataset)) + ] + ) static_dim = 0 if static_key is not None: static_dim = int(torch.as_tensor(sample[static_key]).numel()) @@ -296,6 +313,20 @@ def encode(self, **kwargs) -> Tensor: h = h + self.static_ffn(static.reshape(static.shape[0], -1)) return h + @property + def label_processors(self) -> dict[str, LabelProcessor]: + """The ``K`` binary labels, scored as a multilabel classification. + + The label is a ``"tensor"`` field, which is not a label processor, so + APRICOT-M supplies a fixed :class:`~pyhealth.processors.MultiLabelProcessor` + with ``K`` labels and the model's ``pos_weight``. + + Examples: + >>> model.label_processor.size() # doctest: +SKIP + 12 + """ + return {self.label_key: self._label} + def forward(self, **kwargs) -> dict[str, Tensor]: """Runs APRICOT-M on a batch. @@ -306,22 +337,17 @@ def forward(self, **kwargs) -> dict[str, Tensor]: Returns: ``logit`` ``[B, K]``, ``y_prob`` (sigmoid of the logits), and with labels ``loss`` (mean binary cross-entropy, weighted by - :attr:`pos_weight` when set) and ``y_true``. ``embed=True`` adds + ``pos_weight`` when given) and ``y_true``. ``embed=True`` adds ``embed``, the fused representation. """ h = self.encode(**kwargs) logits = torch.cat([head(h) for head in self.heads], dim=-1) - out = {"logit": logits, "y_prob": torch.sigmoid(logits)} + out = {"logit": logits, "y_prob": self.label_processor.activation(logits)} if self.label_key in kwargs: y_true = torch.as_tensor(kwargs[self.label_key]).to( self.device, torch.float32 ).reshape(logits.shape) - pos_weight = self.pos_weight - out["loss"] = F.binary_cross_entropy_with_logits( - logits, - y_true, - pos_weight=None if pos_weight is None else pos_weight.to(self.device), - ) + out["loss"] = self.label_processor.loss(logits, y_true) out["y_true"] = y_true if kwargs.get("embed", False): out["embed"] = h diff --git a/pyhealth/tasks/acuity_mimic4.py b/pyhealth/tasks/acuity_mimic4.py index 1fed6ee1e7..d02e60235e 100644 --- a/pyhealth/tasks/acuity_mimic4.py +++ b/pyhealth/tasks/acuity_mimic4.py @@ -144,7 +144,16 @@ class ICUAcuityMIMIC4(_YAIBMIMIC4Task): ] }, ), - "static": _YAIBMIMIC4Task.input_schema["static"], + # A flat vector, which APRICOT-M fuses with the pooled events (unlike + # the YAIB tasks, where static is a sequence_v2 series at t = 0). + "static": ( + "tensor", + { + "normalization": "zscore", + "missing_indicators": True, + "impute_strategy": "zero", + }, + ), } output_schema: ClassVar[dict[str, Any]] = {"acuity": "tensor"} diff --git a/tests/core/test_apricotm.py b/tests/core/test_apricotm.py index 8c559835bd..a0153d3538 100644 --- a/tests/core/test_apricotm.py +++ b/tests/core/test_apricotm.py @@ -325,13 +325,17 @@ def test_short_sequence_and_no_static(self): def test_balanced_pos_weight(self): batch = self._batch(range(6)) plain = self.model(**batch)["loss"] - self.model.set_pos_weight("balanced", [self.dataset[i] for i in range(6)]) - # BaseModel.set_pos_weight("balanced") gives negatives / positives, so - # the last label, positive in every sample, gets weight 0 (only labels - # with no positive at all fall back to 1). - torch.testing.assert_close(self.model.pos_weight, + torch.manual_seed(0) + weighted = APRICOTM(self.dataset, static_key="static", embedding_dim=16, + hidden_dim=8, state_size=4, top_k=3, + pos_weight="balanced") + # "balanced" gives negatives / positives over the dataset, so the last + # label, positive in every sample, gets weight 0 (only labels with no + # positive at all fall back to 1). + torch.testing.assert_close(weighted.label_processor.weight, torch.tensor([1.0, 2.0, 1.0, 0.0])) - self.assertFalse(torch.allclose(plain, self.model(**batch)["loss"])) + self.assertIsNone(self.model.label_processor.weight) + self.assertFalse(torch.allclose(plain, weighted(**batch)["loss"])) def test_invalid_arguments(self): with self.assertRaises(ValueError): From 73d3e3b3a94df1f22d36eedd6bd604cd457196bd Mon Sep 17 00:00:00 2001 From: solarsys Date: Mon, 9 Nov 2026 15:44:05 -0500 Subject: [PATCH 6/6] APRICOT-M: document the balanced pos_weight edge cases Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BdtuVKBLhWpYbhTQbaZaTt --- pyhealth/models/apricotm.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/pyhealth/models/apricotm.py b/pyhealth/models/apricotm.py index 5023c3918c..a4d501f7b1 100644 --- a/pyhealth/models/apricotm.py +++ b/pyhealth/models/apricotm.py @@ -118,7 +118,9 @@ class APRICOTM(BaseModel): pos_weight: Weight of the positive examples of each label in the loss: a number, one number per label, ``"balanced"`` (negatives / positives of each label in ``dataset``, so pass the - training split) or None. + training split; this reads every sample of ``dataset`` once) or + None. With ``"balanced"`` a label that is positive in every + sample gets weight 0 and one with no positive gets weight 1. Examples: >>> from pyhealth.datasets import create_sample_dataset