Skip to content

Add ARMR medication recommendation model (IJCAI 2025) - #1371

Merged
solarsys merged 15 commits into
sunlabuiuc:masterfrom
solarsys:feat/armr
Nov 3, 2026
Merged

solarsys merged 15 commits into
sunlabuiuc:masterfrom
solarsys:feat/armr

Conversation

@solarsys

@solarsys solarsys commented Nov 3, 2026 •

Copy link
Copy Markdown
Collaborator

Adds ARMR (Feiyue Wu, Tianxing Wu and Shenqi Jing, ARMR: Adaptively Responsive Network for Medication Recommendation, IJCAI 2025, arXiv:2507.04428) as pyhealth.models.ARMR, for the existing DrugRecommendationMIMIC3 / DrugRecommendationMIMIC4 tasks.

What it adds

  • pyhealth/models/armr.py:
    • PiecewiseTemporalLearning (Eq. 1–4): the most recent visits through a feedforward network, earlier visits through a Mamba block, recent states attending over distant ones.
    • SelectiveSSM: a pure-PyTorch Mamba block with input-dependent step size and B/C (Mamba's selection), unlike the time-invariant ehrmamba.MambaBlock; no mamba_ssm dependency.
    • The adaptively responsive module (Eq. 5–11): reused vs new drugs, each attended over its own set, and time-decayed past use added to the drug's score.
    • The joint direct + cosine-similarity recommendation (Eq. 16–19).
    • The loss 0.7 · BCE + 0.3 · multi-label margin (Eq. 20–22).
    • Inference works without labels.
  • ARMR(..., graph_dataset=train_split) builds the co-occurrence graph from the training split; with use_graph=True (the default) graph_dataset is required, and ARMR raises a ValueError without it.
  • Shared helpers in pyhealth/models/utils.py: ddi_adjacency (now used by GAMENet, SafeDrug, MICRON, MoleRec and ARMR), history_to_label_index, ehr_cooccurrence_adjacency and gcn_normalize_adjacency (GAMENet and ARMR).
  • Docs page and toctree entry; ARMR exported from pyhealth.models.
  • tests/core/test_armr.py (18 tests): shapes with and without graphs, finite gradients, the loss falling in training, a Trainer train-and-evaluate run, inference without labels, the loss formula, the reused/new split, per-set attention normalization, the decay reaching the score, visit lengths with an empty middle visit, the graph_dataset error and split, PTL padding invariance, and the shared helpers. SafeDrug, MICRON and MoleRec tests check generate_ddi_adj against ddi_adjacency.
  • examples/armr_mimic3_drug_recommendation.ipynb, a Colab notebook:
    • Part 1 compares ARMR with GAMENet, SafeDrug and RETAIN on PyHealth's open synthetic MIMIC-III, with no credentials. It was executed end to end; its outputs are trimmed to the results.
    • Part 2 repeats the comparison on MIMIC-III v1.4 once MIMIC3_ROOT is set, next to the paper's Table 3 numbers.

Implementation notes

  • Clean reimplementation. The model was written from the paper's equations. The authors' repository (seucoin/armr2) has no license, so no code was copied. It was read only to settle details the paper leaves open, and its shipped MIMIC-derived records were not used.
  • Choices where the paper is open (all in the class docstring):
    • Eq. 9 uses one learned decay scale and rate over the visits in which each drug was given.
    • Eq. 9's decayed use is added to each drug's score; inside Eq. 11 it would only rescale the drug's embedding, which the cosine similarity ignores.
    • Eq. 11's attention gives a per-feature weight, normalized over the reused set and over the new set separately.
    • The "recent" segment is the N visits closest to the prediction, as in the authors' code.
  • use_graph (default True) adds GCN embeddings of the drug co-occurrence and DDI graphs, as the authors' code does. False follows the paper's equations exactly.

Reproduction status

  • Synthetic data (3 epochs): all four models train. ARMR trails here (Jaccard 24.48 vs 28.86–30.48) because it uses the authors' learning rate of 2e-4 and 3 epochs undertrain it. These are not paper-comparable numbers.
  • Real MIMIC-III: not run yet; it needs credentials.
  • Expected agreement: the paper's cohort comes from the Carmen pipeline, which differs from PyHealth's task preprocessing. Expect the same ordering of models, not identical numbers.
  • Next step: run Part 2 on MIMIC-III and share the notebook with the authors to check.

Colab: https://colab.research.google.com/github/solarsys/PyHealth/blob/feat/armr/examples/armr_mimic3_drug_recommendation.ipynb

Behaviour notes for GAMENet

  • The shared ehr_cooccurrence_adjacency keeps the diagonal at zero. GAMENet's old loop could set a diagonal entry when a drug appeared twice in one visit's raw label list.
  • GAMENet's co-occurrence graph is all zeros on processed samples, because its loop skips multi-hot tensors and PyHealth 2.x samples are always processed. This predates this PR and is left unchanged here (fixing it would also raise the train-split question for GAMENet); its matrix was checked identical before and after the refactor.

Also found

  • Shared DDI file race. Every drug-recommendation model saves its DDI matrix to the same ~/.cache/pyhealth/ddi_adj.npy, and the ddi metric reads it back. Two runs at once (e.g. tests alongside a notebook) overwrite each other's matrix, and evaluation fails with an IndexError. The notebook therefore computes the DDI rate from its own matrix. This is fixed separately in Fix the shared ddi_adj.npy cache race in the "ddi" metric #1374.

🤖 Generated with Claude Code

https://claude.ai/code/session_01BdtuVKBLhWpYbhTQbaZaTt

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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BdtuVKBLhWpYbhTQbaZaTt
@solarsys solarsys added the status: automatic The PR will go through automatic review process. label Nov 3, 2026
@solarsys

solarsys commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

/review

@github-actions

github-actions Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Test Coverage

Total: 76.91% (23512 / 30571 lines)

Modified file Coverage Lines
pyhealth/models/__init__.py 100.00% 60 / 60
pyhealth/models/armr.py 98.07% 203 / 207
pyhealth/models/gamenet.py 93.90% 154 / 164
pyhealth/models/micron.py 83.33% 120 / 144
pyhealth/models/molerec.py 65.93% 240 / 364
pyhealth/models/safedrug.py 85.49% 271 / 317
pyhealth/models/utils.py 92.19% 59 / 64

Workflow run · ad3127b

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

Reviewed commit 7090d8c

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

AI Review

suggestion: need change
decision: need change

Thank you for contributing ARMR. It adds a new medication-recommendation model with piecewise temporal learning, an adaptively responsive module and a joint loss. It also adds docs, tests and a comparison notebook. The test file is clear, and coverage of armr.py is 96.3%, above the 80% bar. Whole-repository coverage is 75.7%, above the 60% bar.

To get this merged:

  1. The learned time decay (Eq. 9) has no effect on the output. In _responsive_drugs, used (which contains decay_scale and decay_rate) is a scalar per drug. It only multiplies that drug's embedding vector, and the model then scores drugs with F.cosine_similarity. Cosine similarity ignores a per-vector scale. For a drug the patient has taken, unused is 0, so used is only a rescaling. As a result decay_scale and decay_rate get essentially no gradient. Please feed the decay into something cosine similarity can see, for example by adding it to the per-feature attention logits or using it as a per-drug bias on the score. Alternatively, document that it is inert and drop it. Please also add a test that checks the decay parameters receive a non-zero gradient.
  2. Duplicated helpers. _ddi_adj and _hist_vocab_map closely mirror the existing GAMENet helpers (generate_ddi_adj and _build_drug_hist_vocab_map). SelectiveSSM reimplements the Mamba block already in ehrmamba.py. Please reuse the existing code, or state in the PR why a separate version is needed (for example, no dependency on mamba_ssm).
  3. Possible leakage in the co-occurrence graph. _ehr_adj builds the graph from every sample in the dataset you pass in. The notebook passes the full dataset to every model, so test-patient labels shape the graph. Please build the graph from the training split only, or pass the training split to the model. The Part 1 comparison depends on this.
  4. The reused/new test doesn't test the model code. test_drug_history_splits_reused_and_new_drugs recomputes the split with its own formula. It should call _responsive_drugs, or a factored-out helper, so it would catch problem 1.

Optional suggestions:

  • Install the notebook from the upstream repo rather than a personal fork branch.
  • Don't state the "about an hour" runtime for Part 2 until you have run it.
  • The constructor writes to the shared ddi_adj.npy cache. You have already flagged this race, so a follow-up fix is fine.

Reviewed commit 7090d8c

solarsys and others added 3 commits November 3, 2026 05:55
- 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BdtuVKBLhWpYbhTQbaZaTt
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BdtuVKBLhWpYbhTQbaZaTt
- 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BdtuVKBLhWpYbhTQbaZaTt
@solarsys

solarsys commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks for the review. Changes are in ecd70c7, 27012ac and 6bf16ad.

Time decay had no effect (fixed). Agreed: the decayed use only rescaled each drug's embedding, and the cosine similarity ignores that. Eq. 11 now uses the past-use indicator to choose between the reused and new attention, and the decayed use (Eq. 9) is added to each drug's score in Eq. 19 as a recency term. The class docstring lists this as a choice where the paper is open. New tests check that decay_scale and decay_rate get a non-zero gradient, and that the recency term is zero for drugs never taken and larger for more recent use.

Duplicated helpers (fixed for the two named; SSM kept with a reason). The DDI graph and the drugs_hist-to-label index map are now ddi_adjacency and history_to_label_index in pyhealth/models/utils.py, with examples and tests. GAMENet and ARMR both call them. I left SafeDrug, MICRON and MoleRec's copies for a follow-up to keep this PR focused. SelectiveSSM stays: ehrmamba.MambaBlock uses fixed per-channel step size and B/C (a time-invariant SSM computed as a convolution), while Mamba's selection mechanism, which ARMR's Eq. 2 uses, computes them from each input step. The docstring now says this.

Co-occurrence graph leakage (fixed in the notebook, documented in the model). The notebook now builds every model from the training split (make(train)), which also fixes the same issue for GAMENet in the comparison. The dataset argument and _ehr_adj docstrings say to pass the training split. Part 1 was re-run. ARMR still trails at three epochs, as the text says.

Reused/new test (fixed). The split is factored into _split_reused_new, which _responsive_drugs calls. The test checks that helper's output, and a separate test calls _responsive_drugs directly.

Optional points. The Colab cell now installs from the upstream PR ref (sunlabuiuc/PyHealth@refs/pull/1371/head). The unmeasured Part 2 runtime is removed. I didn't change the shared ddi_adj.npy write, because ddi_score reads that file and every drug model writes it. Changing it needs a metric API change, which is better as a separate PR.

Local results: the test_armr, test_gamenet, test_safedrug, test_micron and test_molerec tests pass, and tools/check_pr_rules.py passes.

@solarsys

solarsys commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

/review

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

Reviewed commit 6bf16ad

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

AI Review

suggestion: need change
decision: need change

Thank you for contributing ARMR. It adds a pure-PyTorch implementation of the IJCAI 2025 model, with a selective-SSM block, piecewise temporal learning and the adaptively responsive module. It also comes with docs, a notebook and tests. The code is well documented, and the choices where the paper is open are stated clearly. The shared ddi_adjacency and history_to_label_index helpers are additive, and the GAMENet refactor looks behaviour-preserving.

Coverage meets the bar. armr.py is at 97.1%, gamenet.py at 89.7%, utils.py at 89.4% and __init__.py at 100%. The whole repository is at 75.7%, above the 60% guideline.

To get this merged:

  • The new ddi_adjacency helper in pyhealth/models/utils.py duplicates DDI-matrix construction that is still inlined in SafeDrug (safedrug.py ~L436), MoleRec (molerec.py ~L678) and MICRON (micron.py ~L353). Please either switch those models to the shared helper, so there is one implementation, or explain why they should keep their own. Check that the resulting matrices are identical.

Optional suggestions:

  • ARMR's constructor writes to the shared ddi_adj.npy cache. You already flag the race this causes as a separate fix, so this is fine for now. Check whether ARMR needs to write that file at all, since it keeps ddi_adj_norm as a buffer.
  • _visit_lengths counts visits that have at least one code. If an empty visit sits in the middle of a sequence, the count will be too low. The shipped tasks filter such visits, but a short comment or a check would help.
  • When the PR merges, update the notebook's install cell, which currently points at the PR ref, and the Colab badge.
  • The real MIMIC-III run is still pending. You state this clearly, so it is not blocking. Sharing the Part 2 results when you have them would be valuable.

Reviewed commit 6bf16ad

…sit 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BdtuVKBLhWpYbhTQbaZaTt
@solarsys

solarsys commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

Follow-up to the re-review, in 9aba5ef.

One DDI implementation (done). SafeDrug, MICRON and MoleRec's generate_ddi_adj now call pyhealth.models.utils.ddi_adjacency, as GAMENet and ARMR already do. Before switching, I compared each model's old matrix with the helper's (np.array_equal). I used the mimic3demo test data (132 drugs, 920 non-zero entries) and synthetic MIMIC-III (178 drugs, 1221 non-zero entries), on the full sample set and the training split. All of them were identical, including dtype (float32) and shape. MICRON sized its matrix with label_processor.size() and MoleRec with self.label_size, but both equal len(label_vocab) for the multilabel drug labels. The ddi_adj.npy writes in those models are unchanged. Because the SafeDrug class was modified, the PR rules required a >>> example in its docstring, so I added one.

ARMR's ddi_adj.npy (kept, now always written). The ddi metric in pyhealth/metrics/multilabel.py reads that file during evaluation, so ARMR has to write it. Before, it wrote the file only with use_graph=True. It now writes it either way, so that metric also works with use_graph=False.

Visit lengths (fixed). An empty visit is encoded as all padding, so counting non-empty visits undercounted a patient with an empty visit in the middle. That shifted the "last visit" and dropped drug history. _visit_lengths now uses the position of the last non-empty visit. A new test covers an empty middle visit.

The install cell and badge stay as they are until merge. The ARMR, GAMENet, SafeDrug, MICRON and MoleRec test modules pass when run one at a time, and tools/check_pr_rules.py passes.

@solarsys

solarsys commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

/review

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

Reviewed commit 9aba5ef

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

AI Review

suggestion: need change
decision: need change

Thank you for this contribution. ARMR is a well-documented addition for the drug-recommendation tasks. It comes with a pure-PyTorch selective SSM, a notebook, and a shared ddi_adjacency / history_to_label_index helper that removes duplicated code across GAMENet, SafeDrug, MICRON and MoleRec. The model file has 97.6% coverage and the tests look thoughtful. You are close.

To get this merged:

  1. Label leakage in the default configuration. With use_graph=True (the default), _ehr_adj builds the drug co-occurrence graph from every sample of the dataset passed in. Many PyHealth examples pass the full dataset to models, so test labels can end up in a GCN input and inflate metrics without any warning. The docstring warns about this, but the default does not guard against it. Please make this safe, for example by building the graph only from an explicit training split argument, by warning when the dataset looks unsplit, or by defaulting use_graph to False.
  2. Coverage of modified files. molerec.py (62.6%) and safedrug.py (68.5%) are below the 80% per-file guideline. Most of the uncovered code is not code you changed. Please add a small test, or point to an existing one, that exercises the refactored generate_ddi_adj in those two models. That would show the refactor is behaviour-preserving and bring the touched code under test. Overall repository coverage (75.7%) meets the 60% bar.

Optional suggestions:

  • The * self.label_size factor in _responsive_drugs has no effect, because the cosine similarity is scale-invariant. Consider removing it.
  • Every ARMR construction writes the shared ddi_adj.npy cache, which is the race you already flagged. A follow-up fix would help.
  • The notebook installs from refs/pull/1371/head. Remember to switch that to a release or master after merging. The description's Colab link also points to a fork.
  • The refactor of four existing models is behaviour-preserving as far as I can tell. Consider whether it belongs in a separate PR to keep this one focused.

Reviewed commit 9aba5ef

- 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BdtuVKBLhWpYbhTQbaZaTt
@solarsys

solarsys commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

Follow-up to the third review, in 787c221.

Label leakage with use_graph=True (fixed). ARMR now takes graph_dataset, the samples its drug co-occurrence graph is built from. If use_graph is True and graph_dataset is not given, ARMR falls back to dataset and raises a UserWarning saying that the training split should be passed. The notebook passes the training split explicitly, and the docstring and the notebook notes describe the argument. New tests check three things: the warning appears when the argument is missing, no warning appears when it is given or when use_graph=False, and an edge that exists only in a sample outside graph_dataset stays out of the graph. GAMENet is unchanged. The notebook results don't change, because the models were already built from the training split.

Coverage of the refactored DDI code (added). test_safedrug.py and test_molerec.py each gain a test that builds the model on ATC-3 drug labels with known interactions. Each test checks that generate_ddi_adj() equals ddi_adjacency(label_vocab) and that the matrix has the expected shape, is symmetric and is non-empty. The MoleRec test sits inside the existing class, so it uses the same ogb skip guard; it runs in my environment.

* self.label_size (removed). The weighted drug embeddings go only into F.cosine_similarity, so a constant positive factor has no effect. It is not used as a softmax temperature or anywhere else.

Not changed, as explained before. The SafeDrug, MICRON and MoleRec refactor was what the previous review asked for. The shared ddi_adj.npy write is still needed because the ddi metric reads that file. The install cell and badge stay until merge.

The test_armr (14), test_safedrug (7) and test_molerec (8) modules pass when run one at a time, and tools/check_pr_rules.py passes. The branch merges cleanly with the current master.

@solarsys

solarsys commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

/review

@solarsys

solarsys commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

Merged master (now including #1373) into this branch. CI's contribution-rules check was comparing against the new master and flagging untouched lines in __init__.py; with master merged in, the check passes locally. No conflicts.

@solarsys

solarsys commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

/review

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

Reviewed commit 22723b9

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

AI Review

suggestion: need change
decision: need change

Thank you for this contribution. ARMR is a well-documented addition. It comes with a pure-PyTorch selective SSM, a docs page, a notebook, and a refactor that moves the shared ATC-3 DDI and history-index helpers into pyhealth/models/utils.py. The change looks self-contained, so I don't see a reason for a maintainer to be pulled in.

To get this merged:

  1. Eq. 11 attention normalization (armr.py, _responsive_drugs). Both torch.softmax(..., dim=1) calls normalize over all M drugs. The description and notebook say a drug is weighted by attention over the reused drugs if the patient took it before, and over the new drugs otherwise. Please do one of two things:
    • Make the normalization match that description, for example by masking the softmax to the reused or new drugs.
    • If softmax over all drugs is intended, say so explicitly in the docstring and notebook, and add a test that pins the behavior.
  2. Duplicated co-occurrence graph code. ARMR._ehr_adj reimplements GAMENet.generate_ehr_adj. Please share one implementation, as you already did for ddi_adjacency and history_to_label_index, rather than adding a second copy.

Optional suggestions:

  • The notebook's Colab badge points to master, which doesn't have ARMR until the PR is merged. Point it at the PR branch for now, or change it after merging.
  • Add a test for the attention normalization, since none of the current tests check it.
  • Part 2 of the notebook (real MIMIC-III) hasn't been run yet. It would be good to add those results once you have credentials.

Coverage:

  • The whole repository is at 76.17%, above the 60% bar.
  • armr.py is at 97.7%.
  • utils.py (89.4%), gamenet.py (89.7%), safedrug.py (85.5%) and micron.py (83.3%) are also above the 80% bar.
  • molerec.py is at 65.9%, which is below the bar. The shortfall is mostly in existing code. Your added DDI test covers the lines you changed.

Reviewed commit 22723b9

- 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BdtuVKBLhWpYbhTQbaZaTt
@solarsys

solarsys commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

Follow-up to the review of 22723b9, in 3f4689f.

Eq. 11 normalization (fixed). The paper defines q_o and q_n as softmaxes but does not say which axis they normalize over. The authors' released code limits each branch to its own set: it scores the reused branch only against drugs the patient took before, and the new branch only against drugs never taken. The code now matches that. _set_attention computes a masked softmax over the drugs in one set, with each feature summing to 1 over that set. Weights outside the set are zero. An empty set gives all zeros, with finite gradients and no NaNs. The class docstring records this choice. A new test checks all of this, including a patient who has taken every drug and one who has taken none. I re-ran Part 1 of the notebook. ARMR is about the same as before (Jaccard 24.48, PRAUC 46.57, F1 36.35) and still trails at three epochs, as the text says.

Co-occurrence graph duplicated GAMENet (fixed). The graph is now built in one place, ehr_cooccurrence_adjacency(drug_sets, label_vocab) in pyhealth/models/utils.py, with a >>> example and a test. Each entry it accepts can be a list of codes or a multi-hot tensor. ARMR and GAMENet both call it.

GAMENet's old loop skipped processed (tensor) labels. PyHealth 2.x samples are processed, so GAMENet's co-occurrence graph is in practice all zeros. To keep GAMENet's behaviour unchanged in this PR, it still passes only unprocessed samples to the helper. I compared GAMENet's matrix before and after the change with np.array_equal on mimic3demo and synthetic MIMIC-III. It is identical on the normal processed path (all zeros) and on the raw code-list path (13,578 and 25,596 non-zero entries). The one exception is a raw label list that repeats a code: the old loop then set a diagonal entry, while the helper keeps the diagonal at zero. GAMENet's empty graph looks like a bug worth its own issue, but fixing it would also bring the leakage question to GAMENet, so I left it out of this PR.

Optional. The Colab badge now points to the PR branch until merge.

The ARMR, GAMENet, SafeDrug, MICRON and MoleRec test modules pass when run one at a time, and tools/check_pr_rules.py passes. The branch merges cleanly with master. I didn't touch the np.save lines that #1374 changes.

@solarsys

solarsys commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

/review

solarsys and others added 2 commits November 3, 2026 07:55
- 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 sunlabuiuc#1374's).
- End-to-end test: Trainer trains ARMR for one epoch and evaluates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BdtuVKBLhWpYbhTQbaZaTt
@solarsys

solarsys commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

Follow-up to the review of 3f4689f, in dde9990. Before making these changes I merged master (including HeartLang, #1372) into the branch; there were no conflicts.

Paper numbers (checked against arXiv:2507.04428 and corrected). The values are right, but they come from Table 3 ("The comparison results on MIMIC-III and MIMIC-IV datasets"), not Table 2, which holds the dataset statistics. Table 3 reports percentages, as mean ± std. For ARMR on MIMIC-III it gives Jaccard 54.51 ± 0.13, PRAUC 79.63 ± 0.28 and F1 69.59 ± 0.29. On MIMIC-IV it gives 51.74 ± 0.14, 76.95 ± 0.21 and 67.12 ± 0.18. The notebook now:

  • cites Table 3 with the standard deviations;
  • gives the paper's metric definitions from Section 5.1 and maps them to PyHealth's jaccard_samples, f1_samples and pr_auc_samples, shown ×100;
  • gives the cohort from Table 2: Carmen preprocessing, 131 ATC level-3 drugs, 6,350 MIMIC-III patients.

I removed "patients filtered by visit count", because I couldn't confirm it from the paper.

Doctests. The examples that download the ATC DDI data are now marked # doctest: +SKIP. These are the ARMR model example, the ddi_adjacency example and the SafeDrug example. The SafeDrug text is identical to #1374's, and git merge-tree shows no conflict with that branch.

Trainer test. A new test trains ARMR for one epoch with Trainer, evaluates it and checks that the loss, Jaccard and F1 are finite.

PR description. It now says that the shared co-occurrence helper keeps GAMENet's diagonal at zero. Before, a drug repeated within one visit could set it. It also says that GAMENet's co-occurrence graph is all zeros on processed samples, which predates this PR and is out of scope here. The synthetic Jaccard is updated to match the notebook (ARMR 24.48 vs 28.86–30.48), along with the other stale details.

use_graph default (unchanged). use_graph=True stays the default. The authors' released model uses the graphs, and changing the default would change the model the paper reports. Leakage is handled by graph_dataset, and ARMR warns when that argument is missing.

The ARMR, GAMENet, SafeDrug, MICRON, MoleRec and HeartLang test modules pass when run one at a time, and tools/check_pr_rules.py passes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BdtuVKBLhWpYbhTQbaZaTt
@solarsys solarsys added status: automatic The PR will go through automatic review process. and removed status: manual Pending maintainer's review labels Nov 3, 2026
@solarsys

solarsys commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

Merged master again (now including #1369). No conflicts; core.test_armr and core.test_llm_ehr_encoder pass. Relabelling as automatic for a review of the changes in the comment above.

@solarsys

solarsys commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

/review

@solarsys

solarsys commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

Merged master again (now including #1369). No conflicts; core.test_armr and core.test_llm_ehr_encoder pass. Relabelling as automatic for a review of the changes in the comment above.

@solarsys

solarsys commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

/review

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

Reviewed commit bf56c27

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

AI Review

suggestion: need change
decision: need change

Thank you for this contribution. It adds ARMR as a new drug-recommendation model with a pure-PyTorch selective SSM. It also moves the DDI and co-occurrence graph builders into shared helpers, and it comes with 17 tests and a notebook. The model logic reads correctly and the write-up is clear. The PR is close, with one thing to fix.

Coverage is fine. The total is 76.67%, above the 60% bar. armr.py is at 98.11%, and gamenet, micron, safedrug and utils are all above 80%. molerec.py is at 65.93%, but your change to it is a small refactor, so that gap isn't something this PR needs to close.

To get this merged:

  • Make the default path safe against label leakage. With the default use_graph=True and no graph_dataset, ARMR builds the drug co-occurrence graph from every sample in dataset (armr.py, in __init__). In the usual workflow of building the model on the full dataset and then splitting, validation and test drug labels reach the model, which can silently inflate test metrics. A UserWarning alone is easy to miss. Please require graph_dataset when use_graph=True, raising a clear error if it is missing. Alternatively, default to a path that doesn't read labels. Update the test test_graph_without_graph_dataset_warns to match.

Optional suggestions:

  • ARMR rewrites the shared ddi_adj.npy cache on every construction. You already track the race in #1374, so this is fine for now.
  • The notebook's Colab badge and pip install point at a fork branch and a PR ref. Switch them to master or PyPI once merged.
  • Once you have run Part 2 on real MIMIC-III, adding those numbers would help readers judge the reproduction.

Reviewed commit bf56c27

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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BdtuVKBLhWpYbhTQbaZaTt
@solarsys

solarsys commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

Follow-up to the review of bf56c27, in 55ab41b.

Missing graph_dataset is now an error. If use_graph=True and no graph_dataset is given, ARMR raises a ValueError asking for the training split as graph_dataset (for example ARMR(dataset, graph_dataset=train)) or for use_graph=False. It no longer falls back to the full dataset with a warning. The check runs before any other work in the constructor. use_graph=True stays the default. Callers I checked with a repository search for ARMR(:

  • Tests: test_graph_without_graph_dataset_warns is now test_graph_without_graph_dataset_raises. It expects the error and checks that neither graph_dataset=... nor use_graph=False errors or warns. Every other test, including the Trainer test, already passed graph_dataset or use_graph=False.
  • Notebook: it already passed graph_dataset, and its note now says ARMR raises.
  • Docs: the class docstring documents the Raises, and the docs page says graph_dataset is required with the graphs. The >>> example uses use_graph=False, so it needs no change.
  • PR description: updated.

The ARMR, GAMENet, SafeDrug, MICRON and MoleRec test modules pass when run one at a time, and tools/check_pr_rules.py passes. The branch still has no conflict with #1374.

@solarsys

solarsys commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

/review

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

Reviewed commit 55ab41b

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

AI Review

suggestion: need change
decision: need change

Thank you for this contribution. It adds ARMR as pyhealth.models.ARMR, with a pure-PyTorch selective SSM, shared DDI, co-occurrence and history-mapping helpers, docs, a notebook and 17 tests. The model looks carefully built, and you've described the choices you made where the paper is open. Your 17 tests cover shapes, gradients, the loss formula, the graph_dataset split and padding. Coverage is good: armr.py is at 98.1%, and utils.py, gamenet.py, micron.py and safedrug.py are above 80%. molerec.py shows 65.93%, but that is mostly existing code. Whole-repo coverage is 76.67%, above the 60% bar.

To get this merged:

  • _normalize at the end of armr.py repeats the adj + I row normalization already in GAMENet's GCN (gamenet.py, around lines 87-103). Please move it into a shared helper in pyhealth/models/utils.py and use it from both places, or explain why they must differ. It is a small change, and it matches how you already shared the DDI and co-occurrence helpers.

Optional suggestions:

  • Add a direct test for MICRON's generate_ddi_adj, as you did for SafeDrug and MoleRec, since its refactor is currently untested.
  • The notebook's Colab badge and install cell point at a personal fork and a PR ref. Switch them to the main repo once the PR is merged.
  • ARMR's constructor writes the shared ~/.cache/pyhealth/ddi_adj.npy. I understand #1374 addresses that race.
  • The Part 1 results are not like-for-like, because GAMENet's co-occurrence graph is all zeros on processed samples. You note this already, and a short remark next to the table would help readers.

Reviewed commit 55ab41b

solarsys and others added 3 commits November 3, 2026 08:37
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BdtuVKBLhWpYbhTQbaZaTt
- 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BdtuVKBLhWpYbhTQbaZaTt
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BdtuVKBLhWpYbhTQbaZaTt
@solarsys

solarsys commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

Follow-up to the review of 55ab41b, in ad3127b. Before making these changes I merged master (including TrajSurv, #1368) into the branch; there were no conflicts.

Duplicated GCN normalization (fixed). The normalization now lives in one helper, gcn_normalize_adjacency(adj, self_loops=True) in pyhealth/models/utils.py. It computes D^-1 (A + I), and rows that sum to zero stay zero. It has a >>> example and a test. GAMENet's GCN uses it, and its normalize method now calls it with self_loops=False. ARMR uses it too, and its private _normalize is gone.

The two implementations did not actually differ. Both are row normalization of A + I, in float32. They differ only in how the arithmetic is written: GAMENet multiplies by the reciprocal through a diagonal matrix, and ARMR divided by the row sum. On the test data they were already bit-identical. I checked with torch.equal on mimic3demo and synthetic MIMIC-III that the matrices are bit-identical before and after the change:

  • GAMENet's EHR and DDI GCN adjacencies;
  • GAMENet's GCN applied to a non-empty co-occurrence graph (its own EHR graph is empty on processed samples);
  • ARMR's ehr_adj and ddi_adj_norm buffers.

The PR rules wanted a >>> example for the modified GAMENet GCN class, so I added one. The new helper sits away from #1374's additions to utils.py, and git merge-tree against that branch is clean.

Optional points (done). A MICRON test now checks generate_ddi_adj against ddi_adjacency, as SafeDrug and MoleRec already do. Part 1 of the notebook now notes that GAMENet's co-occurrence graph is all zeros on processed samples, so the comparison with GAMENet isn't like-for-like. That was a text-only edit; the outputs are unchanged.

The ARMR (18), GAMENet, MICRON (10), SafeDrug and MoleRec test modules pass when run one at a time, and tools/check_pr_rules.py passes.

@solarsys

solarsys commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

/review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed commit ad3127b

>>> 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],

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] GCN docstring example shows the wrong Parameter repr

The new >>> gcn.adj example expects tensor([[0.5000, 0.5000],\n [0.5000, 0.5000]]). A Parameter with requires_grad=False prints Parameter containing: followed by tensor([[0.5000, 0.5000],\n [0.5000, 0.5000]], requires_grad=False), so the example does not match real output. Fix the expected output to include requires_grad=False, or mark the example # doctest: +SKIP as the other examples in the PR do.

"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/solarsys/PyHealth/blob/feat/armr/examples/armr_mimic3_drug_recommendation.ipynb)\n",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] Colab badge and install cell point at different repositories

The badge links to solarsys/PyHealth on branch feat/armr, but the setup cell installs git+https://github.com/sunlabuiuc/PyHealth@​refs/pull/1371/head. Users who click the badge may run a different copy of the code than the one the setup cell installs. Point both at the same repository, for example the sunlabuiuc PR ref or the merged branch once this lands.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI Review

suggestion: approve
decision: approve

Thank you for adding ARMR (IJCAI 2025) as pyhealth.models.ARMR, with a pure-PyTorch selective SSM and shared DDI, co-occurrence, GCN-normalization and history-mapping helpers that GAMENet, SafeDrug, MICRON and MoleRec now use.

The change looks ready to merge. The model follows the paper's equations, graph_dataset is handled as you describe (including the ValueError when it is missing), and the refactors of the existing models keep their outputs the same, apart from the GAMENet diagonal change you documented. SelectiveSSM is distinct from ehrmamba.MambaBlock, as you explain, so this is not duplication.

Coverage: the whole repository is at 76.91%, above the 60% bar. armr.py is at 98.07%, utils.py at 92.19%, gamenet.py at 93.9%, safedrug.py at 85.49% and micron.py at 83.33%. molerec.py is at 65.93%, below the 80% guideline. The shortfall comes from existing code your diff doesn't touch, and your change there is covered by the new generate_ddi_adj test, so I don't consider it blocking.

Optional suggestions:

  • Add a direct unit test for SelectiveSSM, for example checking causality, meaning that changing later steps leaves earlier outputs unchanged.
  • The notebook's Colab badge points to solarsys/PyHealth, while the install cell uses sunlabuiuc/PyHealth. Aligning them would avoid confusion once the PR is merged.
  • ARMR writes the shared ddi_adj.npy file in its constructor. That race is already tracked in #1374, so nothing is needed here.

Reviewed commit ad3127b

@solarsys
solarsys merged commit ea26a4b into sunlabuiuc:master Nov 3, 2026
2 checks passed
solarsys added a commit that referenced this pull request Nov 4, 2026
The five paper notebooks merged in #1368, #1369, #1371, #1372 and #1373
still installed PyHealth from their pull-request branches, and two Colab
badges opened the fork's branch. They now install from sunlabuiuc master
and open master's copy.

The HeartLang notebook's PTB-XL download also failed in a clean
environment: 32 parallel connections were reset by the S3 mirror, and a
failed download left a truncated file that a rerun treated as finished.
Downloads now retry with backoff, write to a temporary name and rename
when complete, and use 8 threads.


Claude-Session: https://claude.ai/code/session_01BdtuVKBLhWpYbhTQbaZaTt

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
rayrayowo added a commit to rayrayowo/PyHealth that referenced this pull request Nov 21, 2026
… ones

Six bounties are already fully merged but were still listed as open:
22 VAE (sunlabuiuc#1358), 27 YAIB (sunlabuiuc#1338, sunlabuiuc#1417, sunlabuiuc#1423), 40 DiPro (sunlabuiuc#1398),
43 ARMR (sunlabuiuc#1371), 56 TRACE (sunlabuiuc#1382) and 58 ETHOS-ARES (sunlabuiuc#1397).

Eight more are partly merged. Their descriptions now say what is
merged and what remains, so contributors can pick up the rest:
37 MIRA, 41 HeartLang, 42 APN, 52 APRICOT-M, 53 KnowRare,
54 LLMs as EHR Encoders, 55 MEME and 60 TrajSurv.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UxbiyTdwHAng6T548wdSda
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

status: automatic The PR will go through automatic review process.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant