From 7090d8c498fc037a3e7466786a476658633aa351 Mon Sep 17 00:00:00 2001 From: solarsys Date: Tue, 3 Nov 2026 00:02:05 -0800 Subject: [PATCH 01/11] Add ARMR medication recommendation model (IJCAI 2025) ARMR (Wu et al., "ARMR: Adaptively Responsive Network for Medication Recommendation", IJCAI 2025) for the MIMIC-III/IV drug-recommendation tasks: piecewise temporal learning (recent visits through a feedforward network, distant ones through a pure-PyTorch Mamba block), the adaptively responsive module over reused and new drugs with time-decayed past use, and the joint direct/similarity recommendation with the BCE plus multi-label margin loss. Reimplemented from the paper's equations; the authors' code (no license) was only used to check open details. Optional co-occurrence and DDI graph embeddings follow the authors' code. Adds tests, a docs page and a Colab notebook comparing ARMR with GAMENet, SafeDrug and RETAIN on synthetic MIMIC-III and, with credentials, on MIMIC-III v1.4. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BdtuVKBLhWpYbhTQbaZaTt --- docs/api/models.rst | 3 +- docs/api/models/pyhealth.models.ARMR.rst | 23 + .../armr_mimic3_drug_recommendation.ipynb | 348 +++++++++++++ pyhealth/models/__init__.py | 1 + pyhealth/models/armr.py | 483 ++++++++++++++++++ tests/core/test_armr.py | 137 +++++ 6 files changed, 994 insertions(+), 1 deletion(-) create mode 100644 docs/api/models/pyhealth.models.ARMR.rst create mode 100644 examples/armr_mimic3_drug_recommendation.ipynb create mode 100644 pyhealth/models/armr.py create mode 100644 tests/core/test_armr.py diff --git a/docs/api/models.rst b/docs/api/models.rst index 7d47de5769..d4a28d7af3 100644 --- a/docs/api/models.rst +++ b/docs/api/models.rst @@ -154,7 +154,7 @@ default loss with ``set_pos_weight``: ``"balanced"`` is computed from the dataset you pass, so pass the training split, not the full dataset. The weight applies to models that use the default loss (``BaseModel.get_loss_function``); the drug-recommendation models (GAMENet, -SafeDrug, MoleRec, MICRON) compute their own loss and ignore it. Weighting +SafeDrug, MoleRec, MICRON, ARMR) compute their own loss and ignore it. Weighting shifts the predicted probabilities upward, so check calibration before interpreting them as risks. See ``examples/imbalanced_outcome_pos_weight.py``. @@ -225,6 +225,7 @@ API Reference models/pyhealth.models.MICRON models/pyhealth.models.SafeDrug models/pyhealth.models.MoleRec + models/pyhealth.models.ARMR models/pyhealth.models.Deepr models/pyhealth.models.EHRMamba models/pyhealth.models.EHRMambaCEHR diff --git a/docs/api/models/pyhealth.models.ARMR.rst b/docs/api/models/pyhealth.models.ARMR.rst new file mode 100644 index 0000000000..7cda90e95e --- /dev/null +++ b/docs/api/models/pyhealth.models.ARMR.rst @@ -0,0 +1,23 @@ +pyhealth.models.ARMR +=================================== + +ARMR (Wu et al., "ARMR: Adaptively Responsive Network for Medication +Recommendation", IJCAI 2025) for the drug-recommendation tasks +(:class:`~pyhealth.tasks.DrugRecommendationMIMIC3`, +:class:`~pyhealth.tasks.DrugRecommendationMIMIC4`). It needs ``conditions``, +``procedures`` and ``drugs_hist`` in the input schema and predicts ``drugs``. + +Example notebook: ``examples/armr_mimic3_drug_recommendation.ipynb``. + +.. autoclass:: pyhealth.models.ARMR + :members: + :undoc-members: + :show-inheritance: + +.. autoclass:: pyhealth.models.armr.PiecewiseTemporalLearning + :members: + :show-inheritance: + +.. autoclass:: pyhealth.models.armr.SelectiveSSM + :members: + :show-inheritance: diff --git a/examples/armr_mimic3_drug_recommendation.ipynb b/examples/armr_mimic3_drug_recommendation.ipynb new file mode 100644 index 0000000000..ad548c5036 --- /dev/null +++ b/examples/armr_mimic3_drug_recommendation.ipynb @@ -0,0 +1,348 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "9f447d62", + "metadata": {}, + "source": [ + "# ARMR in PyHealth: medication recommendation on MIMIC-III\n", + "\n", + "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/sunlabuiuc/PyHealth/blob/master/examples/armr_mimic3_drug_recommendation.ipynb)\n", + "\n", + "This notebook runs **ARMR** (Feiyue Wu, Tianxing Wu and Shenqi Jing, *ARMR: Adaptively Responsive Network for Medication Recommendation*, IJCAI 2025, [arXiv:2507.04428](https://arxiv.org/abs/2507.04428)) as implemented in PyHealth (`pyhealth.models.ARMR`), and compares it with PyHealth's GAMENet, SafeDrug and RETAIN on the same task, split and metrics.\n", + "\n", + "ARMR has three parts:\n", + "- **Piecewise temporal learning.** The most recent visits go through a feedforward network and the earlier ones through a Mamba block; the recent states attend over the distant ones.\n", + "- **Adaptively responsive module.** The medication history is split into drugs that were reused and drugs that were new at each visit. Each drug's embedding is weighted by whether the patient took it before, with a learned time decay.\n", + "- **Joint recommendation.** A direct score from the patient representation is fused with the cosine similarity between the patient and each weighted drug embedding. The loss is 0.7 \u00d7 BCE + 0.3 \u00d7 multi-label margin.\n", + "\n", + "**How to use it.** Part 1 runs end to end on PyHealth's open synthetic MIMIC-III, with no credentials. Part 2 repeats the experiment on real MIMIC-III v1.4: set `MIMIC3_ROOT` to your copy (PhysioNet credentials required) and run it." + ] + }, + { + "cell_type": "markdown", + "id": "d77f3458", + "metadata": {}, + "source": [ + "## Setup\n", + "\n", + "On Colab this installs PyHealth from the branch that adds ARMR. After the pull request is merged, install `pyhealth` from PyPI or from `master` instead." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "dfbb0f34", + "metadata": { + "execution": { + "iopub.execute_input": "2026-11-03T07:53:36.971041Z", + "iopub.status.busy": "2026-11-03T07:53:36.970886Z", + "iopub.status.idle": "2026-11-03T07:53:36.978785Z", + "shell.execute_reply": "2026-11-03T07:53:36.975561Z" + } + }, + "outputs": [], + "source": [ + "import sys\n", + "import subprocess\n", + "\n", + "if \"google.colab\" in sys.modules:\n", + " subprocess.run(\n", + " [sys.executable, \"-m\", \"pip\", \"install\", \"-q\",\n", + " \"git+https://github.com/solarsys/PyHealth@feat/armr\"],\n", + " check=True,\n", + " )" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "ef9a1fcf", + "metadata": { + "execution": { + "iopub.execute_input": "2026-11-03T07:53:36.985899Z", + "iopub.status.busy": "2026-11-03T07:53:36.984941Z", + "iopub.status.idle": "2026-11-03T07:54:06.213575Z", + "shell.execute_reply": "2026-11-03T07:54:06.209334Z" + } + }, + "outputs": [], + "source": [ + "import random\n", + "\n", + "import numpy as np\n", + "import pandas as pd\n", + "import torch\n", + "\n", + "from pyhealth.datasets import MIMIC3Dataset, get_dataloader, split_by_patient\n", + "from pyhealth.medcode import ATC\n", + "from pyhealth.metrics import ddi_rate_score\n", + "from pyhealth.models import ARMR, GAMENet, RETAIN, SafeDrug\n", + "from pyhealth.tasks import DrugRecommendationMIMIC3\n", + "from pyhealth.trainer import Trainer\n", + "\n", + "METRICS = [\"jaccard_samples\", \"pr_auc_samples\", \"f1_samples\"]\n", + "\n", + "\n", + "def seed_everything(seed: int) -> None:\n", + " random.seed(seed)\n", + " np.random.seed(seed)\n", + " torch.manual_seed(seed)\n", + "\n", + "\n", + "def ddi_matrix(samples) -> np.ndarray:\n", + " \"\"\"Drug-drug interactions between the task's ATC-3 drugs (as GAMENet and SafeDrug).\"\"\"\n", + " vocab = samples.output_processors[\"drugs\"].label_vocab\n", + " adj = np.zeros((len(vocab), len(vocab)))\n", + " for a, b in ATC().get_ddi(gamenet_ddi=True):\n", + " a, b = ATC.convert(a, level=3), ATC.convert(b, level=3)\n", + " if a in vocab and b in vocab:\n", + " adj[vocab[a], vocab[b]] = adj[vocab[b], vocab[a]] = 1\n", + " return adj\n", + "\n", + "\n", + "def load_samples(root: str, dev: bool = False):\n", + " \"\"\"Loads MIMIC-III and builds PyHealth's drug-recommendation samples.\"\"\"\n", + " dataset = MIMIC3Dataset(\n", + " root=root,\n", + " tables=[\"DIAGNOSES_ICD\", \"PROCEDURES_ICD\", \"PRESCRIPTIONS\"],\n", + " dev=dev,\n", + " )\n", + " return dataset.set_task(DrugRecommendationMIMIC3())\n", + "\n", + "\n", + "MODELS = {\n", + " # ARMR's defaults follow the paper; lr 2e-4 is the authors' setting\n", + " \"ARMR\": (lambda s: ARMR(s, embedding_dim=64, n_recent=3), 2e-4),\n", + " \"GAMENet\": (lambda s: GAMENet(s), 1e-3),\n", + " \"SafeDrug\": (lambda s: SafeDrug(s), 1e-3),\n", + " \"RETAIN\": (lambda s: RETAIN(s), 1e-3),\n", + "}\n", + "\n", + "\n", + "def compare(samples, epochs: int, seed: int = 42, batch_size: int = 64):\n", + " \"\"\"Trains each model on one patient-level split and scores it on the test patients.\"\"\"\n", + " train, val, test = split_by_patient(samples, [0.7, 0.1, 0.2], seed=seed)\n", + " loaders = (\n", + " get_dataloader(train, batch_size=batch_size, shuffle=True),\n", + " get_dataloader(val, batch_size=batch_size, shuffle=False),\n", + " get_dataloader(test, batch_size=batch_size, shuffle=False),\n", + " )\n", + " ddi = ddi_matrix(samples)\n", + " rows = {}\n", + " for name, (make, lr) in MODELS.items():\n", + " seed_everything(seed)\n", + " trainer = Trainer(model=make(samples), metrics=METRICS, enable_logging=False)\n", + " trainer.train(\n", + " train_dataloader=loaders[0], val_dataloader=loaders[1], epochs=epochs,\n", + " optimizer_params={\"lr\": lr}, monitor=\"jaccard_samples\",\n", + " )\n", + " scores = trainer.evaluate(loaders[2])\n", + " # DDI rate of the recommended sets (probability >= 0.5)\n", + " _, y_prob, _ = trainer.inference(loaders[2])\n", + " recommended = [np.flatnonzero(row >= 0.5) for row in y_prob]\n", + " rows[name] = {\n", + " \"Jaccard\": scores[\"jaccard_samples\"],\n", + " \"PRAUC\": scores[\"pr_auc_samples\"],\n", + " \"F1\": scores[\"f1_samples\"],\n", + " \"DDI rate\": ddi_rate_score(recommended, ddi),\n", + " }\n", + " return (pd.DataFrame(rows).T * 100).round(2)" + ] + }, + { + "cell_type": "markdown", + "id": "0ae6ab06", + "metadata": {}, + "source": "## Part 1: open synthetic MIMIC-III (no credentials)\n\nPyHealth hosts a synthetic MIMIC-III with the real schema. It is useful for checking that everything runs; its scores say nothing about the paper's results. Three epochs take a few minutes on a CPU. That is too short for ARMR, which trains at the authors' learning rate (2e-4, five times lower than the baselines'), so it trails here; the comparison that matters is Part 2's." + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "b38a21cf", + "metadata": { + "execution": { + "iopub.execute_input": "2026-11-03T07:54:06.227603Z", + "iopub.status.busy": "2026-11-03T07:54:06.225700Z", + "iopub.status.idle": "2026-11-03T08:01:11.638215Z", + "shell.execute_reply": "2026-11-03T08:01:11.633883Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1858 samples\n" + ] + }, + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
JaccardPRAUCF1DDI rate
ARMR24.3446.1736.246.46
GAMENet30.7756.3343.834.51
SafeDrug31.1955.4044.278.20
RETAIN28.7553.9441.287.46
\n", + "
" + ], + "text/plain": [ + " Jaccard PRAUC F1 DDI rate\n", + "ARMR 24.34 46.17 36.24 6.46\n", + "GAMENet 30.77 56.33 43.83 4.51\n", + "SafeDrug 31.19 55.40 44.27 8.20\n", + "RETAIN 28.75 53.94 41.28 7.46" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "synthetic = load_samples(\"https://storage.googleapis.com/pyhealth/Synthetic_MIMIC-III\")\n", + "print(f\"{len(synthetic)} samples\")\n", + "synthetic_results = compare(synthetic, epochs=3)\n", + "synthetic_results" + ] + }, + { + "cell_type": "markdown", + "id": "46e581d1", + "metadata": {}, + "source": [ + "## Part 2: MIMIC-III v1.4 (credentialed)\n", + "\n", + "Set `MIMIC3_ROOT` to the folder with `ADMISSIONS.csv.gz`, `DIAGNOSES_ICD.csv.gz`, `PROCEDURES_ICD.csv.gz` and `PRESCRIPTIONS.csv.gz` (for example a mounted Google Drive folder). On a Colab GPU, 50 epochs take roughly an hour for all four models.\n", + "\n", + "The paper reports, on its MIMIC-III and MIMIC-IV cohorts (Table 2, %):\n", + "\n", + "| Dataset | Jaccard | PRAUC | F1 |\n", + "|---|---|---|---|\n", + "| MIMIC-III | 54.51 | 79.63 | 69.59 |\n", + "| MIMIC-IV | 51.74 | 76.95 | 67.12 |\n", + "\n", + "The paper builds its cohort with the Carmen preprocessing pipeline (ATC level 3, 131 drugs, patients filtered by visit count), while PyHealth's `DrugRecommendationMIMIC3` uses its own filtering and drug vocabulary. Expect the same ordering of models, not identical numbers." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "13e4d4ce", + "metadata": { + "execution": { + "iopub.execute_input": "2026-11-03T08:01:11.680479Z", + "iopub.status.busy": "2026-11-03T08:01:11.679908Z", + "iopub.status.idle": "2026-11-03T08:01:11.698246Z", + "shell.execute_reply": "2026-11-03T08:01:11.697229Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Set MIMIC3_ROOT to run the experiment on MIMIC-III.\n" + ] + } + ], + "source": [ + "MIMIC3_ROOT = \"\" # e.g. \"/content/drive/MyDrive/mimic-iii-clinical-database-1.4\"\n", + "\n", + "if MIMIC3_ROOT:\n", + " mimic3 = load_samples(MIMIC3_ROOT)\n", + " print(f\"{len(mimic3)} samples\")\n", + " mimic3_results = compare(mimic3, epochs=50)\n", + " display(mimic3_results)\n", + "else:\n", + " print(\"Set MIMIC3_ROOT to run the experiment on MIMIC-III.\")" + ] + }, + { + "cell_type": "markdown", + "id": "4207a928", + "metadata": {}, + "source": [ + "## Notes for reproducing the paper\n", + "\n", + "- `ARMR(..., use_graph=True)` (the default) adds GCN embeddings of the drug co-occurrence and drug-drug interaction graphs to the drug embeddings, as the authors' released code does. `use_graph=False` gives the equations exactly as written in the paper.\n", + "- Three details the paper leaves open, and the choices made: Eq. 9's time decay is one learned scale and rate; Eq. 11's attention gives a weight per embedding feature; the \"recent\" segment is the N visits closest to the prediction.\n", + "- Questions or corrections: please open an issue at https://github.com/sunlabuiuc/PyHealth or write on the PyHealth Discord." + ] + } + ], + "metadata": { + "accelerator": "GPU", + "colab": { + "provenance": [] + }, + "kernelspec": { + "display_name": "Python 3", + "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 8a176d06f7..6c1d4d11d1 100644 --- a/pyhealth/models/__init__.py +++ b/pyhealth/models/__init__.py @@ -13,6 +13,7 @@ PretrainedEmbedding as PretrainedEmbedding, SequenceEmbeddingModel as SequenceEmbeddingModel, ) +from .armr import ARMR as ARMR from .gamenet import GAMENet, GAMENetLayer from .jamba_ehr import JambaEHR, JambaLayer from .logistic_regression import LogisticRegression diff --git a/pyhealth/models/armr.py b/pyhealth/models/armr.py new file mode 100644 index 0000000000..5236a38232 --- /dev/null +++ b/pyhealth/models/armr.py @@ -0,0 +1,483 @@ +"""ARMR: Adaptively Responsive network for Medication Recommendation. + +Paper: Feiyue Wu, Tianxing Wu, and Shenqi Jing. "ARMR: Adaptively Responsive +Network for Medication Recommendation." IJCAI 2025. +https://arxiv.org/abs/2507.04428 + +This is a reimplementation from the paper's equations (Section 4), for +PyHealth's drug-recommendation tasks. The authors' code +(https://github.com/seucoin/armr2) was used only to check details that the +paper leaves open; see the class docstring for each choice. +""" + +from __future__ import annotations + +import math +import os + +import numpy as np +import torch +import torch.nn.functional as F +from torch import nn + +from pyhealth import BASE_CACHE_PATH as CACHE_PATH +from pyhealth.datasets import SampleDataset +from pyhealth.medcode import ATC +from pyhealth.models.base_model import BaseModel +from pyhealth.models.embedding import EmbeddingModel + + +def _reverse_padded(x: torch.Tensor, lengths: torch.Tensor) -> torch.Tensor: + """Reverses the first ``lengths[b]`` steps of each sequence, keeping padding last. + + Args: + x: tensor of shape [batch, steps, dim]. + lengths: number of valid steps per sequence, shape [batch]. + + Returns: + Tensor of the same shape with each valid prefix reversed. + """ + steps = x.size(1) + pos = torch.arange(steps, device=x.device).unsqueeze(0) + lengths = lengths.unsqueeze(1) + idx = torch.where(pos < lengths, lengths - 1 - pos, pos) + 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). + + 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. + + The ``n_recent`` most recent visits go through a feedforward network + (Eq. 1); the earlier, distant visits go through a Mamba block in + chronological order (Eq. 2); the recent states then attend over the + distant ones (Eq. 3), and both are concatenated (Eq. 4). Patients with + fewer than ``n_recent`` visits are zero-padded, and those with no distant + visit get no attention term. + + The paper writes the recent segment as "the first N visits"; like the + authors' code, this orders visits from the most recent, so the segment + is the N visits closest to the prediction. + + Args: + dim: visit representation size. + n_recent: number of recent visits N. + + Examples: + >>> ptl = PiecewiseTemporalLearning(dim=8, n_recent=2) + >>> out = ptl(torch.randn(3, 4, 8), torch.tensor([4, 2, 1])) + >>> out.shape + torch.Size([3, 4, 8]) + """ + + def __init__(self, dim: int, n_recent: int): + super().__init__() + self.n_recent = n_recent + self.ff = nn.Sequential(nn.Linear(dim, dim), nn.ReLU(), nn.Linear(dim, dim)) + self.norm_near = nn.LayerNorm(dim) + self.norm_far = nn.LayerNorm(dim) + self.mamba = SelectiveSSM(dim) + + def forward(self, seq: torch.Tensor, lengths: torch.Tensor) -> torch.Tensor: + """Encodes visits. + + Args: + seq: visit representations in chronological order, padding last, + shape [batch, visits, dim]. + lengths: number of valid visits per patient, shape [batch]. + + Returns: + ``h_S`` of shape [batch, 2 * n_recent, dim]. + """ + batch, visits, dim = seq.shape + n = self.n_recent + if visits < n + 1: # room for n recent visits and one distant visit + seq = torch.cat([seq, seq.new_zeros(batch, n + 1 - visits, dim)], 1) + recent_first = _reverse_padded(seq, lengths) + near = recent_first[:, :n] + near_valid = (torch.arange(n, device=seq.device) < lengths.unsqueeze(1)) + near = near * near_valid.unsqueeze(-1) + h_near = self.norm_near(near + self.ff(near)) # Eq. 1 + + far_len = (lengths - n).clamp(min=0) + far = _reverse_padded(recent_first[:, n:], far_len) # oldest first + h_far = self.mamba(far) # Eq. 2 + far_valid = torch.arange(far.size(1), device=seq.device) < far_len.unsqueeze(1) + scores = torch.bmm(h_near, h_far.transpose(1, 2)) + scores = scores.masked_fill(~far_valid.unsqueeze(1), float("-inf")) + attn = torch.nan_to_num(torch.softmax(scores, dim=-1)) # no distant visit + h_far = self.norm_far(h_near + torch.bmm(attn, h_far)) # Eq. 3 + return torch.cat([h_near, h_far], dim=1) # Eq. 4 + + +class ARMR(BaseModel): + """ARMR medication recommendation model. + + Paper: Feiyue Wu, Tianxing Wu, and Shenqi Jing. "ARMR: Adaptively + Responsive Network for Medication Recommendation." IJCAI 2025. + + ARMR encodes each code history with Piecewise Temporal Learning + (:class:`PiecewiseTemporalLearning`): recent visits through a feedforward + network and distant visits through a Mamba block. Its Adaptively + Responsive Module splits the medication history into drugs that were + reused and drugs that were new at each visit, encodes both, and weights + every drug's embedding by whether the patient took it before, with a + learned time decay for past use. The recommendation fuses a direct score + from the patient representation with the cosine similarity between the + patient and each weighted drug embedding (Eq. 19). The loss is + ``alpha * BCE + (1 - alpha) * multi-label margin`` (Eq. 22, alpha 0.7). + + Choices where the paper is open: + + - Eq. 9 uses one learned decay rate and scale, ``alpha * exp(-beta * + lag)`` summed over the visits in which drug ``j`` was given, where + ``lag`` counts visits back from the prediction. + - Eq. 11's attention maps the drug-history attention to a per-feature + weight (``W_o`` and ``W_n`` are ``2N -> dim``), so the weighting changes + the direction of a drug's embedding, which cosine similarity sees. + - ``use_graph`` (default ``True``) adds two-layer GCN embeddings of the + drug co-occurrence graph and the drug-drug interaction graph to the + drug embeddings, with weights 1 and 0.5, as the authors' released code + does; the paper's text does not describe this. Set it to ``False`` for + the equations as written. + + Note: + Takes ``conditions``, ``procedures`` and ``drugs_hist`` (nested + per-visit codes, the current visit's drugs left out) and predicts the + ``drugs`` label, as :class:`~pyhealth.tasks.DrugRecommendationMIMIC3` + and :class:`~pyhealth.tasks.DrugRecommendationMIMIC4` produce. Drug + codes are ATC level 3, which the DDI graph needs. + + Args: + dataset: the training dataset, used for vocabularies and the graphs. + embedding_dim: code and visit embedding size. Default is 64. + n_recent: number of recent visits ``N`` handled by the feedforward + branch. Default is 3. + alpha: weight of the BCE term in the loss (Eq. 22). Default is 0.7. + dropout: dropout on the patient representation. Default is 0.3. + use_graph: add the co-occurrence and DDI graph embeddings to the drug + embeddings, as the authors' code does. Default is True. + + Examples: + >>> from pyhealth.datasets import create_sample_dataset + >>> samples = [ + ... {"patient_id": "p0", "visit_id": "v1", + ... "conditions": [["d1", "d2"], ["d3"]], + ... "procedures": [["p1"], ["p2"]], + ... "drugs_hist": [["A01A"], []], + ... "drugs": ["A01A", "B01A"]}, + ... {"patient_id": "p1", "visit_id": "v2", + ... "conditions": [["d2"], ["d1"], ["d3"]], + ... "procedures": [["p2"], ["p1"], ["p1"]], + ... "drugs_hist": [["B01A"], ["C03C"], []], + ... "drugs": ["C03C"]}, + ... ] + >>> dataset = create_sample_dataset( + ... samples=samples, + ... input_schema={"conditions": "nested_sequence", + ... "procedures": "nested_sequence", + ... "drugs_hist": "nested_sequence"}, + ... output_schema={"drugs": "multilabel"}, + ... dataset_name="demo", + ... ) + >>> model = ARMR(dataset, embedding_dim=16, use_graph=False) + >>> from pyhealth.datasets import get_dataloader + >>> batch = next(iter(get_dataloader(dataset, batch_size=2))) + >>> out = model(**batch) + >>> sorted(out) + ['logit', 'loss', 'y_prob', 'y_true'] + """ + + def __init__( + self, + dataset: SampleDataset, + embedding_dim: int = 64, + n_recent: int = 3, + alpha: float = 0.7, + dropout: float = 0.3, + use_graph: bool = True, + ): + super().__init__(dataset=dataset) + for key in ("conditions", "procedures", "drugs_hist"): + if key not in self.dataset.input_schema: + raise ValueError( + f"ARMR needs '{key}' in the input schema, as " + "pyhealth.tasks.DrugRecommendationMIMIC3/4 produce" + ) + if len(self.label_keys) != 1: + raise ValueError("ARMR predicts exactly one label (the drugs)") + self.label_key = self.label_keys[0] + self.feature_keys = ["conditions", "procedures"] + self.embedding_dim = embedding_dim + self.n_recent = n_recent + self.alpha = alpha + self.use_graph = use_graph + + label_vocab = self.dataset.output_processors[self.label_key].label_vocab + self.label_size = len(label_vocab) + dim = embedding_dim + + # Patient representation (Eq. 12-15) + self.embedding_model = EmbeddingModel(dataset, dim) + self.ptl_d = PiecewiseTemporalLearning(dim, n_recent) + self.ptl_p = PiecewiseTemporalLearning(dim, n_recent) + + # Adaptively Responsive Module (Eq. 5-11) + self.register_buffer("_hist_to_label", self._hist_vocab_map(label_vocab)) + self.drug_emb = nn.Parameter(torch.empty(self.label_size, dim)) + nn.init.xavier_uniform_(self.drug_emb) + self.ptl_reused = PiecewiseTemporalLearning(dim, n_recent) + self.ptl_new = PiecewiseTemporalLearning(dim, n_recent) + self.w_reused = nn.Linear(2 * n_recent, dim, bias=False) + self.w_new = nn.Linear(2 * n_recent, dim, bias=False) + self.decay_scale = nn.Parameter(torch.tensor(1.0)) # alpha in Eq. 9 + self.decay_rate = nn.Parameter(torch.tensor(0.0)) # softplus -> beta + + if use_graph: + ddi_adj = self._ddi_adj(label_vocab) + self.register_buffer("ehr_adj", _normalize(self._ehr_adj(label_vocab))) + self.register_buffer("ddi_adj_norm", _normalize(ddi_adj)) + self.gcn_ehr = nn.ModuleList([nn.Linear(dim, dim), nn.Linear(dim, dim)]) + self.gcn_ddi = nn.ModuleList([nn.Linear(dim, dim), nn.Linear(dim, dim)]) + os.makedirs(CACHE_PATH, exist_ok=True) + np.save(os.path.join(CACHE_PATH, "ddi_adj.npy"), ddi_adj.numpy()) + + # Joint recommendation (Eq. 16-19) + patient_size = 4 * n_recent * dim + self.dropout = nn.Dropout(dropout) + self.ff_direct = nn.Sequential( + nn.Linear(patient_size, dim), nn.ReLU(), nn.Linear(dim, self.label_size) + ) + self.ff_query = nn.Sequential( + nn.Linear(patient_size, dim), nn.ReLU(), nn.Linear(dim, dim) + ) + self.w_direct = nn.Parameter(torch.tensor(1.0)) + self.w_sim = nn.Parameter(torch.tensor(1.0)) + + # ------------------------------------------------------------ vocabulary + def _hist_vocab_map(self, label_vocab: dict) -> torch.Tensor: + """Maps drugs_hist input indices to label indices; others to a trash bin.""" + hist_vocab = self.dataset.input_processors["drugs_hist"].code_vocab + mapping = torch.full((len(hist_vocab),), self.label_size, dtype=torch.long) + for code, idx in hist_vocab.items(): + if code in label_vocab: + mapping[idx] = label_vocab[code] + return mapping + + def _ehr_adj(self, label_vocab: dict) -> torch.Tensor: + """Co-occurrence graph of the drugs given together in a training visit.""" + adj = torch.zeros(self.label_size, self.label_size) + for sample in self.dataset: + drugs = sample[self.label_key] + if isinstance(drugs, torch.Tensor): # processed: multi-hot + ids = torch.nonzero(drugs.flatten()).flatten() + else: + ids = torch.tensor([label_vocab[c] for c in drugs if c in label_vocab]) + if ids.numel() > 1: + adj[ids.unsqueeze(1), ids.unsqueeze(0)] = 1.0 + adj.fill_diagonal_(0.0) + return adj + + def _ddi_adj(self, label_vocab: dict) -> torch.Tensor: + """Drug-drug interaction graph at ATC level 3 (as GAMENet and SafeDrug).""" + adj = torch.zeros(self.label_size, self.label_size) + for a, b in ATC().get_ddi(gamenet_ddi=True): + a, b = ATC.convert(a, level=3), ATC.convert(b, level=3) + if a in label_vocab and b in label_vocab: + adj[label_vocab[a], label_vocab[b]] = 1.0 + adj[label_vocab[b], label_vocab[a]] = 1.0 + return adj + + # ---------------------------------------------------------------- pieces + def _visit_lengths(self, codes: torch.Tensor) -> torch.Tensor: + """Number of visits with at least one code, per patient.""" + return (codes > 0).any(dim=-1).sum(dim=1) + + def _drug_history(self, drugs_hist: torch.Tensor, visits: int) -> torch.Tensor: + """Multi-hot drugs of each visit in the label space, [batch, visits, M].""" + if drugs_hist.size(1) < visits: + pad = drugs_hist.new_zeros( + drugs_hist.size(0), visits - drugs_hist.size(1), drugs_hist.size(2) + ) + drugs_hist = torch.cat([drugs_hist, pad], dim=1) + drugs_hist = drugs_hist[:, :visits] + mapped = self._hist_to_label[drugs_hist.clamp(min=0)] + multihot = torch.zeros( + *drugs_hist.shape[:2], self.label_size + 1, device=drugs_hist.device + ) + multihot.scatter_(2, mapped, 1.0) + return multihot[..., : self.label_size] + + def _drug_embeddings(self) -> torch.Tensor: + """Base drug embeddings ``E_m``, plus the graph embeddings if used.""" + emb = self.drug_emb + if not self.use_graph: + return emb + out = emb + for layers, adj, weight in ( + (self.gcn_ehr, self.ehr_adj, 1.0), + (self.gcn_ddi, self.ddi_adj_norm, 0.5), + ): + h = F.relu(adj @ layers[0](emb)) + out = out + weight * (adj @ layers[1](h)) + return out + + def _responsive_drugs( + self, history: torch.Tensor, prev_len: torch.Tensor + ) -> torch.Tensor: + """The patient's weighted drug embeddings ``E'_m`` (Eq. 5-11). + + Args: + history: multi-hot drugs per previous visit, [batch, visits, M], + zero after each patient's ``prev_len`` previous visits. + prev_len: number of previous visits per patient, [batch]. + + Returns: + Tensor of shape [batch, M, dim]. + """ + visits = history.size(1) + seen_before = torch.cumsum(history, dim=1) - history > 0 + reused = history * seen_before # Eq. 5 + new = history - reused # Eq. 6 + emb = self._drug_embeddings() + h_reused = self.ptl_reused(reused @ emb, prev_len) # Eq. 7 + h_new = self.ptl_new(new @ emb, prev_len) # Eq. 8 + + # Eq. 9: time-decayed past use; lag 1 is the visit before the prediction + steps = torch.arange(visits, device=history.device).unsqueeze(0) + lag = (prev_len.unsqueeze(1) - steps).clamp(min=1).float() + decay = self.decay_scale * torch.exp(-F.softplus(self.decay_rate) * lag) + used = (history * decay.unsqueeze(-1)).sum(dim=1) # [batch, M] + unused = 1.0 - (history.sum(dim=1) > 0).float() # Eq. 10 + + # Eq. 11 + scale = math.sqrt(self.embedding_dim) + q_reused = torch.softmax( + self.w_reused(torch.einsum("md,bkd->bmk", emb, h_reused)) / scale, dim=1 + ) + q_new = torch.softmax( + self.w_new(torch.einsum("md,bkd->bmk", emb, h_new)) / scale, dim=1 + ) + weight = used.unsqueeze(-1) * q_reused + unused.unsqueeze(-1) * q_new + return emb.unsqueeze(0) * weight * self.label_size + + def _loss(self, prob: torch.Tensor, logit: torch.Tensor, y: torch.Tensor): + """``alpha * BCE + (1 - alpha) * multi-label margin`` (Eq. 20-22).""" + bce = F.binary_cross_entropy_with_logits(logit, y) + diff = 1.0 - (prob.unsqueeze(2) - prob.unsqueeze(1)) # p_i - p_j + pairs = y.unsqueeze(2) * (1.0 - y).unsqueeze(1) # i positive, j negative + margin = (F.relu(diff) * pairs).sum(dim=(1, 2)) / self.label_size + return self.alpha * bce + (1.0 - self.alpha) * margin.mean() + + # --------------------------------------------------------------- forward + def forward(self, **kwargs) -> dict[str, torch.Tensor]: + """Recommends drugs for the last visit of each patient. + + Args: + **kwargs: the batch: ``conditions``, ``procedures`` and + ``drugs_hist`` of shape [batch, visits, codes], and, for the + loss, the ``drugs`` label of shape [batch, num_drugs]. + + Returns: + ``logit`` and ``y_prob`` of shape [batch, num_drugs]; ``loss`` and + ``y_true`` when the label is in the batch. + """ + conditions = kwargs["conditions"].to(self.device) + procedures = kwargs["procedures"].to(self.device) + embedded = self.embedding_model( + {"conditions": conditions, "procedures": procedures} + ) + d = embedded["conditions"].sum(dim=2) # Eq. 12 + p = embedded["procedures"].sum(dim=2) # Eq. 13 + lengths = torch.maximum( + self._visit_lengths(conditions), self._visit_lengths(procedures) + ).clamp(min=1) + patient = torch.cat( + [self.ptl_d(d, lengths), self.ptl_p(p, lengths)], dim=1 + ) # Eq. 14-15 + patient = self.dropout(patient.flatten(1)) + + # previous visits: all but the last one, whose drugs are the target + prev_len = lengths - 1 + history = self._drug_history( + kwargs["drugs_hist"].to(self.device), d.size(1) + ) + valid = torch.arange(history.size(1), device=self.device) < prev_len.unsqueeze(1) + history = history * valid.unsqueeze(-1) + drugs = self._responsive_drugs(history, prev_len) + + o_direct = self.ff_direct(patient) # Eq. 16 + query = self.ff_query(patient) + o_sim = F.cosine_similarity(query.unsqueeze(1), drugs, dim=-1) # Eq. 17-18 + logit = self.w_direct * o_direct + self.w_sim * o_sim # Eq. 19 + y_prob = torch.sigmoid(logit) + out = {"logit": logit, "y_prob": y_prob} + if self.label_key in kwargs: + y_true = kwargs[self.label_key].to(self.device).float() + out["loss"] = self._loss(y_prob, logit, y_true) + out["y_true"] = y_true + return out + + +def _normalize(adj: torch.Tensor) -> torch.Tensor: + """Row-normalizes ``adj + I``, as in Kipf and Welling's GCN.""" + adj = adj + torch.eye(adj.size(0)) + return adj / adj.sum(dim=1, keepdim=True) diff --git a/tests/core/test_armr.py b/tests/core/test_armr.py new file mode 100644 index 0000000000..768dd3460d --- /dev/null +++ b/tests/core/test_armr.py @@ -0,0 +1,137 @@ +import unittest + +import torch + +from pyhealth.datasets import create_sample_dataset, get_dataloader +from pyhealth.models import ARMR +from pyhealth.models.armr import PiecewiseTemporalLearning, _reverse_padded + +SCHEMA = { + "conditions": "nested_sequence", + "procedures": "nested_sequence", + "drugs_hist": "nested_sequence", +} + + +def _samples(): + return [ + {"patient_id": "p0", "visit_id": "v0", + "conditions": [["d1", "d2"], ["d3"]], + "procedures": [["p1"], ["p2"]], + "drugs_hist": [["A01A"], []], + "drugs": ["A01A", "B01A"]}, + # a long history: more visits than n_recent, so the Mamba branch runs + {"patient_id": "p1", "visit_id": "v1", + "conditions": [["d2"], ["d1"], ["d3"], ["d1"], ["d2"]], + "procedures": [["p2"], ["p1"], ["p1"], ["p2"], ["p1"]], + "drugs_hist": [["B01A"], ["C03C", "A01A"], ["B01A"], ["A01A"], []], + "drugs": ["C03C", "N02B"]}, + # a single visit: no drug history at all + {"patient_id": "p2", "visit_id": "v2", + "conditions": [["d3"]], + "procedures": [["p1"]], + "drugs_hist": [[]], + "drugs": ["N02B"]}, + ] + + +class TestARMR(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.dataset = create_sample_dataset( + samples=_samples(), input_schema=SCHEMA, + output_schema={"drugs": "multilabel"}, dataset_name="armr", + ) + cls.batch = next(iter(get_dataloader(cls.dataset, batch_size=3))) + + def test_forward_shapes_with_and_without_graphs(self): + for use_graph in (False, True): + torch.manual_seed(0) + model = ARMR(self.dataset, embedding_dim=16, use_graph=use_graph) + out = model(**self.batch) + self.assertEqual(out["y_prob"].shape, (3, 4)) + self.assertEqual(out["logit"].shape, (3, 4)) + self.assertEqual(out["y_true"].shape, (3, 4)) + self.assertEqual(out["loss"].dim(), 0) + self.assertTrue(((out["y_prob"] >= 0) & (out["y_prob"] <= 1)).all()) + out["loss"].backward() + grads = [p.grad for p in model.parameters() if p.grad is not None] + self.assertTrue(grads) + self.assertFalse(any(torch.isnan(g).any() for g in grads)) + + def test_training_reduces_the_loss(self): + torch.manual_seed(0) + model = ARMR(self.dataset, embedding_dim=16, use_graph=False, dropout=0.0) + optimizer = torch.optim.Adam(model.parameters(), lr=1e-2) + first = None + for _ in range(20): + optimizer.zero_grad() + loss = model(**self.batch)["loss"] + loss.backward() + optimizer.step() + first = first if first is not None else loss.item() + self.assertLess(loss.item(), first * 0.5) + + def test_inference_without_labels(self): + model = ARMR(self.dataset, embedding_dim=16, use_graph=False) + model.eval() + batch = {k: v for k, v in self.batch.items() if k != "drugs"} + with torch.no_grad(): + out = model(**batch) + self.assertEqual(sorted(out), ["logit", "y_prob"]) + + def test_loss_is_the_weighted_bce_and_margin(self): + model = ARMR(self.dataset, embedding_dim=16, use_graph=False, alpha=1.0) + logit = torch.tensor([[2.0, -1.0, 0.5, -3.0]]) + y = torch.tensor([[1.0, 0.0, 1.0, 0.0]]) + bce = torch.nn.functional.binary_cross_entropy_with_logits(logit, y) + self.assertAlmostEqual( + model._loss(torch.sigmoid(logit), logit, y).item(), bce.item(), places=6 + ) + # the margin term alone: pairs (positive i, negative j), divided by |M| + model.alpha = 0.0 + prob = torch.tensor([[0.9, 0.1, 0.6, 0.2]]) + expected = sum( + max(0.0, 1 - (prob[0, i] - prob[0, j]).item()) + for i in (0, 2) for j in (1, 3) + ) / 4 + self.assertAlmostEqual( + model._loss(prob, logit, y).item(), expected, places=6 + ) + + def test_drug_history_splits_reused_and_new_drugs(self): + model = ARMR(self.dataset, embedding_dim=16, use_graph=False) + hist = self.batch["drugs_hist"] + multihot = model._drug_history(hist, hist.size(1)) + vocab = self.dataset.output_processors["drugs"].label_vocab + # patient p1: B01A, then C03C and A01A (both new), then B01A and + # A01A again (both reused) + p1 = multihot[1] + self.assertEqual(p1[0, vocab["B01A"]].item(), 1.0) + self.assertEqual(p1[1, vocab["C03C"]].item(), 1.0) + seen_before = torch.cumsum(p1, 0) - p1 > 0 + reused = p1 * seen_before + self.assertEqual(reused[2, vocab["B01A"]].item(), 1.0) + self.assertEqual(reused[1].sum().item(), 0.0) + + +class TestPiecewiseTemporalLearning(unittest.TestCase): + def test_reverse_padded_keeps_padding_last(self): + x = torch.arange(8.0).view(2, 4, 1) + out = _reverse_padded(x, torch.tensor([3, 1])) + self.assertEqual(out[0, :, 0].tolist(), [2.0, 1.0, 0.0, 3.0]) + self.assertEqual(out[1, :, 0].tolist(), [4.0, 5.0, 6.0, 7.0]) + + def test_output_shape_and_padding_independence(self): + torch.manual_seed(0) + ptl = PiecewiseTemporalLearning(dim=8, n_recent=2).eval() + seq = torch.randn(1, 5, 8) + out = ptl(seq, torch.tensor([5])) + self.assertEqual(out.shape, (1, 4, 8)) + # extra padded visits do not change the result + padded = torch.cat([seq, torch.randn(1, 3, 8)], dim=1) + self.assertTrue(torch.allclose(out, ptl(padded, torch.tensor([5])), atol=1e-6)) + + +if __name__ == "__main__": + unittest.main() From ecd70c7d36c4536cacd59a1a8e58b8cb324a2254 Mon Sep 17 00:00:00 2001 From: solarsys Date: Tue, 3 Nov 2026 05:55:34 -0800 Subject: [PATCH 02/11] ARMR: make the time decay reach the score; share DDI/history helpers - Eq. 9's decayed past use multiplied each drug's whole embedding, which the cosine similarity of Eq. 17-18 ignores, so decay_scale/decay_rate had no effect. Eq. 11 now uses the past-use indicator, and the decayed use is added to each drug's score as a recency term. Documented as a choice where the paper is open. - Move the DDI graph and drugs_hist -> label index map into pyhealth.models.utils (ddi_adjacency, history_to_label_index); GAMENet and ARMR both call them instead of keeping copies. - Document why SelectiveSSM is separate from ehrmamba.MambaBlock (input- dependent dt, B, C vs. a fixed per-channel SSM). - Document that the co-occurrence graph comes from the dataset passed in, so callers should pass the training split. - Tests call _split_reused_new and _responsive_drugs directly, check the recency term orders by lag, check the decay parameters get a gradient, and cover the two shared helpers. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BdtuVKBLhWpYbhTQbaZaTt --- pyhealth/models/armr.py | 87 +++++++++++++++++++++++++------------- pyhealth/models/gamenet.py | 28 ++++-------- pyhealth/models/utils.py | 66 +++++++++++++++++++++++++++++ tests/core/test_armr.py | 66 +++++++++++++++++++++++++---- 4 files changed, 189 insertions(+), 58 deletions(-) diff --git a/pyhealth/models/armr.py b/pyhealth/models/armr.py index 5236a38232..020cf51616 100644 --- a/pyhealth/models/armr.py +++ b/pyhealth/models/armr.py @@ -22,9 +22,9 @@ from pyhealth import BASE_CACHE_PATH as CACHE_PATH from pyhealth.datasets import SampleDataset -from pyhealth.medcode import ATC from pyhealth.models.base_model import BaseModel from pyhealth.models.embedding import EmbeddingModel +from pyhealth.models.utils import ddi_adjacency, history_to_label_index def _reverse_padded(x: torch.Tensor, lengths: torch.Tensor) -> torch.Tensor: @@ -51,6 +51,12 @@ class SelectiveSSM(nn.Module): 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. @@ -179,10 +185,12 @@ class ARMR(BaseModel): network and distant visits through a Mamba block. Its Adaptively Responsive Module splits the medication history into drugs that were reused and drugs that were new at each visit, encodes both, and weights - every drug's embedding by whether the patient took it before, with a - learned time decay for past use. The recommendation fuses a direct score - from the patient representation with the cosine similarity between the - patient and each weighted drug embedding (Eq. 19). The loss is + every drug's embedding with the reused-drug attention if the patient took + it before and the new-drug attention otherwise. The recommendation fuses a + direct score from the patient representation with the cosine similarity + between the patient and each weighted drug embedding (Eq. 19), plus a + learned, time-decayed score for each drug the patient took before. The + loss is ``alpha * BCE + (1 - alpha) * multi-label margin`` (Eq. 22, alpha 0.7). Choices where the paper is open: @@ -190,6 +198,11 @@ class ARMR(BaseModel): - Eq. 9 uses one learned decay rate and scale, ``alpha * exp(-beta * lag)`` summed over the visits in which drug ``j`` was given, where ``lag`` counts visits back from the prediction. + - In Eq. 11 that decayed use multiplies the drug's whole embedding, and + the cosine similarity of Eq. 17-18 cannot see a per-drug scale, so the + decay would have no effect on the output. Here Eq. 11 uses the + indicator of past use instead, and the decayed use is added to the + drug's score (Eq. 19) as a recency term. - Eq. 11's attention maps the drug-history attention to a per-feature weight (``W_o`` and ``W_n`` are ``2N -> dim``), so the weighting changes the direction of a drug's embedding, which cosine similarity sees. @@ -207,7 +220,10 @@ class ARMR(BaseModel): codes are ATC level 3, which the DDI graph needs. Args: - dataset: the training dataset, used for vocabularies and the graphs. + dataset: the training dataset (for example the training split from + :func:`~pyhealth.datasets.split_by_patient`), used for the + vocabularies and the drug co-occurrence graph. Passing the full + dataset lets validation and test labels into that graph. embedding_dim: code and visit embedding size. Default is 64. n_recent: number of recent visits ``N`` handled by the feedforward branch. Default is 3. @@ -316,14 +332,14 @@ def __init__( def _hist_vocab_map(self, label_vocab: dict) -> torch.Tensor: """Maps drugs_hist input indices to label indices; others to a trash bin.""" hist_vocab = self.dataset.input_processors["drugs_hist"].code_vocab - mapping = torch.full((len(hist_vocab),), self.label_size, dtype=torch.long) - for code, idx in hist_vocab.items(): - if code in label_vocab: - mapping[idx] = label_vocab[code] - return mapping + return history_to_label_index(hist_vocab, label_vocab) def _ehr_adj(self, label_vocab: dict) -> torch.Tensor: - """Co-occurrence graph of the drugs given together in a training visit.""" + """Co-occurrence graph of the drugs given together in a visit. + + Built from every sample of ``self.dataset``, so pass the training + split to the model to keep evaluation labels out of it. + """ adj = torch.zeros(self.label_size, self.label_size) for sample in self.dataset: drugs = sample[self.label_key] @@ -338,13 +354,7 @@ def _ehr_adj(self, label_vocab: dict) -> torch.Tensor: def _ddi_adj(self, label_vocab: dict) -> torch.Tensor: """Drug-drug interaction graph at ATC level 3 (as GAMENet and SafeDrug).""" - adj = torch.zeros(self.label_size, self.label_size) - for a, b in ATC().get_ddi(gamenet_ddi=True): - a, b = ATC.convert(a, level=3), ATC.convert(b, level=3) - if a in label_vocab and b in label_vocab: - adj[label_vocab[a], label_vocab[b]] = 1.0 - adj[label_vocab[b], label_vocab[a]] = 1.0 - return adj + return ddi_adjacency(label_vocab) # ---------------------------------------------------------------- pieces def _visit_lengths(self, codes: torch.Tensor) -> torch.Tensor: @@ -382,7 +392,7 @@ def _drug_embeddings(self) -> torch.Tensor: def _responsive_drugs( self, history: torch.Tensor, prev_len: torch.Tensor - ) -> torch.Tensor: + ) -> tuple[torch.Tensor, torch.Tensor]: """The patient's weighted drug embeddings ``E'_m`` (Eq. 5-11). Args: @@ -391,12 +401,12 @@ def _responsive_drugs( prev_len: number of previous visits per patient, [batch]. Returns: - Tensor of shape [batch, M, dim]. + The weighted drug embeddings, [batch, M, dim], and the time-decayed + past use of each drug (Eq. 9), [batch, M], which is zero for drugs + the patient never took. """ visits = history.size(1) - seen_before = torch.cumsum(history, dim=1) - history > 0 - reused = history * seen_before # Eq. 5 - new = history - reused # Eq. 6 + reused, new = _split_reused_new(history) # Eq. 5-6 emb = self._drug_embeddings() h_reused = self.ptl_reused(reused @ emb, prev_len) # Eq. 7 h_new = self.ptl_new(new @ emb, prev_len) # Eq. 8 @@ -406,7 +416,8 @@ def _responsive_drugs( lag = (prev_len.unsqueeze(1) - steps).clamp(min=1).float() decay = self.decay_scale * torch.exp(-F.softplus(self.decay_rate) * lag) used = (history * decay.unsqueeze(-1)).sum(dim=1) # [batch, M] - unused = 1.0 - (history.sum(dim=1) > 0).float() # Eq. 10 + taken = (history.sum(dim=1) > 0).float() + unused = 1.0 - taken # Eq. 10 # Eq. 11 scale = math.sqrt(self.embedding_dim) @@ -416,8 +427,9 @@ def _responsive_drugs( q_new = torch.softmax( self.w_new(torch.einsum("md,bkd->bmk", emb, h_new)) / scale, dim=1 ) - weight = used.unsqueeze(-1) * q_reused + unused.unsqueeze(-1) * q_new - return emb.unsqueeze(0) * weight * self.label_size + # the decay goes into the score (forward) instead: cosine ignores it here + weight = taken.unsqueeze(-1) * q_reused + unused.unsqueeze(-1) * q_new + return emb.unsqueeze(0) * weight * self.label_size, used def _loss(self, prob: torch.Tensor, logit: torch.Tensor, y: torch.Tensor): """``alpha * BCE + (1 - alpha) * multi-label margin`` (Eq. 20-22).""" @@ -462,12 +474,12 @@ def forward(self, **kwargs) -> dict[str, torch.Tensor]: ) valid = torch.arange(history.size(1), device=self.device) < prev_len.unsqueeze(1) history = history * valid.unsqueeze(-1) - drugs = self._responsive_drugs(history, prev_len) + drugs, recency = self._responsive_drugs(history, prev_len) o_direct = self.ff_direct(patient) # Eq. 16 query = self.ff_query(patient) o_sim = F.cosine_similarity(query.unsqueeze(1), drugs, dim=-1) # Eq. 17-18 - logit = self.w_direct * o_direct + self.w_sim * o_sim # Eq. 19 + logit = self.w_direct * o_direct + self.w_sim * o_sim + recency # Eq. 19 y_prob = torch.sigmoid(logit) out = {"logit": logit, "y_prob": y_prob} if self.label_key in kwargs: @@ -477,6 +489,23 @@ def forward(self, **kwargs) -> dict[str, torch.Tensor]: return out +def _split_reused_new(history: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + """Splits multi-hot drugs per visit into reused and new drugs (Eq. 5-6). + + A drug is reused at a visit if the patient took it at an earlier visit, + and new otherwise. + + Args: + history: multi-hot drugs per visit, [batch, visits, M]. + + Returns: + ``(reused, new)``, each of the same shape as ``history``. + """ + seen_before = torch.cumsum(history, dim=1) - history > 0 + reused = history * seen_before + return reused, history - reused + + def _normalize(adj: torch.Tensor) -> torch.Tensor: """Row-normalizes ``adj + I``, as in Kipf and Welling's GCN.""" adj = adj + torch.eye(adj.size(0)) diff --git a/pyhealth/models/gamenet.py b/pyhealth/models/gamenet.py index 9baae5ebf4..f53443b507 100644 --- a/pyhealth/models/gamenet.py +++ b/pyhealth/models/gamenet.py @@ -6,9 +6,13 @@ import torch.nn as nn import numpy as np from pyhealth.datasets import SampleDataset -from pyhealth.medcode import ATC from pyhealth.models import BaseModel -from pyhealth.models.utils import get_last_visit, batch_to_multihot +from pyhealth.models.utils import ( + batch_to_multihot, + ddi_adjacency, + get_last_visit, + history_to_label_index, +) from pyhealth import BASE_CACHE_PATH as CACHE_PATH from pyhealth.models.embedding import EmbeddingModel @@ -445,19 +449,8 @@ def generate_ehr_adj(self) -> torch.tensor: def generate_ddi_adj(self) -> torch.tensor: """Generates the DDI graph adjacency matrix.""" - atc = ATC() - ddi = atc.get_ddi(gamenet_ddi=True) label_vocab = self.dataset.output_processors[self.label_key].label_vocab - label_size = len(label_vocab) - ddi_adj = torch.zeros((label_size, label_size)) - ddi_atc3 = [ - [ATC.convert(l[0], level=3), ATC.convert(l[1], level=3)] for l in ddi - ] - for atc_i, atc_j in ddi_atc3: - if atc_i in label_vocab and atc_j in label_vocab: - ddi_adj[label_vocab[atc_i], label_vocab[atc_j]] = 1 - ddi_adj[label_vocab[atc_j], label_vocab[atc_i]] = 1 - return ddi_adj + return ddi_adjacency(label_vocab) def _build_drug_hist_vocab_map(self) -> torch.Tensor: """Maps drugs_hist input-vocabulary indices to drugs label_vocab @@ -474,12 +467,7 @@ def _build_drug_hist_vocab_map(self) -> torch.Tensor: """ hist_vocab = self.dataset.input_processors["drugs_hist"].code_vocab label_vocab = self.dataset.output_processors[self.label_key].label_vocab - - mapping = torch.full((len(hist_vocab),), self.label_size, dtype=torch.long) - for code, hist_idx in hist_vocab.items(): - if code in label_vocab: - mapping[hist_idx] = label_vocab[code] - return mapping + return history_to_label_index(hist_vocab, label_vocab) def _build_prev_drugs(self, drugs_hist: torch.Tensor) -> torch.Tensor: """Converts the raw drugs_hist tensor into the multi-hot Dynamic diff --git a/pyhealth/models/utils.py b/pyhealth/models/utils.py index 45cd6608d5..a25fea7f34 100644 --- a/pyhealth/models/utils.py +++ b/pyhealth/models/utils.py @@ -72,3 +72,69 @@ def get_rightmost_masked_timestep(hidden_states, mask): last_idx = last_idx.view(batch, 1, 1).expand(batch, 1, hidden) gathered = torch.gather(hidden_states, 1, last_idx) return gathered[:, 0, :] + + +def ddi_adjacency(label_vocab: dict[str, int]) -> torch.Tensor: + """Builds the drug-drug interaction graph over a drug label vocabulary. + + Uses the DDI pairs that GAMENet released (``ATC().get_ddi(gamenet_ddi=True)``) + converted to ATC level 3, so ``label_vocab`` should hold ATC-3 codes, as + the MIMIC drug-recommendation tasks produce. Shared by the drug + recommendation models (GAMENet, ARMR). + + Args: + label_vocab: drug code to label index. + + Returns: + Symmetric 0/1 tensor of shape [len(label_vocab), len(label_vocab)]. + + Examples: + >>> adj = ddi_adjacency({"N02B": 0, "B01A": 1, "C03C": 2}) + >>> adj.shape + torch.Size([3, 3]) + >>> bool((adj == adj.T).all()) + True + """ + from pyhealth.medcode import ATC + + size = len(label_vocab) + adj = torch.zeros((size, size)) + for a, b in ATC().get_ddi(gamenet_ddi=True): + a, b = ATC.convert(a, level=3), ATC.convert(b, level=3) + if a in label_vocab and b in label_vocab: + adj[label_vocab[a], label_vocab[b]] = 1 + adj[label_vocab[b], label_vocab[a]] = 1 + return adj + + +def history_to_label_index( + hist_vocab: dict[str, int], label_vocab: dict[str, int] +) -> torch.Tensor: + """Maps a drug-history input vocabulary onto the drug label vocabulary. + + ``drugs_hist`` is tokenized with its own input vocabulary, which is not + the label vocabulary of ``drugs``. The returned table converts history + indices to label indices. Codes with no label (the processor's + ````/```` tokens, or a history code absent from the labels) map + to ``len(label_vocab)``, a "trash" index to slice away after a scatter. + + Args: + hist_vocab: history code to input index. + label_vocab: drug code to label index. + + Returns: + LongTensor of shape [len(hist_vocab)]. + + Examples: + >>> history_to_label_index( + ... {"": 0, "": 1, "B01A": 2, "X99X": 3}, + ... {"N02B": 0, "B01A": 1}, + ... ).tolist() + [2, 2, 1, 2] + """ + trash = len(label_vocab) + mapping = torch.full((len(hist_vocab),), trash, dtype=torch.long) + for code, idx in hist_vocab.items(): + if code in label_vocab: + mapping[idx] = label_vocab[code] + return mapping diff --git a/tests/core/test_armr.py b/tests/core/test_armr.py index 768dd3460d..8432207cd4 100644 --- a/tests/core/test_armr.py +++ b/tests/core/test_armr.py @@ -4,7 +4,12 @@ from pyhealth.datasets import create_sample_dataset, get_dataloader from pyhealth.models import ARMR -from pyhealth.models.armr import PiecewiseTemporalLearning, _reverse_padded +from pyhealth.models.armr import ( + PiecewiseTemporalLearning, + _reverse_padded, + _split_reused_new, +) +from pyhealth.models.utils import ddi_adjacency, history_to_label_index SCHEMA = { "conditions": "nested_sequence", @@ -106,14 +111,41 @@ def test_drug_history_splits_reused_and_new_drugs(self): vocab = self.dataset.output_processors["drugs"].label_vocab # patient p1: B01A, then C03C and A01A (both new), then B01A and # A01A again (both reused) - p1 = multihot[1] - self.assertEqual(p1[0, vocab["B01A"]].item(), 1.0) - self.assertEqual(p1[1, vocab["C03C"]].item(), 1.0) - seen_before = torch.cumsum(p1, 0) - p1 > 0 - reused = p1 * seen_before - self.assertEqual(reused[2, vocab["B01A"]].item(), 1.0) - self.assertEqual(reused[1].sum().item(), 0.0) - + reused, new = _split_reused_new(multihot) + b, c, a = vocab["B01A"], vocab["C03C"], vocab["A01A"] + self.assertEqual(new[1, 0, b].item(), 1.0) + self.assertEqual(new[1, 1, c].item(), 1.0) + self.assertEqual(new[1, 1, a].item(), 1.0) + self.assertEqual(reused[1, :2].sum().item(), 0.0) + self.assertEqual(reused[1, 2, b].item(), 1.0) + self.assertEqual(reused[1, 3, a].item(), 1.0) + self.assertEqual(new[1, 2:].sum().item(), 0.0) + self.assertTrue(torch.equal(reused + new, multihot)) + + def test_responsive_drugs_decay_reaches_the_score(self): + torch.manual_seed(0) + model = ARMR(self.dataset, embedding_dim=16, use_graph=False) + m = model.label_size + prev_len = torch.tensor([3]) + # drug 0 given one visit back, or three visits back + recent = torch.zeros(1, 4, m) + recent[0, 2, 0] = 1.0 + old = torch.zeros(1, 4, m) + old[0, 0, 0] = 1.0 + _, rec_recent = model._responsive_drugs(recent, prev_len) + _, rec_old = model._responsive_drugs(old, prev_len) + # zero for drugs never taken, larger for more recent use + self.assertEqual(rec_recent[0, 1:].abs().sum().item(), 0.0) + self.assertGreater(rec_recent[0, 0].item(), rec_old[0, 0].item()) + self.assertGreater(rec_old[0, 0].item(), 0.0) + + def test_decay_parameters_get_a_gradient(self): + torch.manual_seed(0) + model = ARMR(self.dataset, embedding_dim=16, use_graph=False) + model(**self.batch)["loss"].backward() + for param in (model.decay_scale, model.decay_rate): + self.assertIsNotNone(param.grad) + self.assertNotEqual(param.grad.item(), 0.0) class TestPiecewiseTemporalLearning(unittest.TestCase): def test_reverse_padded_keeps_padding_last(self): @@ -133,5 +165,21 @@ def test_output_shape_and_padding_independence(self): self.assertTrue(torch.allclose(out, ptl(padded, torch.tensor([5])), atol=1e-6)) +class TestDrugHelpers(unittest.TestCase): + def test_history_to_label_index_sends_unknown_codes_to_trash(self): + mapping = history_to_label_index( + {"": 0, "": 1, "B01A": 2, "X99X": 3}, {"N02B": 0, "B01A": 1} + ) + self.assertEqual(mapping.tolist(), [2, 2, 1, 2]) + + def test_ddi_adjacency_is_a_symmetric_0_1_matrix(self): + vocab = {"N02B": 0, "B01A": 1, "C03C": 2, "N02A": 3, "M01A": 4} + adj = ddi_adjacency(vocab) + self.assertEqual(adj.shape, (5, 5)) + self.assertTrue(torch.equal(adj, adj.T)) + self.assertTrue(((adj == 0) | (adj == 1)).all()) + self.assertGreater(adj.sum().item(), 0.0) + + if __name__ == "__main__": unittest.main() From 27012ac048a983d6750d04a9d36ced5482fdd887 Mon Sep 17 00:00:00 2001 From: solarsys Date: Tue, 3 Nov 2026 05:55:50 -0800 Subject: [PATCH 03/11] GAMENet: drop the unused batch_to_multihot import Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BdtuVKBLhWpYbhTQbaZaTt --- pyhealth/models/gamenet.py | 1 - 1 file changed, 1 deletion(-) diff --git a/pyhealth/models/gamenet.py b/pyhealth/models/gamenet.py index f53443b507..360fd37e5b 100644 --- a/pyhealth/models/gamenet.py +++ b/pyhealth/models/gamenet.py @@ -8,7 +8,6 @@ from pyhealth.datasets import SampleDataset from pyhealth.models import BaseModel from pyhealth.models.utils import ( - batch_to_multihot, ddi_adjacency, get_last_visit, history_to_label_index, From 6bf16ada8b1796c3ce0c206fd0088ac5d74be099 Mon Sep 17 00:00:00 2001 From: solarsys Date: Tue, 3 Nov 2026 05:57:19 -0800 Subject: [PATCH 04/11] ARMR notebook: train-split graphs, upstream install, refreshed outputs - Models are built from the training split, so the drug co-occurrence graphs no longer see validation/test labels. - Colab installs from the upstream PR ref instead of a fork branch. - The DDI matrix comes from pyhealth.models.utils.ddi_adjacency. - Drop the unmeasured Part 2 runtime; describe the decay change. - Part 1 re-run with the updated model. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BdtuVKBLhWpYbhTQbaZaTt --- .../armr_mimic3_drug_recommendation.ipynb | 104 +++++++++--------- 1 file changed, 52 insertions(+), 52 deletions(-) diff --git a/examples/armr_mimic3_drug_recommendation.ipynb b/examples/armr_mimic3_drug_recommendation.ipynb index ad548c5036..73c679340d 100644 --- a/examples/armr_mimic3_drug_recommendation.ipynb +++ b/examples/armr_mimic3_drug_recommendation.ipynb @@ -13,8 +13,8 @@ "\n", "ARMR has three parts:\n", "- **Piecewise temporal learning.** The most recent visits go through a feedforward network and the earlier ones through a Mamba block; the recent states attend over the distant ones.\n", - "- **Adaptively responsive module.** The medication history is split into drugs that were reused and drugs that were new at each visit. Each drug's embedding is weighted by whether the patient took it before, with a learned time decay.\n", - "- **Joint recommendation.** A direct score from the patient representation is fused with the cosine similarity between the patient and each weighted drug embedding. The loss is 0.7 \u00d7 BCE + 0.3 \u00d7 multi-label margin.\n", + "- **Adaptively responsive module.** The medication history is split into drugs that were reused and drugs that were new at each visit. Each drug's embedding is weighted by attention over the reused drugs if the patient took it before, and over the new drugs otherwise; a learned, time-decayed score for past use is added to the drug's score.\n", + "- **Joint recommendation.** A direct score from the patient representation is fused with the cosine similarity between the patient and each weighted drug embedding. The loss is 0.7 × BCE + 0.3 × multi-label margin.\n", "\n", "**How to use it.** Part 1 runs end to end on PyHealth's open synthetic MIMIC-III, with no credentials. Part 2 repeats the experiment on real MIMIC-III v1.4: set `MIMIC3_ROOT` to your copy (PhysioNet credentials required) and run it." ] @@ -26,7 +26,7 @@ "source": [ "## Setup\n", "\n", - "On Colab this installs PyHealth from the branch that adds ARMR. After the pull request is merged, install `pyhealth` from PyPI or from `master` instead." + "On Colab this installs PyHealth from the pull request that adds ARMR ([#1371](https://github.com/sunlabuiuc/PyHealth/pull/1371)). After it is merged, install `pyhealth` from PyPI or from `master` instead." ] }, { @@ -35,10 +35,10 @@ "id": "dfbb0f34", "metadata": { "execution": { - "iopub.execute_input": "2026-11-03T07:53:36.971041Z", - "iopub.status.busy": "2026-11-03T07:53:36.970886Z", - "iopub.status.idle": "2026-11-03T07:53:36.978785Z", - "shell.execute_reply": "2026-11-03T07:53:36.975561Z" + "iopub.execute_input": "2026-11-03T13:55:11.396947Z", + "iopub.status.busy": "2026-11-03T13:55:11.396867Z", + "iopub.status.idle": "2026-11-03T13:55:11.401817Z", + "shell.execute_reply": "2026-11-03T13:55:11.401365Z" } }, "outputs": [], @@ -49,7 +49,7 @@ "if \"google.colab\" in sys.modules:\n", " subprocess.run(\n", " [sys.executable, \"-m\", \"pip\", \"install\", \"-q\",\n", - " \"git+https://github.com/solarsys/PyHealth@feat/armr\"],\n", + " \"git+https://github.com/sunlabuiuc/PyHealth@refs/pull/1371/head\"],\n", " check=True,\n", " )" ] @@ -60,10 +60,10 @@ "id": "ef9a1fcf", "metadata": { "execution": { - "iopub.execute_input": "2026-11-03T07:53:36.985899Z", - "iopub.status.busy": "2026-11-03T07:53:36.984941Z", - "iopub.status.idle": "2026-11-03T07:54:06.213575Z", - "shell.execute_reply": "2026-11-03T07:54:06.209334Z" + "iopub.execute_input": "2026-11-03T13:55:11.403157Z", + "iopub.status.busy": "2026-11-03T13:55:11.403081Z", + "iopub.status.idle": "2026-11-03T13:55:16.886787Z", + "shell.execute_reply": "2026-11-03T13:55:16.886305Z" } }, "outputs": [], @@ -75,9 +75,9 @@ "import torch\n", "\n", "from pyhealth.datasets import MIMIC3Dataset, get_dataloader, split_by_patient\n", - "from pyhealth.medcode import ATC\n", "from pyhealth.metrics import ddi_rate_score\n", "from pyhealth.models import ARMR, GAMENet, RETAIN, SafeDrug\n", + "from pyhealth.models.utils import ddi_adjacency\n", "from pyhealth.tasks import DrugRecommendationMIMIC3\n", "from pyhealth.trainer import Trainer\n", "\n", @@ -92,13 +92,7 @@ "\n", "def ddi_matrix(samples) -> np.ndarray:\n", " \"\"\"Drug-drug interactions between the task's ATC-3 drugs (as GAMENet and SafeDrug).\"\"\"\n", - " vocab = samples.output_processors[\"drugs\"].label_vocab\n", - " adj = np.zeros((len(vocab), len(vocab)))\n", - " for a, b in ATC().get_ddi(gamenet_ddi=True):\n", - " a, b = ATC.convert(a, level=3), ATC.convert(b, level=3)\n", - " if a in vocab and b in vocab:\n", - " adj[vocab[a], vocab[b]] = adj[vocab[b], vocab[a]] = 1\n", - " return adj\n", + " return ddi_adjacency(samples.output_processors[\"drugs\"].label_vocab).numpy()\n", "\n", "\n", "def load_samples(root: str, dev: bool = False):\n", @@ -132,7 +126,9 @@ " rows = {}\n", " for name, (make, lr) in MODELS.items():\n", " seed_everything(seed)\n", - " trainer = Trainer(model=make(samples), metrics=METRICS, enable_logging=False)\n", + " # models see the training patients only: ARMR's and GAMENet's drug\n", + " # co-occurrence graphs are built from the samples they are given\n", + " trainer = Trainer(model=make(train), metrics=METRICS, enable_logging=False)\n", " trainer.train(\n", " train_dataloader=loaders[0], val_dataloader=loaders[1], epochs=epochs,\n", " optimizer_params={\"lr\": lr}, monitor=\"jaccard_samples\",\n", @@ -154,7 +150,11 @@ "cell_type": "markdown", "id": "0ae6ab06", "metadata": {}, - "source": "## Part 1: open synthetic MIMIC-III (no credentials)\n\nPyHealth hosts a synthetic MIMIC-III with the real schema. It is useful for checking that everything runs; its scores say nothing about the paper's results. Three epochs take a few minutes on a CPU. That is too short for ARMR, which trains at the authors' learning rate (2e-4, five times lower than the baselines'), so it trails here; the comparison that matters is Part 2's." + "source": [ + "## Part 1: open synthetic MIMIC-III (no credentials)\n", + "\n", + "PyHealth hosts a synthetic MIMIC-III with the real schema. It is useful for checking that everything runs; its scores say nothing about the paper's results. Three epochs take a few minutes on a CPU. That is too short for ARMR, which trains at the authors' learning rate (2e-4, five times lower than the baselines'), so it trails here; the comparison that matters is Part 2's." + ] }, { "cell_type": "code", @@ -162,10 +162,10 @@ "id": "b38a21cf", "metadata": { "execution": { - "iopub.execute_input": "2026-11-03T07:54:06.227603Z", - "iopub.status.busy": "2026-11-03T07:54:06.225700Z", - "iopub.status.idle": "2026-11-03T08:01:11.638215Z", - "shell.execute_reply": "2026-11-03T08:01:11.633883Z" + "iopub.execute_input": "2026-11-03T13:55:16.888827Z", + "iopub.status.busy": "2026-11-03T13:55:16.888525Z", + "iopub.status.idle": "2026-11-03T13:56:59.097336Z", + "shell.execute_reply": "2026-11-03T13:56:59.096844Z" } }, "outputs": [ @@ -206,31 +206,31 @@ " \n", " \n", " ARMR\n", - " 24.34\n", - " 46.17\n", - " 36.24\n", - " 6.46\n", + " 24.44\n", + " 46.35\n", + " 36.31\n", + " 6.81\n", " \n", " \n", " GAMENet\n", - " 30.77\n", - " 56.33\n", - " 43.83\n", - " 4.51\n", + " 30.63\n", + " 56.60\n", + " 44.07\n", + " 8.11\n", " \n", " \n", " SafeDrug\n", - " 31.19\n", - " 55.40\n", - " 44.27\n", - " 8.20\n", + " 31.81\n", + " 54.84\n", + " 45.27\n", + " 6.43\n", " \n", " \n", " RETAIN\n", - " 28.75\n", - " 53.94\n", - " 41.28\n", - " 7.46\n", + " 29.22\n", + " 54.15\n", + " 41.80\n", + " 7.47\n", " \n", " \n", "\n", @@ -238,10 +238,10 @@ ], "text/plain": [ " Jaccard PRAUC F1 DDI rate\n", - "ARMR 24.34 46.17 36.24 6.46\n", - "GAMENet 30.77 56.33 43.83 4.51\n", - "SafeDrug 31.19 55.40 44.27 8.20\n", - "RETAIN 28.75 53.94 41.28 7.46" + "ARMR 24.44 46.35 36.31 6.81\n", + "GAMENet 30.63 56.60 44.07 8.11\n", + "SafeDrug 31.81 54.84 45.27 6.43\n", + "RETAIN 29.22 54.15 41.80 7.47" ] }, "execution_count": 3, @@ -263,7 +263,7 @@ "source": [ "## Part 2: MIMIC-III v1.4 (credentialed)\n", "\n", - "Set `MIMIC3_ROOT` to the folder with `ADMISSIONS.csv.gz`, `DIAGNOSES_ICD.csv.gz`, `PROCEDURES_ICD.csv.gz` and `PRESCRIPTIONS.csv.gz` (for example a mounted Google Drive folder). On a Colab GPU, 50 epochs take roughly an hour for all four models.\n", + "Set `MIMIC3_ROOT` to the folder with `ADMISSIONS.csv.gz`, `DIAGNOSES_ICD.csv.gz`, `PROCEDURES_ICD.csv.gz` and `PRESCRIPTIONS.csv.gz` (for example a mounted Google Drive folder).\n", "\n", "The paper reports, on its MIMIC-III and MIMIC-IV cohorts (Table 2, %):\n", "\n", @@ -281,10 +281,10 @@ "id": "13e4d4ce", "metadata": { "execution": { - "iopub.execute_input": "2026-11-03T08:01:11.680479Z", - "iopub.status.busy": "2026-11-03T08:01:11.679908Z", - "iopub.status.idle": "2026-11-03T08:01:11.698246Z", - "shell.execute_reply": "2026-11-03T08:01:11.697229Z" + "iopub.execute_input": "2026-11-03T13:56:59.098667Z", + "iopub.status.busy": "2026-11-03T13:56:59.098585Z", + "iopub.status.idle": "2026-11-03T13:56:59.101010Z", + "shell.execute_reply": "2026-11-03T13:56:59.100605Z" } }, "outputs": [ @@ -316,7 +316,7 @@ "## Notes for reproducing the paper\n", "\n", "- `ARMR(..., use_graph=True)` (the default) adds GCN embeddings of the drug co-occurrence and drug-drug interaction graphs to the drug embeddings, as the authors' released code does. `use_graph=False` gives the equations exactly as written in the paper.\n", - "- Three details the paper leaves open, and the choices made: Eq. 9's time decay is one learned scale and rate; Eq. 11's attention gives a weight per embedding feature; the \"recent\" segment is the N visits closest to the prediction.\n", + "- Three details the paper leaves open, and the choices made: Eq. 9's time decay is one learned scale and rate, added to each drug's score (in Eq. 11 it would only rescale a drug's embedding, which the cosine similarity ignores); Eq. 11's attention gives a weight per embedding feature; the \"recent\" segment is the N visits closest to the prediction.\n", "- Questions or corrections: please open an issue at https://github.com/sunlabuiuc/PyHealth or write on the PyHealth Discord." ] } From 9aba5ef1c0cbc52f510cf6e20ccfe65fc5e503e3 Mon Sep 17 00:00:00 2001 From: solarsys Date: Tue, 3 Nov 2026 06:20:56 -0800 Subject: [PATCH 05/11] Use the shared ddi_adjacency in SafeDrug, MICRON and MoleRec; ARMR visit lengths - SafeDrug, MICRON and MoleRec's generate_ddi_adj now call pyhealth.models.utils.ddi_adjacency. Checked first that each model's old matrix is identical (np.array_equal) to the helper's on the mimic3demo test data and synthetic MIMIC-III (full and training split). Their ddi_adj.npy writes are unchanged. - ARMR writes ddi_adj.npy with or without use_graph, since the "ddi" metric reads it during evaluation. - ARMR's _visit_lengths takes the position of the last non-empty visit, so an empty visit in the middle no longer shortens the sequence; test added. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BdtuVKBLhWpYbhTQbaZaTt --- pyhealth/models/armr.py | 21 +++++++++++++++----- pyhealth/models/micron.py | 19 +++--------------- pyhealth/models/molerec.py | 15 ++------------ pyhealth/models/safedrug.py | 39 ++++++++++++++++++++++++------------- pyhealth/models/utils.py | 2 +- tests/core/test_armr.py | 22 +++++++++++++++++++++ 6 files changed, 69 insertions(+), 49 deletions(-) diff --git a/pyhealth/models/armr.py b/pyhealth/models/armr.py index 020cf51616..b70524fe07 100644 --- a/pyhealth/models/armr.py +++ b/pyhealth/models/armr.py @@ -307,14 +307,17 @@ def __init__( self.decay_scale = nn.Parameter(torch.tensor(1.0)) # alpha in Eq. 9 self.decay_rate = nn.Parameter(torch.tensor(0.0)) # softplus -> beta + ddi_adj = self._ddi_adj(label_vocab) if use_graph: - ddi_adj = self._ddi_adj(label_vocab) self.register_buffer("ehr_adj", _normalize(self._ehr_adj(label_vocab))) self.register_buffer("ddi_adj_norm", _normalize(ddi_adj)) self.gcn_ehr = nn.ModuleList([nn.Linear(dim, dim), nn.Linear(dim, dim)]) self.gcn_ddi = nn.ModuleList([nn.Linear(dim, dim), nn.Linear(dim, dim)]) - os.makedirs(CACHE_PATH, exist_ok=True) - np.save(os.path.join(CACHE_PATH, "ddi_adj.npy"), ddi_adj.numpy()) + # the "ddi" metric (pyhealth.metrics.multilabel) reads this file, as + # for GAMENet, SafeDrug, MICRON and MoleRec; written with or without + # the graphs so that metric works either way + os.makedirs(CACHE_PATH, exist_ok=True) + np.save(os.path.join(CACHE_PATH, "ddi_adj.npy"), ddi_adj.numpy()) # Joint recommendation (Eq. 16-19) patient_size = 4 * n_recent * dim @@ -358,8 +361,16 @@ def _ddi_adj(self, label_vocab: dict) -> torch.Tensor: # ---------------------------------------------------------------- pieces def _visit_lengths(self, codes: torch.Tensor) -> torch.Tensor: - """Number of visits with at least one code, per patient.""" - return (codes > 0).any(dim=-1).sum(dim=1) + """Number of visits per patient: the last visit with a code, plus one. + + An empty visit is all padding, like the padded visits after the end, + so counting non-empty visits would undercount a patient with an + empty visit in the middle; the position of the last non-empty visit + does not. + """ + nonempty = (codes > 0).any(dim=-1) # [batch, visits] + position = torch.arange(1, codes.size(1) + 1, device=codes.device) + return (nonempty * position).amax(dim=1) def _drug_history(self, drugs_hist: torch.Tensor, visits: int) -> torch.Tensor: """Multi-hot drugs of each visit in the label space, [batch, visits, M].""" diff --git a/pyhealth/models/micron.py b/pyhealth/models/micron.py index dd52ef4513..537358d211 100644 --- a/pyhealth/models/micron.py +++ b/pyhealth/models/micron.py @@ -13,9 +13,8 @@ SequenceProcessor, StageNetProcessor, StageNetTensorProcessor, TimeseriesProcessor, TensorProcessor, MultiHotProcessor ) from pyhealth.processors.base_processor import FeatureProcessor -from pyhealth.models.utils import get_last_visit +from pyhealth.models.utils import ddi_adjacency, get_last_visit from pyhealth import BASE_CACHE_PATH as CACHE_PATH -from pyhealth.medcode import ATC class MICRONLayer(nn.Module): """MICRON layer. @@ -352,19 +351,7 @@ def forward(self, **kwargs) -> Dict[str, torch.Tensor]: def generate_ddi_adj(self) -> torch.Tensor: """Generates the drug-drug interaction (DDI) graph adjacency matrix using PyHealth 2.0 label processor.""" - atc = ATC() - ddi = atc.get_ddi(gamenet_ddi=True) - label_processor = self.dataset.output_processors[self.label_key] - label_size = label_processor.size() - vocab_to_index = label_processor.label_vocab - ddi_adj = np.zeros((label_size, label_size)) - ddi_atc3 = [ - [ATC.convert(l[0], level=3), ATC.convert(l[1], level=3)] for l in ddi - ] - for atc_i, atc_j in ddi_atc3: - if atc_i in vocab_to_index and atc_j in vocab_to_index: - ddi_adj[vocab_to_index[atc_i], vocab_to_index[atc_j]] = 1 - ddi_adj[vocab_to_index[atc_j], vocab_to_index[atc_i]] = 1 - return torch.tensor(ddi_adj, dtype=torch.float) + label_vocab = self.dataset.output_processors[self.label_key].label_vocab + return ddi_adjacency(label_vocab) diff --git a/pyhealth/models/molerec.py b/pyhealth/models/molerec.py index b4100d0ccb..bec1136c40 100644 --- a/pyhealth/models/molerec.py +++ b/pyhealth/models/molerec.py @@ -10,7 +10,7 @@ from torch.nn.functional import multilabel_margin_loss from pyhealth.models import BaseModel -from pyhealth.models.utils import get_last_visit +from pyhealth.models.utils import ddi_adjacency, get_last_visit from pyhealth.models.utils import batch_to_multihot from pyhealth.models.embedding import EmbeddingModel from pyhealth.metrics import ddi_rate_score @@ -677,19 +677,8 @@ def __init__( def generate_ddi_adj(self) -> torch.FloatTensor: """Generates the DDI graph adjacency matrix.""" - atc = ATC() - ddi = atc.get_ddi(gamenet_ddi=True) label_vocab = self.dataset.output_processors[self.label_key].label_vocab - ddi_adj = np.zeros((self.label_size, self.label_size)) - ddi_atc3 = [ - [ATC.convert(l[0], level=3), ATC.convert(l[1], level=3)] for l in ddi - ] - for atc_i, atc_j in ddi_atc3: - if atc_i in label_vocab and atc_j in label_vocab: - ddi_adj[label_vocab[atc_i], label_vocab[atc_j]] = 1 - ddi_adj[label_vocab[atc_j], label_vocab[atc_i]] = 1 - ddi_adj = torch.FloatTensor(ddi_adj) - return ddi_adj + return ddi_adjacency(label_vocab) def generate_substructure_mask(self) -> Tuple[torch.Tensor, List[str]]: all_substructures_list = [[] for _ in range(self.label_size)] diff --git a/pyhealth/models/safedrug.py b/pyhealth/models/safedrug.py index 7b677169d5..681ffef1ad 100644 --- a/pyhealth/models/safedrug.py +++ b/pyhealth/models/safedrug.py @@ -17,7 +17,7 @@ from pyhealth.medcode import ATC from pyhealth.metrics import ddi_rate_score from pyhealth.models import BaseModel -from pyhealth.models.utils import get_last_visit +from pyhealth.models.utils import ddi_adjacency, get_last_visit from pyhealth.models.embedding import EmbeddingModel from pyhealth import BASE_CACHE_PATH as CACHE_PATH @@ -327,6 +327,29 @@ class SafeDrug(BaseModel): num_layers: the number of layers used in RNN. Default is 1. dropout: the dropout rate. Default is 0.5. **kwargs: other parameters for the SafeDrug layer. + + Examples: + >>> from pyhealth.datasets import create_sample_dataset, get_dataloader + >>> samples = [ + ... {"patient_id": "p0", "visit_id": "v0", + ... "conditions": [["c1", "c2"], ["c3"]], + ... "procedures": [["p1"], ["p2"]], + ... "drugs": ["A01A", "B01A"]}, + ... {"patient_id": "p1", "visit_id": "v1", + ... "conditions": [["c2"]], "procedures": [["p1"]], + ... "drugs": ["N02B"]}, + ... ] + >>> dataset = create_sample_dataset( + ... samples=samples, + ... input_schema={"conditions": "nested_sequence", + ... "procedures": "nested_sequence"}, + ... output_schema={"drugs": "multilabel"}, + ... dataset_name="demo", + ... ) + >>> model = SafeDrug(dataset) + >>> batch = next(iter(get_dataloader(dataset, batch_size=2))) + >>> sorted(model(**batch)) + ['loss', 'y_prob', 'y_true'] """ def __init__( @@ -435,20 +458,8 @@ def __init__( def generate_ddi_adj(self) -> torch.tensor: """Generates the DDI graph adjacency matrix.""" - atc = ATC() - ddi = atc.get_ddi(gamenet_ddi=True) label_vocab = self.dataset.output_processors[self.label_key].label_vocab - label_size = len(label_vocab) - ddi_adj = np.zeros((label_size, label_size)) - ddi_atc3 = [ - [ATC.convert(l[0], level=3), ATC.convert(l[1], level=3)] for l in ddi - ] - for atc_i, atc_j in ddi_atc3: - if atc_i in label_vocab and atc_j in label_vocab: - ddi_adj[label_vocab[atc_i], label_vocab[atc_j]] = 1 - ddi_adj[label_vocab[atc_j], label_vocab[atc_i]] = 1 - ddi_adj = torch.FloatTensor(ddi_adj) - return ddi_adj + return ddi_adjacency(label_vocab) def generate_smiles_list(self) -> List[List[str]]: """Generates the list of SMILES strings.""" diff --git a/pyhealth/models/utils.py b/pyhealth/models/utils.py index a25fea7f34..615a0ef1bc 100644 --- a/pyhealth/models/utils.py +++ b/pyhealth/models/utils.py @@ -80,7 +80,7 @@ def ddi_adjacency(label_vocab: dict[str, int]) -> torch.Tensor: Uses the DDI pairs that GAMENet released (``ATC().get_ddi(gamenet_ddi=True)``) converted to ATC level 3, so ``label_vocab`` should hold ATC-3 codes, as the MIMIC drug-recommendation tasks produce. Shared by the drug - recommendation models (GAMENet, ARMR). + recommendation models (GAMENet, SafeDrug, MICRON, MoleRec, ARMR). Args: label_vocab: drug code to label index. diff --git a/tests/core/test_armr.py b/tests/core/test_armr.py index 8432207cd4..d73879d8d6 100644 --- a/tests/core/test_armr.py +++ b/tests/core/test_armr.py @@ -139,6 +139,28 @@ def test_responsive_drugs_decay_reaches_the_score(self): self.assertGreater(rec_recent[0, 0].item(), rec_old[0, 0].item()) self.assertGreater(rec_old[0, 0].item(), 0.0) + def test_visit_lengths_count_an_empty_middle_visit(self): + samples = [ + {"patient_id": "p0", "visit_id": "v0", + "conditions": [["d1"], [], ["d2"]], + "procedures": [["p1"], [], ["p2"]], + "drugs_hist": [["A01A"], ["B01A"], []], + "drugs": ["A01A"]}, + {"patient_id": "p1", "visit_id": "v1", + "conditions": [["d1"]], "procedures": [["p1"]], + "drugs_hist": [[]], "drugs": ["B01A"]}, + ] + dataset = create_sample_dataset( + samples=samples, input_schema=SCHEMA, + output_schema={"drugs": "multilabel"}, dataset_name="armr_gap", + ) + batch = next(iter(get_dataloader(dataset, batch_size=2))) + model = ARMR(dataset, embedding_dim=16, use_graph=False) + self.assertEqual(model._visit_lengths(batch["conditions"]).tolist(), [3, 1]) + out = model(**batch) + self.assertEqual(out["logit"].shape, (2, 2)) + self.assertFalse(torch.isnan(out["loss"])) + def test_decay_parameters_get_a_gradient(self): torch.manual_seed(0) model = ARMR(self.dataset, embedding_dim=16, use_graph=False) From 787c221cee6507b32830b2bd5b7f79f42128a106 Mon Sep 17 00:00:00 2001 From: solarsys Date: Tue, 3 Nov 2026 06:40:19 -0800 Subject: [PATCH 06/11] ARMR: graph_dataset for the co-occurrence graph; DDI helper tests - ARMR takes graph_dataset, the samples its drug co-occurrence graph is built from. With use_graph=True and no graph_dataset it falls back to dataset and warns that the training split should be passed. The notebook passes the training split explicitly. - Drop the constant label_size factor on the weighted drug embeddings: they only feed the cosine similarity, which ignores a positive scale. - Tests: the warning, the graph built only from graph_dataset, and SafeDrug's and MoleRec's generate_ddi_adj matching ddi_adjacency. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BdtuVKBLhWpYbhTQbaZaTt --- .../armr_mimic3_drug_recommendation.ipynb | 8 ++-- pyhealth/models/armr.py | 40 ++++++++++++++----- tests/core/test_armr.py | 27 ++++++++++++- tests/core/test_molerec.py | 23 +++++++++++ tests/core/test_safedrug.py | 23 +++++++++++ 5 files changed, 107 insertions(+), 14 deletions(-) diff --git a/examples/armr_mimic3_drug_recommendation.ipynb b/examples/armr_mimic3_drug_recommendation.ipynb index 73c679340d..85101eb1e2 100644 --- a/examples/armr_mimic3_drug_recommendation.ipynb +++ b/examples/armr_mimic3_drug_recommendation.ipynb @@ -106,8 +106,10 @@ "\n", "\n", "MODELS = {\n", - " # ARMR's defaults follow the paper; lr 2e-4 is the authors' setting\n", - " \"ARMR\": (lambda s: ARMR(s, embedding_dim=64, n_recent=3), 2e-4),\n", + " # ARMR's defaults follow the paper; lr 2e-4 is the authors' setting.\n", + " # `s` is the training split; ARMR builds its drug co-occurrence graph\n", + " # from graph_dataset, so test-patient labels stay out of it.\n", + " \"ARMR\": (lambda s: ARMR(s, embedding_dim=64, n_recent=3, graph_dataset=s), 2e-4),\n", " \"GAMENet\": (lambda s: GAMENet(s), 1e-3),\n", " \"SafeDrug\": (lambda s: SafeDrug(s), 1e-3),\n", " \"RETAIN\": (lambda s: RETAIN(s), 1e-3),\n", @@ -315,7 +317,7 @@ "source": [ "## Notes for reproducing the paper\n", "\n", - "- `ARMR(..., use_graph=True)` (the default) adds GCN embeddings of the drug co-occurrence and drug-drug interaction graphs to the drug embeddings, as the authors' released code does. `use_graph=False` gives the equations exactly as written in the paper.\n", + "- `ARMR(..., use_graph=True)` (the default) adds GCN embeddings of the drug co-occurrence and drug-drug interaction graphs to the drug embeddings, as the authors' released code does. `use_graph=False` gives the equations exactly as written in the paper. With the graphs, pass the training split as `graph_dataset` so the co-occurrence graph never sees evaluation labels (ARMR warns if it is missing).\n", "- Three details the paper leaves open, and the choices made: Eq. 9's time decay is one learned scale and rate, added to each drug's score (in Eq. 11 it would only rescale a drug's embedding, which the cosine similarity ignores); Eq. 11's attention gives a weight per embedding feature; the \"recent\" segment is the N visits closest to the prediction.\n", "- Questions or corrections: please open an issue at https://github.com/sunlabuiuc/PyHealth or write on the PyHealth Discord." ] diff --git a/pyhealth/models/armr.py b/pyhealth/models/armr.py index b70524fe07..c9fbb1134a 100644 --- a/pyhealth/models/armr.py +++ b/pyhealth/models/armr.py @@ -14,6 +14,7 @@ import math import os +import warnings import numpy as np import torch @@ -220,10 +221,9 @@ class ARMR(BaseModel): codes are ATC level 3, which the DDI graph needs. Args: - dataset: the training dataset (for example the training split from - :func:`~pyhealth.datasets.split_by_patient`), used for the - vocabularies and the drug co-occurrence graph. Passing the full - dataset lets validation and test labels into that graph. + dataset: the dataset whose processors give the vocabularies. A + split from :func:`~pyhealth.datasets.split_by_patient` works, as + does the full dataset. embedding_dim: code and visit embedding size. Default is 64. n_recent: number of recent visits ``N`` handled by the feedforward branch. Default is 3. @@ -231,6 +231,10 @@ class ARMR(BaseModel): dropout: dropout on the patient representation. Default is 0.3. use_graph: add the co-occurrence and DDI graph embeddings to the drug embeddings, as the authors' code does. Default is True. + graph_dataset: the samples the drug co-occurrence graph is built + from; pass the training split, so that validation and test + labels stay out of the model. If ``use_graph`` is True and this is + None, the graph is built from ``dataset`` with a warning. Examples: >>> from pyhealth.datasets import create_sample_dataset @@ -255,6 +259,8 @@ class ARMR(BaseModel): ... dataset_name="demo", ... ) >>> model = ARMR(dataset, embedding_dim=16, use_graph=False) + >>> # with the graphs, give the training split explicitly: + >>> # ARMR(dataset, graph_dataset=train_split) >>> from pyhealth.datasets import get_dataloader >>> batch = next(iter(get_dataloader(dataset, batch_size=2))) >>> out = model(**batch) @@ -270,6 +276,7 @@ def __init__( alpha: float = 0.7, dropout: float = 0.3, use_graph: bool = True, + graph_dataset: SampleDataset | None = None, ): super().__init__(dataset=dataset) for key in ("conditions", "procedures", "drugs_hist"): @@ -309,7 +316,18 @@ def __init__( ddi_adj = self._ddi_adj(label_vocab) if use_graph: - self.register_buffer("ehr_adj", _normalize(self._ehr_adj(label_vocab))) + if graph_dataset is None: + warnings.warn( + "ARMR(use_graph=True) builds its drug co-occurrence graph " + "from the drug labels of every sample in `dataset`. Pass " + "the training split as `graph_dataset` so that validation " + "and test labels do not leak into the model.", + UserWarning, + stacklevel=2, + ) + graph_dataset = self.dataset + ehr_adj = self._ehr_adj(label_vocab, graph_dataset) + self.register_buffer("ehr_adj", _normalize(ehr_adj)) self.register_buffer("ddi_adj_norm", _normalize(ddi_adj)) self.gcn_ehr = nn.ModuleList([nn.Linear(dim, dim), nn.Linear(dim, dim)]) self.gcn_ddi = nn.ModuleList([nn.Linear(dim, dim), nn.Linear(dim, dim)]) @@ -337,14 +355,16 @@ def _hist_vocab_map(self, label_vocab: dict) -> torch.Tensor: hist_vocab = self.dataset.input_processors["drugs_hist"].code_vocab return history_to_label_index(hist_vocab, label_vocab) - def _ehr_adj(self, label_vocab: dict) -> torch.Tensor: + def _ehr_adj(self, label_vocab: dict, samples) -> torch.Tensor: """Co-occurrence graph of the drugs given together in a visit. - Built from every sample of ``self.dataset``, so pass the training - split to the model to keep evaluation labels out of it. + Args: + label_vocab: drug code to label index. + samples: the samples to read the drug labels from (the training + split). """ adj = torch.zeros(self.label_size, self.label_size) - for sample in self.dataset: + for sample in samples: drugs = sample[self.label_key] if isinstance(drugs, torch.Tensor): # processed: multi-hot ids = torch.nonzero(drugs.flatten()).flatten() @@ -440,7 +460,7 @@ def _responsive_drugs( ) # the decay goes into the score (forward) instead: cosine ignores it here weight = taken.unsqueeze(-1) * q_reused + unused.unsqueeze(-1) * q_new - return emb.unsqueeze(0) * weight * self.label_size, used + return emb.unsqueeze(0) * weight, used def _loss(self, prob: torch.Tensor, logit: torch.Tensor, y: torch.Tensor): """``alpha * BCE + (1 - alpha) * multi-label margin`` (Eq. 20-22).""" diff --git a/tests/core/test_armr.py b/tests/core/test_armr.py index d73879d8d6..57f5135153 100644 --- a/tests/core/test_armr.py +++ b/tests/core/test_armr.py @@ -1,4 +1,5 @@ import unittest +import warnings import torch @@ -52,7 +53,10 @@ def setUpClass(cls): def test_forward_shapes_with_and_without_graphs(self): for use_graph in (False, True): torch.manual_seed(0) - model = ARMR(self.dataset, embedding_dim=16, use_graph=use_graph) + model = ARMR( + self.dataset, embedding_dim=16, use_graph=use_graph, + graph_dataset=self.dataset, + ) out = model(**self.batch) self.assertEqual(out["y_prob"].shape, (3, 4)) self.assertEqual(out["logit"].shape, (3, 4)) @@ -161,6 +165,27 @@ def test_visit_lengths_count_an_empty_middle_visit(self): self.assertEqual(out["logit"].shape, (2, 2)) self.assertFalse(torch.isnan(out["loss"])) + def test_graph_without_graph_dataset_warns(self): + with self.assertWarnsRegex(UserWarning, "graph_dataset"): + ARMR(self.dataset, embedding_dim=16) + with warnings.catch_warnings(): + warnings.simplefilter("error") + ARMR(self.dataset, embedding_dim=16, graph_dataset=self.dataset) + ARMR(self.dataset, embedding_dim=16, use_graph=False) + + def test_graph_comes_only_from_graph_dataset(self): + vocab = self.dataset.output_processors["drugs"].label_vocab + a, b = vocab["A01A"], vocab["B01A"] + c, n = vocab["C03C"], vocab["N02B"] + # p0 (A01A with B01A) only; p1's C03C with N02B stays out + model = ARMR( + self.dataset, embedding_dim=16, graph_dataset=self.dataset.subset([0]) + ) + self.assertGreater(model.ehr_adj[a, b].item(), 0.0) + self.assertEqual(model.ehr_adj[c, n].item(), 0.0) + full = ARMR(self.dataset, embedding_dim=16, graph_dataset=self.dataset) + self.assertGreater(full.ehr_adj[c, n].item(), 0.0) + def test_decay_parameters_get_a_gradient(self): torch.manual_seed(0) model = ARMR(self.dataset, embedding_dim=16, use_graph=False) diff --git a/tests/core/test_molerec.py b/tests/core/test_molerec.py index d68c120012..5a13ef807c 100644 --- a/tests/core/test_molerec.py +++ b/tests/core/test_molerec.py @@ -5,6 +5,7 @@ from pyhealth.datasets import create_sample_dataset, get_dataloader from pyhealth.models import MoleRec +from pyhealth.models.utils import ddi_adjacency class TestMoleRec(unittest.TestCase): @@ -162,6 +163,28 @@ def test_fallback_predictor_registered_and_trains(self): "fallback predictor was not updated by the optimizer step", ) + def test_generate_ddi_adj_matches_the_shared_helper(self): + """The DDI matrix is the shared ATC-3 one, over the drug labels.""" + samples = [ + {"patient_id": "p0", "visit_id": "v0", + "conditions": [["c1"], ["c2"]], "procedures": [["p1"], ["p2"]], + "drugs": ["N02B", "B01A", "C03C"]}, + {"patient_id": "p1", "visit_id": "v1", + "conditions": [["c3"]], "procedures": [["p3"]], + "drugs": ["N02A", "M01A"]}, + ] + dataset = create_sample_dataset( + samples=samples, input_schema=self.input_schema, + output_schema=self.output_schema, dataset_name="ddi", + ) + model = MoleRec(dataset=dataset) + adj = model.generate_ddi_adj() + vocab = dataset.output_processors["drugs"].label_vocab + self.assertEqual(tuple(adj.shape), (len(vocab), len(vocab))) + self.assertTrue(torch.equal(adj, ddi_adjacency(vocab))) + self.assertTrue(torch.equal(adj, adj.T)) + self.assertGreater(adj.sum().item(), 0) + if __name__ == "__main__": unittest.main() diff --git a/tests/core/test_safedrug.py b/tests/core/test_safedrug.py index 75e278a199..dfd81173d4 100644 --- a/tests/core/test_safedrug.py +++ b/tests/core/test_safedrug.py @@ -3,6 +3,7 @@ from pyhealth.datasets import create_sample_dataset, get_dataloader from pyhealth.models import SafeDrug +from pyhealth.models.utils import ddi_adjacency class TestSafeDrug(unittest.TestCase): @@ -175,6 +176,28 @@ def test_model_device(self): next(model_cuda.parameters()).device.type, "cuda" ) + def test_generate_ddi_adj_matches_the_shared_helper(self): + """The DDI matrix is the shared ATC-3 one, over the drug labels.""" + samples = [ + {"patient_id": "p0", "visit_id": "v0", + "conditions": [["c1"], ["c2"]], "procedures": [["p1"], ["p2"]], + "drugs": ["N02B", "B01A", "C03C"]}, + {"patient_id": "p1", "visit_id": "v1", + "conditions": [["c3"]], "procedures": [["p3"]], + "drugs": ["N02A", "M01A"]}, + ] + dataset = create_sample_dataset( + samples=samples, input_schema=self.input_schema, + output_schema=self.output_schema, dataset_name="ddi", + ) + model = SafeDrug(dataset=dataset) + adj = model.generate_ddi_adj() + vocab = dataset.output_processors["drugs"].label_vocab + self.assertEqual(tuple(adj.shape), (len(vocab), len(vocab))) + self.assertTrue(torch.equal(adj, ddi_adjacency(vocab))) + self.assertTrue(torch.equal(adj, adj.T)) + self.assertGreater(adj.sum().item(), 0) + if __name__ == "__main__": unittest.main() From 3f4689f07ce3dd833fb4cc073937821ae5534ab0 Mon Sep 17 00:00:00 2001 From: solarsys Date: Tue, 3 Nov 2026 07:39:14 -0800 Subject: [PATCH 07/11] ARMR: per-set Eq. 11 softmax; shared co-occurrence graph helper - Eq. 11: the reused-drug attention is a softmax over the drugs the patient took before and the new-drug attention over the drugs never taken (masked softmax; an empty set gives zeros, no NaNs). The paper does not give the axis; the authors' code restricts each branch to its set. Test pins the normalization. - Move the co-occurrence graph into pyhealth.models.utils (ehr_cooccurrence_adjacency, for code lists or multi-hot tensors). ARMR and GAMENet call it. GAMENet still passes only unprocessed samples, so its matrix is unchanged (np.array_equal on mimic3demo and synthetic MIMIC-III, for processed samples and for raw code lists). - Notebook: Colab badge points at the PR branch; Part 1 re-run. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BdtuVKBLhWpYbhTQbaZaTt --- .../armr_mimic3_drug_recommendation.ipynb | 76 +++++++++---------- pyhealth/models/armr.py | 62 +++++++++------ pyhealth/models/gamenet.py | 26 +++---- pyhealth/models/utils.py | 39 ++++++++++ tests/core/test_armr.py | 40 +++++++++- 5 files changed, 164 insertions(+), 79 deletions(-) diff --git a/examples/armr_mimic3_drug_recommendation.ipynb b/examples/armr_mimic3_drug_recommendation.ipynb index 85101eb1e2..29306f73ff 100644 --- a/examples/armr_mimic3_drug_recommendation.ipynb +++ b/examples/armr_mimic3_drug_recommendation.ipynb @@ -7,13 +7,13 @@ "source": [ "# ARMR in PyHealth: medication recommendation on MIMIC-III\n", "\n", - "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/sunlabuiuc/PyHealth/blob/master/examples/armr_mimic3_drug_recommendation.ipynb)\n", + "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/solarsys/PyHealth/blob/feat/armr/examples/armr_mimic3_drug_recommendation.ipynb)\n", "\n", "This notebook runs **ARMR** (Feiyue Wu, Tianxing Wu and Shenqi Jing, *ARMR: Adaptively Responsive Network for Medication Recommendation*, IJCAI 2025, [arXiv:2507.04428](https://arxiv.org/abs/2507.04428)) as implemented in PyHealth (`pyhealth.models.ARMR`), and compares it with PyHealth's GAMENet, SafeDrug and RETAIN on the same task, split and metrics.\n", "\n", "ARMR has three parts:\n", "- **Piecewise temporal learning.** The most recent visits go through a feedforward network and the earlier ones through a Mamba block; the recent states attend over the distant ones.\n", - "- **Adaptively responsive module.** The medication history is split into drugs that were reused and drugs that were new at each visit. Each drug's embedding is weighted by attention over the reused drugs if the patient took it before, and over the new drugs otherwise; a learned, time-decayed score for past use is added to the drug's score.\n", + "- **Adaptively responsive module.** The medication history is split into drugs that were reused and drugs that were new at each visit. Each drug's embedding is weighted by attention over the drugs the patient took before if it is one of them, and over the drugs never taken otherwise; a learned, time-decayed score for past use is added to the drug's score.\n", "- **Joint recommendation.** A direct score from the patient representation is fused with the cosine similarity between the patient and each weighted drug embedding. The loss is 0.7 × BCE + 0.3 × multi-label margin.\n", "\n", "**How to use it.** Part 1 runs end to end on PyHealth's open synthetic MIMIC-III, with no credentials. Part 2 repeats the experiment on real MIMIC-III v1.4: set `MIMIC3_ROOT` to your copy (PhysioNet credentials required) and run it." @@ -35,10 +35,10 @@ "id": "dfbb0f34", "metadata": { "execution": { - "iopub.execute_input": "2026-11-03T13:55:11.396947Z", - "iopub.status.busy": "2026-11-03T13:55:11.396867Z", - "iopub.status.idle": "2026-11-03T13:55:11.401817Z", - "shell.execute_reply": "2026-11-03T13:55:11.401365Z" + "iopub.execute_input": "2026-11-03T15:37:00.887981Z", + "iopub.status.busy": "2026-11-03T15:37:00.887518Z", + "iopub.status.idle": "2026-11-03T15:37:00.900591Z", + "shell.execute_reply": "2026-11-03T15:37:00.899424Z" } }, "outputs": [], @@ -60,10 +60,10 @@ "id": "ef9a1fcf", "metadata": { "execution": { - "iopub.execute_input": "2026-11-03T13:55:11.403157Z", - "iopub.status.busy": "2026-11-03T13:55:11.403081Z", - "iopub.status.idle": "2026-11-03T13:55:16.886787Z", - "shell.execute_reply": "2026-11-03T13:55:16.886305Z" + "iopub.execute_input": "2026-11-03T15:37:00.903702Z", + "iopub.status.busy": "2026-11-03T15:37:00.903455Z", + "iopub.status.idle": "2026-11-03T15:37:05.861164Z", + "shell.execute_reply": "2026-11-03T15:37:05.860718Z" } }, "outputs": [], @@ -164,10 +164,10 @@ "id": "b38a21cf", "metadata": { "execution": { - "iopub.execute_input": "2026-11-03T13:55:16.888827Z", - "iopub.status.busy": "2026-11-03T13:55:16.888525Z", - "iopub.status.idle": "2026-11-03T13:56:59.097336Z", - "shell.execute_reply": "2026-11-03T13:56:59.096844Z" + "iopub.execute_input": "2026-11-03T15:37:05.863069Z", + "iopub.status.busy": "2026-11-03T15:37:05.862784Z", + "iopub.status.idle": "2026-11-03T15:38:59.735066Z", + "shell.execute_reply": "2026-11-03T15:38:59.734372Z" } }, "outputs": [ @@ -208,31 +208,31 @@ " \n", " \n", " ARMR\n", - " 24.44\n", - " 46.35\n", - " 36.31\n", - " 6.81\n", + " 24.48\n", + " 46.57\n", + " 36.35\n", + " 6.66\n", " \n", " \n", " GAMENet\n", - " 30.63\n", - " 56.60\n", - " 44.07\n", - " 8.11\n", + " 30.48\n", + " 56.40\n", + " 43.62\n", + " 8.67\n", " \n", " \n", " SafeDrug\n", - " 31.81\n", - " 54.84\n", - " 45.27\n", - " 6.43\n", + " 29.99\n", + " 54.08\n", + " 43.58\n", + " 6.39\n", " \n", " \n", " RETAIN\n", - " 29.22\n", - " 54.15\n", - " 41.80\n", - " 7.47\n", + " 28.86\n", + " 54.02\n", + " 41.45\n", + " 7.19\n", " \n", " \n", "\n", @@ -240,10 +240,10 @@ ], "text/plain": [ " Jaccard PRAUC F1 DDI rate\n", - "ARMR 24.44 46.35 36.31 6.81\n", - "GAMENet 30.63 56.60 44.07 8.11\n", - "SafeDrug 31.81 54.84 45.27 6.43\n", - "RETAIN 29.22 54.15 41.80 7.47" + "ARMR 24.48 46.57 36.35 6.66\n", + "GAMENet 30.48 56.40 43.62 8.67\n", + "SafeDrug 29.99 54.08 43.58 6.39\n", + "RETAIN 28.86 54.02 41.45 7.19" ] }, "execution_count": 3, @@ -283,10 +283,10 @@ "id": "13e4d4ce", "metadata": { "execution": { - "iopub.execute_input": "2026-11-03T13:56:59.098667Z", - "iopub.status.busy": "2026-11-03T13:56:59.098585Z", - "iopub.status.idle": "2026-11-03T13:56:59.101010Z", - "shell.execute_reply": "2026-11-03T13:56:59.100605Z" + "iopub.execute_input": "2026-11-03T15:38:59.737786Z", + "iopub.status.busy": "2026-11-03T15:38:59.737651Z", + "iopub.status.idle": "2026-11-03T15:38:59.740429Z", + "shell.execute_reply": "2026-11-03T15:38:59.739963Z" } }, "outputs": [ diff --git a/pyhealth/models/armr.py b/pyhealth/models/armr.py index c9fbb1134a..8c94c225ea 100644 --- a/pyhealth/models/armr.py +++ b/pyhealth/models/armr.py @@ -25,7 +25,11 @@ from pyhealth.datasets import SampleDataset from pyhealth.models.base_model import BaseModel from pyhealth.models.embedding import EmbeddingModel -from pyhealth.models.utils import ddi_adjacency, history_to_label_index +from pyhealth.models.utils import ( + ddi_adjacency, + ehr_cooccurrence_adjacency, + history_to_label_index, +) def _reverse_padded(x: torch.Tensor, lengths: torch.Tensor) -> torch.Tensor: @@ -206,7 +210,10 @@ class ARMR(BaseModel): drug's score (Eq. 19) as a recency term. - Eq. 11's attention maps the drug-history attention to a per-feature weight (``W_o`` and ``W_n`` are ``2N -> dim``), so the weighting changes - the direction of a drug's embedding, which cosine similarity sees. + the direction of a drug's embedding, which cosine similarity sees. The + reused-drug softmax is taken over the drugs the patient took before + and the new-drug softmax over the drugs never taken (the paper does not + give the axis; the authors' code restricts each branch to its set). - ``use_graph`` (default ``True``) adds two-layer GCN embeddings of the drug co-occurrence graph and the drug-drug interaction graph to the drug embeddings, with weights 1 and 0.5, as the authors' released code @@ -363,17 +370,8 @@ def _ehr_adj(self, label_vocab: dict, samples) -> torch.Tensor: samples: the samples to read the drug labels from (the training split). """ - adj = torch.zeros(self.label_size, self.label_size) - for sample in samples: - drugs = sample[self.label_key] - if isinstance(drugs, torch.Tensor): # processed: multi-hot - ids = torch.nonzero(drugs.flatten()).flatten() - else: - ids = torch.tensor([label_vocab[c] for c in drugs if c in label_vocab]) - if ids.numel() > 1: - adj[ids.unsqueeze(1), ids.unsqueeze(0)] = 1.0 - adj.fill_diagonal_(0.0) - return adj + drug_sets = (sample[self.label_key] for sample in samples) + return ehr_cooccurrence_adjacency(drug_sets, label_vocab) def _ddi_adj(self, label_vocab: dict) -> torch.Tensor: """Drug-drug interaction graph at ATC level 3 (as GAMENet and SafeDrug).""" @@ -450,17 +448,35 @@ def _responsive_drugs( taken = (history.sum(dim=1) > 0).float() unused = 1.0 - taken # Eq. 10 - # Eq. 11 - scale = math.sqrt(self.embedding_dim) - q_reused = torch.softmax( - self.w_reused(torch.einsum("md,bkd->bmk", emb, h_reused)) / scale, dim=1 - ) - q_new = torch.softmax( - self.w_new(torch.einsum("md,bkd->bmk", emb, h_new)) / scale, dim=1 + # Eq. 11: reused drugs attend over the drugs taken before, new drugs + # over the drugs never taken; the decay goes into the score (forward) + # instead, since the cosine similarity ignores a per-drug scale + q_reused = self._set_attention(emb, h_reused, self.w_reused, taken) + q_new = self._set_attention(emb, h_new, self.w_new, unused) + return emb.unsqueeze(0) * (q_reused + q_new), used + + def _set_attention( + self, emb: torch.Tensor, h: torch.Tensor, proj: nn.Linear, member: torch.Tensor + ) -> torch.Tensor: + """Eq. 11 attention ``q``, normalized over one set of drugs. + + Args: + emb: drug embeddings, [M, dim]. + h: the set's time-sensitive representation, [batch, 2N, dim]. + proj: ``W_o`` or ``W_n``, mapping ``2N -> dim``. + member: 1 for the drugs in the set, else 0, [batch, M]. + + Returns: + Per-feature weights, [batch, M, dim]: a softmax over the drugs of + the set (each feature sums to 1 over them), zero outside the set + and all zero when the set is empty. + """ + logits = proj(torch.einsum("md,bkd->bmk", emb, h)) / math.sqrt( + self.embedding_dim ) - # the decay goes into the score (forward) instead: cosine ignores it here - weight = taken.unsqueeze(-1) * q_reused + unused.unsqueeze(-1) * q_new - return emb.unsqueeze(0) * weight, used + inside = member.unsqueeze(-1) > 0 + logits = logits.masked_fill(~inside, torch.finfo(logits.dtype).min) + return torch.softmax(logits, dim=1) * inside def _loss(self, prob: torch.Tensor, logit: torch.Tensor, y: torch.Tensor): """``alpha * BCE + (1 - alpha) * multi-label margin`` (Eq. 20-22).""" diff --git a/pyhealth/models/gamenet.py b/pyhealth/models/gamenet.py index 360fd37e5b..8673d6b856 100644 --- a/pyhealth/models/gamenet.py +++ b/pyhealth/models/gamenet.py @@ -9,6 +9,7 @@ from pyhealth.models import BaseModel from pyhealth.models.utils import ( ddi_adjacency, + ehr_cooccurrence_adjacency, get_last_visit, history_to_label_index, ) @@ -428,23 +429,14 @@ def __init__( def generate_ehr_adj(self) -> torch.tensor: """Generates the EHR graph adjacency matrix.""" label_vocab = self.dataset.output_processors[self.label_key].label_vocab - label_size = len(label_vocab) - ehr_adj = torch.zeros((label_size, label_size)) - for sample in self.dataset: - curr_drugs = sample["drugs"] - if isinstance(curr_drugs, torch.Tensor): - continue - encoded_drugs = [] - for drug in curr_drugs: - if drug in label_vocab: - encoded_drugs.append(label_vocab[drug]) - for idx1, med1 in enumerate(encoded_drugs): - for idx2, med2 in enumerate(encoded_drugs): - if idx1 >= idx2: - continue - ehr_adj[med1, med2] = 1 - ehr_adj[med2, med1] = 1 - return ehr_adj + # only unprocessed samples (lists of codes) are used, as before; + # processed multi-hot labels were always skipped here + drug_sets = ( + sample["drugs"] + for sample in self.dataset + if not isinstance(sample["drugs"], torch.Tensor) + ) + return ehr_cooccurrence_adjacency(drug_sets, label_vocab) def generate_ddi_adj(self) -> torch.tensor: """Generates the DDI graph adjacency matrix.""" diff --git a/pyhealth/models/utils.py b/pyhealth/models/utils.py index 615a0ef1bc..f2a3b5e22d 100644 --- a/pyhealth/models/utils.py +++ b/pyhealth/models/utils.py @@ -107,6 +107,45 @@ def ddi_adjacency(label_vocab: dict[str, int]) -> torch.Tensor: return adj +def ehr_cooccurrence_adjacency(drug_sets, label_vocab: dict[str, int]) -> torch.Tensor: + """Builds the drug co-occurrence graph: drugs given together in a visit. + + Build it from the training samples only, so that evaluation labels do not + reach the model. Shared by the drug recommendation models (GAMENet, ARMR). + + Args: + drug_sets: an iterable with one entry per visit, either a list of + drug codes or a multi-hot tensor over ``label_vocab`` (as a + processed ``multilabel`` field is). Codes not in ``label_vocab`` + are ignored. + label_vocab: drug code to label index. + + Returns: + Symmetric 0/1 tensor of shape [len(label_vocab), len(label_vocab)] + with an empty diagonal. + + Examples: + >>> vocab = {"A01A": 0, "B01A": 1, "C03C": 2} + >>> ehr_cooccurrence_adjacency( + ... [["A01A", "B01A"], torch.tensor([0.0, 0.0, 1.0])], vocab + ... ).tolist() + [[0.0, 1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 0.0]] + """ + size = len(label_vocab) + adj = torch.zeros((size, size)) + for drugs in drug_sets: + if isinstance(drugs, torch.Tensor): # multi-hot + ids = torch.nonzero(drugs.flatten()).flatten() + else: + ids = torch.tensor( + sorted({label_vocab[c] for c in drugs if c in label_vocab}), + dtype=torch.long, + ) + if ids.numel() > 1: + adj[ids.unsqueeze(1), ids.unsqueeze(0)] = 1.0 + adj.fill_diagonal_(0.0) + return adj + def history_to_label_index( hist_vocab: dict[str, int], label_vocab: dict[str, int] ) -> torch.Tensor: diff --git a/tests/core/test_armr.py b/tests/core/test_armr.py index 57f5135153..f6967e8dd3 100644 --- a/tests/core/test_armr.py +++ b/tests/core/test_armr.py @@ -10,7 +10,11 @@ _reverse_padded, _split_reused_new, ) -from pyhealth.models.utils import ddi_adjacency, history_to_label_index +from pyhealth.models.utils import ( + ddi_adjacency, + ehr_cooccurrence_adjacency, + history_to_label_index, +) SCHEMA = { "conditions": "nested_sequence", @@ -186,6 +190,29 @@ def test_graph_comes_only_from_graph_dataset(self): full = ARMR(self.dataset, embedding_dim=16, graph_dataset=self.dataset) self.assertGreater(full.ehr_adj[c, n].item(), 0.0) + def test_set_attention_is_normalized_within_each_set(self): + torch.manual_seed(0) + model = ARMR(self.dataset, embedding_dim=16, use_graph=False) + emb = model._drug_embeddings() + h = torch.randn(3, 2 * model.n_recent, 16) + # patient 0: drugs 0 and 2 taken; patient 1: all; patient 2: none + taken = torch.tensor( + [[1.0, 0.0, 1.0, 0.0], [1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 0.0]] + ) + for member in (taken, 1.0 - taken): + q = model._set_attention(emb, h, model.w_reused, member) + self.assertEqual(q.shape, (3, 4, 16)) + sums = q.sum(dim=1) # per patient and feature + for b in range(3): + expected = 1.0 if member[b].sum() > 0 else 0.0 + self.assertTrue(torch.allclose(sums[b], torch.full((16,), expected))) + # zero outside the set + self.assertEqual((q * (1 - member).unsqueeze(-1)).abs().sum().item(), 0.0) + # an empty set gives zeros with finite gradients + h.requires_grad_(True) + model._set_attention(emb, h, model.w_new, taken).sum().backward() + self.assertTrue(torch.isfinite(h.grad).all()) + def test_decay_parameters_get_a_gradient(self): torch.manual_seed(0) model = ARMR(self.dataset, embedding_dim=16, use_graph=False) @@ -213,6 +240,17 @@ def test_output_shape_and_padding_independence(self): class TestDrugHelpers(unittest.TestCase): + def test_ehr_cooccurrence_adjacency_from_codes_and_multihot(self): + vocab = {"A01A": 0, "B01A": 1, "C03C": 2, "N02B": 3} + adj = ehr_cooccurrence_adjacency( + [["A01A", "B01A", "A01A", "X99X"], torch.tensor([0.0, 0.0, 1.0, 1.0]), + ["N02B"]], + vocab, + ) + expected = torch.zeros(4, 4) + expected[0, 1] = expected[1, 0] = expected[2, 3] = expected[3, 2] = 1.0 + self.assertTrue(torch.equal(adj, expected)) + def test_history_to_label_index_sends_unknown_codes_to_trash(self): mapping = history_to_label_index( {"": 0, "": 1, "B01A": 2, "X99X": 3}, {"N02B": 0, "B01A": 1} From dde99909bc656444648416d81fcc701e05dfd67b Mon Sep 17 00:00:00 2001 From: solarsys Date: Tue, 3 Nov 2026 07:57:01 -0800 Subject: [PATCH 08/11] ARMR: cite the paper's Table 3; skip network doctests; Trainer test MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Notebook Part 2: the paper's ARMR results are in Table 3 (not Table 2), in %, mean ± std; checked against arXiv:2507.04428. Cite the metric definitions (Section 5.1) and the cohort (Table 2), and drop the unconfirmed "filtered by visit count". - Mark the examples that download the ATC DDI data with `# doctest: +SKIP` (ARMR, ddi_adjacency, SafeDrug; SafeDrug's text is identical to #1374's). - End-to-end test: Trainer trains ARMR for one epoch and evaluates. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BdtuVKBLhWpYbhTQbaZaTt --- examples/armr_mimic3_drug_recommendation.ipynb | 10 ++++++---- pyhealth/models/armr.py | 6 +++--- pyhealth/models/safedrug.py | 4 ++-- pyhealth/models/utils.py | 6 +++--- tests/core/test_armr.py | 16 ++++++++++++++++ 5 files changed, 30 insertions(+), 12 deletions(-) diff --git a/examples/armr_mimic3_drug_recommendation.ipynb b/examples/armr_mimic3_drug_recommendation.ipynb index 29306f73ff..194150a6ed 100644 --- a/examples/armr_mimic3_drug_recommendation.ipynb +++ b/examples/armr_mimic3_drug_recommendation.ipynb @@ -267,14 +267,16 @@ "\n", "Set `MIMIC3_ROOT` to the folder with `ADMISSIONS.csv.gz`, `DIAGNOSES_ICD.csv.gz`, `PROCEDURES_ICD.csv.gz` and `PRESCRIPTIONS.csv.gz` (for example a mounted Google Drive folder).\n", "\n", - "The paper reports, on its MIMIC-III and MIMIC-IV cohorts (Table 2, %):\n", + "The paper reports ARMR's results (mean ± std over runs, in %) in its Table 3 (\"The comparison results on MIMIC-III and MIMIC-IV datasets\"):\n", "\n", "| Dataset | Jaccard | PRAUC | F1 |\n", "|---|---|---|---|\n", - "| MIMIC-III | 54.51 | 79.63 | 69.59 |\n", - "| MIMIC-IV | 51.74 | 76.95 | 67.12 |\n", + "| MIMIC-III | 54.51 ± 0.13 | 79.63 ± 0.28 | 69.59 ± 0.29 |\n", + "| MIMIC-IV | 51.74 ± 0.14 | 76.95 ± 0.21 | 67.12 ± 0.18 |\n", "\n", - "The paper builds its cohort with the Carmen preprocessing pipeline (ATC level 3, 131 drugs, patients filtered by visit count), while PyHealth's `DrugRecommendationMIMIC3` uses its own filtering and drug vocabulary. Expect the same ordering of models, not identical numbers." + "Section 5.1 of the paper defines the metrics: Jaccard is the intersection over the union of the recommended and true drug sets, F1 the harmonic mean of precision and recall, and PRAUC the area under the precision-recall curve, each averaged over the evaluation records. Here they are PyHealth's `jaccard_samples`, `f1_samples` and `pr_auc_samples` (averaged over the test samples, one per visit), shown ×100.\n", + "\n", + "The paper follows the preprocessing of Chen et al. (2023, Carmen): ATC level-3 drugs, 131 of them, with 6,350 MIMIC-III patients (15,032 visits) in its Table 2. PyHealth's `DrugRecommendationMIMIC3` uses its own filtering and drug vocabulary, so expect the same ordering of models, not identical numbers." ] }, { diff --git a/pyhealth/models/armr.py b/pyhealth/models/armr.py index 8c94c225ea..f02834e19f 100644 --- a/pyhealth/models/armr.py +++ b/pyhealth/models/armr.py @@ -265,13 +265,13 @@ class ARMR(BaseModel): ... output_schema={"drugs": "multilabel"}, ... dataset_name="demo", ... ) - >>> model = ARMR(dataset, embedding_dim=16, use_graph=False) + >>> model = ARMR(dataset, embedding_dim=16, use_graph=False) # doctest: +SKIP >>> # with the graphs, give the training split explicitly: >>> # ARMR(dataset, graph_dataset=train_split) >>> from pyhealth.datasets import get_dataloader >>> batch = next(iter(get_dataloader(dataset, batch_size=2))) - >>> out = model(**batch) - >>> sorted(out) + >>> out = model(**batch) # doctest: +SKIP + >>> sorted(out) # doctest: +SKIP ['logit', 'loss', 'y_prob', 'y_true'] """ diff --git a/pyhealth/models/safedrug.py b/pyhealth/models/safedrug.py index 681ffef1ad..b58c1771e8 100644 --- a/pyhealth/models/safedrug.py +++ b/pyhealth/models/safedrug.py @@ -346,9 +346,9 @@ class SafeDrug(BaseModel): ... output_schema={"drugs": "multilabel"}, ... dataset_name="demo", ... ) - >>> model = SafeDrug(dataset) + >>> model = SafeDrug(dataset) # doctest: +SKIP >>> batch = next(iter(get_dataloader(dataset, batch_size=2))) - >>> sorted(model(**batch)) + >>> sorted(model(**batch)) # doctest: +SKIP ['loss', 'y_prob', 'y_true'] """ diff --git a/pyhealth/models/utils.py b/pyhealth/models/utils.py index f2a3b5e22d..ee51be0f10 100644 --- a/pyhealth/models/utils.py +++ b/pyhealth/models/utils.py @@ -89,10 +89,10 @@ def ddi_adjacency(label_vocab: dict[str, int]) -> torch.Tensor: Symmetric 0/1 tensor of shape [len(label_vocab), len(label_vocab)]. Examples: - >>> adj = ddi_adjacency({"N02B": 0, "B01A": 1, "C03C": 2}) - >>> adj.shape + >>> adj = ddi_adjacency({"N02B": 0, "B01A": 1, "C03C": 2}) # doctest: +SKIP + >>> adj.shape # doctest: +SKIP torch.Size([3, 3]) - >>> bool((adj == adj.T).all()) + >>> bool((adj == adj.T).all()) # doctest: +SKIP True """ from pyhealth.medcode import ATC diff --git a/tests/core/test_armr.py b/tests/core/test_armr.py index f6967e8dd3..9d6d113d0a 100644 --- a/tests/core/test_armr.py +++ b/tests/core/test_armr.py @@ -1,3 +1,4 @@ +import math import unittest import warnings @@ -15,6 +16,7 @@ ehr_cooccurrence_adjacency, history_to_label_index, ) +from pyhealth.trainer import Trainer SCHEMA = { "conditions": "nested_sequence", @@ -85,6 +87,20 @@ def test_training_reduces_the_loss(self): first = first if first is not None else loss.item() self.assertLess(loss.item(), first * 0.5) + def test_trainer_trains_and_evaluates(self): + torch.manual_seed(0) + model = ARMR(self.dataset, embedding_dim=16, graph_dataset=self.dataset) + loader = get_dataloader(self.dataset, batch_size=2, shuffle=True) + trainer = Trainer( + model=model, metrics=["jaccard_samples", "f1_samples"], + enable_logging=False, + ) + trainer.train(train_dataloader=loader, epochs=1) + scores = trainer.evaluate(get_dataloader(self.dataset, batch_size=2)) + for key in ("loss", "jaccard_samples", "f1_samples"): + self.assertIn(key, scores) + self.assertTrue(math.isfinite(scores[key])) + def test_inference_without_labels(self): model = ARMR(self.dataset, embedding_dim=16, use_graph=False) model.eval() From 55ab41b9c309b648c6b7100d1ffeb60e9c9098b2 Mon Sep 17 00:00:00 2001 From: solarsys Date: Tue, 3 Nov 2026 08:19:34 -0800 Subject: [PATCH 09/11] ARMR: require graph_dataset when use_graph=True With the drug graphs (the default) and no graph_dataset, ARMR now raises a ValueError asking for the training split as graph_dataset, or use_graph=False, instead of falling back to the full dataset with a warning. Tests, docstring, docs page and notebook note updated. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BdtuVKBLhWpYbhTQbaZaTt --- docs/api/models/pyhealth.models.ARMR.rst | 4 +++ .../armr_mimic3_drug_recommendation.ipynb | 2 +- pyhealth/models/armr.py | 27 +++++++++---------- tests/core/test_armr.py | 9 ++++--- 4 files changed, 24 insertions(+), 18 deletions(-) diff --git a/docs/api/models/pyhealth.models.ARMR.rst b/docs/api/models/pyhealth.models.ARMR.rst index 7cda90e95e..b9dfac0fc4 100644 --- a/docs/api/models/pyhealth.models.ARMR.rst +++ b/docs/api/models/pyhealth.models.ARMR.rst @@ -6,6 +6,10 @@ Recommendation", IJCAI 2025) for the drug-recommendation tasks (:class:`~pyhealth.tasks.DrugRecommendationMIMIC3`, :class:`~pyhealth.tasks.DrugRecommendationMIMIC4`). It needs ``conditions``, ``procedures`` and ``drugs_hist`` in the input schema and predicts ``drugs``. +With the drug graphs (``use_graph=True``, the default) pass the training split +as ``graph_dataset``, for example ``ARMR(train, graph_dataset=train)``, so the +co-occurrence graph never sees evaluation labels; otherwise ARMR raises a +``ValueError``. ``use_graph=False`` needs no ``graph_dataset``. Example notebook: ``examples/armr_mimic3_drug_recommendation.ipynb``. diff --git a/examples/armr_mimic3_drug_recommendation.ipynb b/examples/armr_mimic3_drug_recommendation.ipynb index 194150a6ed..a6f326c040 100644 --- a/examples/armr_mimic3_drug_recommendation.ipynb +++ b/examples/armr_mimic3_drug_recommendation.ipynb @@ -319,7 +319,7 @@ "source": [ "## Notes for reproducing the paper\n", "\n", - "- `ARMR(..., use_graph=True)` (the default) adds GCN embeddings of the drug co-occurrence and drug-drug interaction graphs to the drug embeddings, as the authors' released code does. `use_graph=False` gives the equations exactly as written in the paper. With the graphs, pass the training split as `graph_dataset` so the co-occurrence graph never sees evaluation labels (ARMR warns if it is missing).\n", + "- `ARMR(..., use_graph=True)` (the default) adds GCN embeddings of the drug co-occurrence and drug-drug interaction graphs to the drug embeddings, as the authors' released code does. `use_graph=False` gives the equations exactly as written in the paper. With the graphs, pass the training split as `graph_dataset` so the co-occurrence graph never sees evaluation labels (ARMR raises a `ValueError` if it is missing).\n", "- Three details the paper leaves open, and the choices made: Eq. 9's time decay is one learned scale and rate, added to each drug's score (in Eq. 11 it would only rescale a drug's embedding, which the cosine similarity ignores); Eq. 11's attention gives a weight per embedding feature; the \"recent\" segment is the N visits closest to the prediction.\n", "- Questions or corrections: please open an issue at https://github.com/sunlabuiuc/PyHealth or write on the PyHealth Discord." ] diff --git a/pyhealth/models/armr.py b/pyhealth/models/armr.py index f02834e19f..6ab5116f09 100644 --- a/pyhealth/models/armr.py +++ b/pyhealth/models/armr.py @@ -14,7 +14,6 @@ import math import os -import warnings import numpy as np import torch @@ -240,8 +239,11 @@ class ARMR(BaseModel): embeddings, as the authors' code does. Default is True. graph_dataset: the samples the drug co-occurrence graph is built from; pass the training split, so that validation and test - labels stay out of the model. If ``use_graph`` is True and this is - None, the graph is built from ``dataset`` with a warning. + labels stay out of the model. Required when ``use_graph`` is + True. + + Raises: + ValueError: if ``use_graph`` is True and ``graph_dataset`` is None. Examples: >>> from pyhealth.datasets import create_sample_dataset @@ -266,7 +268,7 @@ class ARMR(BaseModel): ... dataset_name="demo", ... ) >>> model = ARMR(dataset, embedding_dim=16, use_graph=False) # doctest: +SKIP - >>> # with the graphs, give the training split explicitly: + >>> # with the graphs (the default), pass the training split: >>> # ARMR(dataset, graph_dataset=train_split) >>> from pyhealth.datasets import get_dataloader >>> batch = next(iter(get_dataloader(dataset, batch_size=2))) @@ -285,6 +287,13 @@ def __init__( use_graph: bool = True, graph_dataset: SampleDataset | None = None, ): + if use_graph and graph_dataset is None: + raise ValueError( + "ARMR(use_graph=True) builds a drug co-occurrence graph from " + "drug labels: pass the training split as graph_dataset (for " + "example ARMR(dataset, graph_dataset=train)), or set " + "use_graph=False." + ) super().__init__(dataset=dataset) for key in ("conditions", "procedures", "drugs_hist"): if key not in self.dataset.input_schema: @@ -323,16 +332,6 @@ def __init__( ddi_adj = self._ddi_adj(label_vocab) if use_graph: - if graph_dataset is None: - warnings.warn( - "ARMR(use_graph=True) builds its drug co-occurrence graph " - "from the drug labels of every sample in `dataset`. Pass " - "the training split as `graph_dataset` so that validation " - "and test labels do not leak into the model.", - UserWarning, - stacklevel=2, - ) - graph_dataset = self.dataset ehr_adj = self._ehr_adj(label_vocab, graph_dataset) self.register_buffer("ehr_adj", _normalize(ehr_adj)) self.register_buffer("ddi_adj_norm", _normalize(ddi_adj)) diff --git a/tests/core/test_armr.py b/tests/core/test_armr.py index 9d6d113d0a..e3ca773aae 100644 --- a/tests/core/test_armr.py +++ b/tests/core/test_armr.py @@ -185,11 +185,14 @@ def test_visit_lengths_count_an_empty_middle_visit(self): self.assertEqual(out["logit"].shape, (2, 2)) self.assertFalse(torch.isnan(out["loss"])) - def test_graph_without_graph_dataset_warns(self): - with self.assertWarnsRegex(UserWarning, "graph_dataset"): + def test_graph_without_graph_dataset_raises(self): + with self.assertRaisesRegex(ValueError, "graph_dataset"): ARMR(self.dataset, embedding_dim=16) + with self.assertRaisesRegex(ValueError, "use_graph=False"): + ARMR(self.dataset, embedding_dim=16, use_graph=True) + # no error, and no warning, with graph_dataset or without the graphs with warnings.catch_warnings(): - warnings.simplefilter("error") + warnings.simplefilter("error", UserWarning) ARMR(self.dataset, embedding_dim=16, graph_dataset=self.dataset) ARMR(self.dataset, embedding_dim=16, use_graph=False) From 364c3a24dfe72024cb81f3a8514374b18b061d1b Mon Sep 17 00:00:00 2001 From: solarsys Date: Tue, 3 Nov 2026 08:40:13 -0800 Subject: [PATCH 10/11] Share the GCN adjacency normalization between GAMENet and ARMR - New pyhealth.models.utils.gcn_normalize_adjacency (D^-1 (A + I), zero rows stay zero). GAMENet's GCN and ARMR call it; ARMR's _normalize is removed. Normalized adjacencies are bit-identical before and after (torch.equal) for GAMENet's EHR/DDI GCNs and ARMR's buffers on mimic3demo and synthetic MIMIC-III. - Tests: the helper, and MICRON's generate_ddi_adj against ddi_adjacency. - Notebook Part 1: note that GAMENet's co-occurrence graph is all zeros on processed samples, so that comparison is not like-for-like. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BdtuVKBLhWpYbhTQbaZaTt --- .../armr_mimic3_drug_recommendation.ipynb | 2 +- pyhealth/models/armr.py | 11 ++----- pyhealth/models/gamenet.py | 11 ++----- pyhealth/models/utils.py | 29 +++++++++++++++++++ tests/core/test_armr.py | 13 +++++++++ tests/core/test_micron.py | 21 ++++++++++++++ 6 files changed, 70 insertions(+), 17 deletions(-) diff --git a/examples/armr_mimic3_drug_recommendation.ipynb b/examples/armr_mimic3_drug_recommendation.ipynb index a6f326c040..c67ecb372c 100644 --- a/examples/armr_mimic3_drug_recommendation.ipynb +++ b/examples/armr_mimic3_drug_recommendation.ipynb @@ -155,7 +155,7 @@ "source": [ "## Part 1: open synthetic MIMIC-III (no credentials)\n", "\n", - "PyHealth hosts a synthetic MIMIC-III with the real schema. It is useful for checking that everything runs; its scores say nothing about the paper's results. Three epochs take a few minutes on a CPU. That is too short for ARMR, which trains at the authors' learning rate (2e-4, five times lower than the baselines'), so it trails here; the comparison that matters is Part 2's." + "PyHealth hosts a synthetic MIMIC-III with the real schema. It is useful for checking that everything runs; its scores say nothing about the paper's results. Three epochs take a few minutes on a CPU. That is too short for ARMR, which trains at the authors' learning rate (2e-4, five times lower than the baselines'), so it trails here; the comparison that matters is Part 2's. Also, GAMENet's drug co-occurrence graph is all zeros on PyHealth's processed samples (a known GAMENet issue, separate from this notebook), so only its DDI graph is active here and the comparison with GAMENet is not like-for-like." ] }, { diff --git a/pyhealth/models/armr.py b/pyhealth/models/armr.py index 6ab5116f09..014fea27aa 100644 --- a/pyhealth/models/armr.py +++ b/pyhealth/models/armr.py @@ -27,6 +27,7 @@ from pyhealth.models.utils import ( ddi_adjacency, ehr_cooccurrence_adjacency, + gcn_normalize_adjacency, history_to_label_index, ) @@ -333,8 +334,8 @@ def __init__( ddi_adj = self._ddi_adj(label_vocab) if use_graph: ehr_adj = self._ehr_adj(label_vocab, graph_dataset) - self.register_buffer("ehr_adj", _normalize(ehr_adj)) - self.register_buffer("ddi_adj_norm", _normalize(ddi_adj)) + self.register_buffer("ehr_adj", gcn_normalize_adjacency(ehr_adj)) + self.register_buffer("ddi_adj_norm", gcn_normalize_adjacency(ddi_adj)) self.gcn_ehr = nn.ModuleList([nn.Linear(dim, dim), nn.Linear(dim, dim)]) self.gcn_ddi = nn.ModuleList([nn.Linear(dim, dim), nn.Linear(dim, dim)]) # the "ddi" metric (pyhealth.metrics.multilabel) reads this file, as @@ -550,9 +551,3 @@ def _split_reused_new(history: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor seen_before = torch.cumsum(history, dim=1) - history > 0 reused = history * seen_before return reused, history - reused - - -def _normalize(adj: torch.Tensor) -> torch.Tensor: - """Row-normalizes ``adj + I``, as in Kipf and Welling's GCN.""" - adj = adj + torch.eye(adj.size(0)) - return adj / adj.sum(dim=1, keepdim=True) diff --git a/pyhealth/models/gamenet.py b/pyhealth/models/gamenet.py index 8673d6b856..f6a1ed8fd9 100644 --- a/pyhealth/models/gamenet.py +++ b/pyhealth/models/gamenet.py @@ -10,6 +10,7 @@ from pyhealth.models.utils import ( ddi_adjacency, ehr_cooccurrence_adjacency, + gcn_normalize_adjacency, get_last_visit, history_to_label_index, ) @@ -84,8 +85,7 @@ def __init__(self, adj: torch.tensor, hidden_size: int, dropout: float = 0.5): self.dropout = dropout voc_size = adj.shape[0] - adj = adj + torch.eye(adj.shape[0]) - adj = self.normalize(adj) + adj = gcn_normalize_adjacency(adj) self.adj = torch.nn.Parameter(adj, requires_grad=False) self.x = torch.nn.Parameter(torch.eye(voc_size), requires_grad=False) @@ -95,12 +95,7 @@ def __init__(self, adj: torch.tensor, hidden_size: int, dropout: float = 0.5): def normalize(self, mx: torch.tensor) -> torch.tensor: """Normalizes the matrix row-wise.""" - rowsum = mx.sum(1) - r_inv = torch.pow(rowsum, -1).flatten() - r_inv[torch.isinf(r_inv)] = 0.0 - r_mat_inv = torch.diagflat(r_inv) - mx = torch.mm(r_mat_inv, mx) - return mx + return gcn_normalize_adjacency(mx, self_loops=False) def forward(self) -> torch.tensor: """Forward propagation. diff --git a/pyhealth/models/utils.py b/pyhealth/models/utils.py index ee51be0f10..6959fb0089 100644 --- a/pyhealth/models/utils.py +++ b/pyhealth/models/utils.py @@ -146,6 +146,35 @@ def ehr_cooccurrence_adjacency(drug_sets, label_vocab: dict[str, int]) -> torch. adj.fill_diagonal_(0.0) return adj +def gcn_normalize_adjacency(adj: torch.Tensor, self_loops: bool = True) -> torch.Tensor: + """Row-normalizes an adjacency matrix for a GCN (Kipf and Welling). + + Computes ``D^-1 (A + I)``: each row is divided by its sum, after adding + self-loops if ``self_loops``. Rows that sum to zero stay zero. Shared by + GAMENet's GCN and ARMR. + + Args: + adj: adjacency tensor of shape [num_nodes, num_nodes]. + self_loops: add the identity before normalizing. Default is True. + + Returns: + Tensor of the same shape whose non-empty rows sum to 1. + + Examples: + >>> gcn_normalize_adjacency(torch.tensor([[0.0, 1.0], [1.0, 0.0]])) + tensor([[0.5000, 0.5000], + [0.5000, 0.5000]]) + >>> gcn_normalize_adjacency(torch.zeros(2, 2), self_loops=False) + tensor([[0., 0.], + [0., 0.]]) + """ + if self_loops: + adj = adj + torch.eye(adj.size(0), dtype=adj.dtype, device=adj.device) + r_inv = adj.sum(dim=1).pow(-1) + r_inv[torch.isinf(r_inv)] = 0.0 + return r_inv.unsqueeze(1) * adj + + def history_to_label_index( hist_vocab: dict[str, int], label_vocab: dict[str, int] ) -> torch.Tensor: diff --git a/tests/core/test_armr.py b/tests/core/test_armr.py index e3ca773aae..dac58b6e6d 100644 --- a/tests/core/test_armr.py +++ b/tests/core/test_armr.py @@ -14,6 +14,7 @@ from pyhealth.models.utils import ( ddi_adjacency, ehr_cooccurrence_adjacency, + gcn_normalize_adjacency, history_to_label_index, ) from pyhealth.trainer import Trainer @@ -270,6 +271,18 @@ def test_ehr_cooccurrence_adjacency_from_codes_and_multihot(self): expected[0, 1] = expected[1, 0] = expected[2, 3] = expected[3, 2] = 1.0 self.assertTrue(torch.equal(adj, expected)) + def test_gcn_normalize_adjacency_rows_sum_to_one(self): + adj = torch.tensor([[0.0, 1.0, 1.0], [1.0, 0.0, 0.0], [1.0, 0.0, 0.0]]) + norm = gcn_normalize_adjacency(adj) + expected = torch.tensor( + [[1 / 3, 1 / 3, 1 / 3], [0.5, 0.5, 0.0], [0.5, 0.0, 0.5]] + ) + self.assertTrue(torch.allclose(norm, expected)) + self.assertTrue(torch.allclose(norm.sum(dim=1), torch.ones(3))) + # without self-loops, an empty row stays zero (no NaN or inf) + bare = gcn_normalize_adjacency(torch.tensor([[0.0, 2.0], [0.0, 0.0]]), False) + self.assertTrue(torch.equal(bare, torch.tensor([[0.0, 1.0], [0.0, 0.0]]))) + def test_history_to_label_index_sends_unknown_codes_to_trash(self): mapping = history_to_label_index( {"": 0, "": 1, "B01A": 2, "X99X": 3}, {"N02B": 0, "B01A": 1} diff --git a/tests/core/test_micron.py b/tests/core/test_micron.py index 0552a50d34..e5d23746ff 100644 --- a/tests/core/test_micron.py +++ b/tests/core/test_micron.py @@ -6,6 +6,7 @@ from pyhealth.datasets import create_sample_dataset, get_dataloader from pyhealth.models import MICRON +from pyhealth.models.utils import ddi_adjacency from pyhealth.processors.base_processor import FeatureProcessor @@ -238,5 +239,25 @@ def test_reconstruction_loss(self): self.assertTrue(rec_loss >= 0) # non-negative loss + def test_generate_ddi_adj_matches_the_shared_helper(self): + """The DDI matrix is the shared ATC-3 one, over the drug labels.""" + samples = [ + {"patient_id": "p0", "visit_id": "v0", "conditions": ["c1"], + "procedures": ["p1"], "drugs": ["N02B", "B01A", "C03C"]}, + {"patient_id": "p1", "visit_id": "v1", "conditions": ["c2"], + "procedures": ["p2"], "drugs": ["N02A", "M01A"]}, + ] + dataset = create_sample_dataset( + samples=samples, input_schema=self.input_schema, + output_schema=self.output_schema, dataset_name="ddi", + ) + adj = MICRON(dataset=dataset).generate_ddi_adj() + vocab = dataset.output_processors["drugs"].label_vocab + self.assertEqual(tuple(adj.shape), (len(vocab), len(vocab))) + self.assertTrue(torch.equal(adj, ddi_adjacency(vocab))) + self.assertTrue(torch.equal(adj, adj.T)) + self.assertGreater(adj.sum().item(), 0) + + if __name__ == "__main__": unittest.main() \ No newline at end of file From ad3127baa76f81e5931a861a57e4ec27513de8ff Mon Sep 17 00:00:00 2001 From: solarsys Date: Tue, 3 Nov 2026 08:40:45 -0800 Subject: [PATCH 11/11] GAMENet: add a usage example to the GCN docstring Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BdtuVKBLhWpYbhTQbaZaTt --- pyhealth/models/gamenet.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/pyhealth/models/gamenet.py b/pyhealth/models/gamenet.py index f6a1ed8fd9..3f2b248622 100644 --- a/pyhealth/models/gamenet.py +++ b/pyhealth/models/gamenet.py @@ -77,6 +77,16 @@ class GCN(nn.Module): hidden_size: hidden feature size. adj: adjacency tensor of shape [num_nodes, num_nodes]. dropout: dropout rate. Default is 0.5. + + Examples: + >>> from pyhealth.models.gamenet import GCN + >>> gcn = GCN(adj=torch.tensor([[0.0, 1.0], [1.0, 0.0]]), hidden_size=4) + >>> gcn.adj + Parameter containing: + tensor([[0.5000, 0.5000], + [0.5000, 0.5000]]) + >>> gcn().shape + torch.Size([2, 4]) """ def __init__(self, adj: torch.tensor, hidden_size: int, dropout: float = 0.5):