Repository navigation
[BTY-29] Implement GiantMed medication recommendation - #1502
Conversation
Test CoverageTotal: 88.88% (61184 / 68839 lines)
|
# Conflicts: # pyhealth/models/__init__.py
|
/review |
There was a problem hiding this comment.
Previous review
AI Review
suggestion: need change
decision: human review
Thank you for this contribution. It adds GiantMed, an inference-time LLM refinement of SafeDrug scores, with MEDI evidence filtering, optional run manifests, an explicit NDC-to-ATC3 option on the MIMIC-III and MIMIC-IV tasks, examples, a notebook and docs. The work is thorough and the limitations are stated clearly. The change is close, and one bug needs fixing first.
To get this merged:
- In
pyhealth/models/giantmed.py, theprompt_templatecheck accepts a template with a trailing line break, such as"... {boundary}\n"."x\n".splitlines()has length 1, so it passes. The rendered prompt then has a newline before " Return only a JSON object...". In_fit_prompt(budgeted, non-batched mode) the prompt is split into lines and each line after the first is parsed asName: json. The extra line makes this fail with an IndexError or JSON error. Please reject trailing or embedded line breaks, or strip them (the example script already doesrstrip), and add a test with a trailing newline in budgeted mode. pyhealth/tasks/drug_recommendation.pyis at 71.27% coverage, below the 80% guideline for modified files. Please add tests for the newmap_drugsdefault path (nondc_to_atc3) and for the MIMIC-IV mapping, or explain why the remaining uncovered lines are unrelated to this change. Overall coverage (86%) and the new files (giantmed.py96%,experiment_tracking.py85%) meet the bar.
Optional suggestions:
- The OpenRouter adapter's error says "stopping the run", but the example continues per visit. Please reword it.
- The
cache_versionbump tondc_to_atc3_v2invalidates existing task caches even though default output is unchanged. A brief note in the description would help. - The
refine_with_detailsdocstring omits several returned keys, such asprompts,responses,prompt_budgetandchanged. --candidate-batch-sizewithout a tokenizer fails with a constructor traceback. A clear argparse error would be friendlier.- The notebook is committed without saved outputs. That is fine, but the description mentions executing it.
Reviewed commit 6c4426d
|
@solarsys Could you please take another look at this PR when you have a chance? The four review threads have been addressed and resolved, and the latest build and contribution checks passed. The drug-recommendation module coverage is now 94.98% on the current commit. Thank you! |
|
/review Generated by Claude Code |
|
Let me clean this up, and reduce the output |
|
/review |
# Conflicts: # pyhealth/models/__init__.py
|
/review |
There was a problem hiding this comment.
Previous review
AI Review
suggestion: approve
decision: human review
Thank you for this contribution. GiantMed adds a SafeDrug-compatible postprocessor that refines uncertain medication probabilities. It uses similar training visits, optional MEDI evidence filtering, a budgeted prompt and candidate batching, and it comes with MIMIC-III and MIMIC-IV demos, docs and a notebook. It looks ready to merge.
What I checked:
- Scope: The only change to shared code is an optional
ndc_to_atc3argument and amap_drugsmethod onDrugRecommendationMIMIC3/4. Default labels and cache identity are unchanged, and a test covers that. The description names this change and explains it as aligning labels with the MEDI index. - Links between components: The example reads SafeDrug's
ddi_adj, and the MEDI index uses the task'smap_drugs. Both are explained in the description and README. - Coverage: It meets the bar.
giantmed.pyis at 96.14% anddrug_recommendation.pyat 94.98%, both above the 80% guideline. The repository total is 86.76%, above 60%. The models__init__.pyis at 100%. - Documentation: The docs match the code. Limitations are stated clearly: DDI evidence is not a hard constraint, the NDC mapping is incomplete, and the demo is a smoke test rather than a paper reproduction.
Optional suggestions:
- The batched and budgeted interaction adjacency lists are one-directional, so each pair is listed only once. A short note in the prompt, or listing both directions, would make that harder to misread.
- An unclosed
<think>block isn't stripped from responses. Handling it would make parsing more robust. - The README is very long. Moving the MEDI and batching details into separate sections or the docs page would make it easier to scan.
- The notebook's recorded metrics are hard-coded. You could note that they come from local runs and can't be regenerated from the repository alone.
- The example pipelines are tested only through helpers and argument checks. A small end-to-end test with the
--demo-refinementresponder would be a nice addition.
Reviewed commit 643ac99
# Conflicts: # pyhealth/models/__init__.py
|
/review |
There was a problem hiding this comment.
Previous review
AI Review
suggestion: approve
decision: human review
Thank you for this contribution. It adds GiantMed, an LLM-based postprocessor that refines uncertain medication probabilities from a trained model such as SafeDrug. It also adds optional MEDI evidence filtering with ICD-9/ICD-10 handling, token-budgeted and batched prompts, MIMIC-III and MIMIC-IV demo scripts, a notebook and docs. The change looks ready to merge.
What I checked:
- The change is self-contained. The new module imports only numpy and the standard library.
DrugRecommendationMIMIC3/4gain an optionalndc_to_atc3argument and amap_drugsmethod. Defaults and the default cache identity stay the same, and your test checks this.- The description names the links to other components, namely the SafeDrug backbone in the example and the task's explicit mapping, along with their purpose.
- The docs match the code on boundary semantics, response statuses and ICD prefixes.
- The module has no new dataset, so no dataset source link is needed.
- Coverage meets the bar:
giantmed.py96.7% (added),drug_recommendation.py95.0% (modified), whole repository 87.2%.
Optional suggestions:
giantmed_mimic4.pyusesfrom giantmed_mimic3 import main. This works when the script is run directly but would fail underpython -mor as a package import. A fallback import would make it more robust.- The MIMIC-IV branch of
main()has no test of its own. A small stub test like the MIMIC-III one would help. - The notebook's recorded numbers come from external inputs and prior runs. A one-line provenance note, such as the command and date, would help readers.
tests/core/test_drug_recommendation_legacy.pyand the reformatting intest_drug_recommendation_atc3.pyare unrelated to GiantMed. They are harmless, but you could split them out if you prefer a tighter diff.
Reviewed commit 317d9f6
|
/review |
There was a problem hiding this comment.
Previous review
AI Review
suggestion: approve
decision: human review
Thank you for contributing GiantMed. It adds an inference postprocessor that refines uncertain SafeDrug medication probabilities using similar training visits, interaction evidence and an LLM. It also adds optional MEDI evidence filtering, an optional ndc_to_atc3 mapping on the MIMIC-III and MIMIC-IV drug-recommendation tasks, MIMIC-III and MIMIC-IV demo scripts, a notebook, docs and tests.
This looks ready to merge. The diff matches the description, and the default task behaviour and cache identity are unchanged. The tests cover parsing, prompt budgeting, batching, MEDI matching, task mapping, and an offline stub-backbone run of both examples. Coverage is 96.69% for the new giantmed.py and 94.98% for drug_recommendation.py. Both are above the 80% bar, and the repository total of 88.86% is above 60%.
Optional suggestions:
- CSV-only MIMIC-III root:
giantmed_mimic3.pyonly looks forPRESCRIPTIONS.csv.gz, as far as I can see from the diff. A root with only the uncompressed.csvwould fail, even though the dataset loader accepts both. The MIMIC-IV path already falls back to the uncompressed file, so the same fallback would make the two consistent. - MIMIC-IV entry point:
giantmed_mimic4.pyreusesmainfromgiantmed_mimic3.py. This is fine as the same example family. A one-line note in the description saying it's intentional would make it explicit. - Unrelated test changes:
test_drug_recommendation_legacy.pyand the reformatting intest_drug_recommendation_atc3.pyaren't part of GiantMed. They are harmless, but you could move them to a separate PR. - Notebook results: the notebook's recorded results can't be regenerated from the repository, which the PR already says clearly. A short pointer to the exact script options used would help readers who want to repeat the runs.
Reviewed commit a1d855b
|
/review |
| "# python examples/drug_recommendation/giantmed_mimic3.py --ndc-rxcui PATH --ndc-atc PATH --medi PATH --ingredient-cache PATH --openrouter-model qwen/qwen3-14b --prompt-tokenizer Qwen/Qwen3-14B --candidate-batch-size 32 --epochs 1 --max-test-visits 5\n", | ||
| "# Exact source commit, provider route and model checkpoint were not recorded.\n", | ||
| "# Recorded aggregate results; no prompts, responses or patient identifiers.\n", | ||
| "reference_run = {'visits': 5, 'baseline': {'jaccard_samples': 0.25900159841467174, 'f1_samples': 0.40822082608196825, 'pr_auc_samples': 0.49918605283314055, 'ddi_rate': 0.04011194029850746, 'mean_medications': 21.25}, 'giantmed': {'jaccard_samples': 0.24820716320716318, 'f1_samples': 0.3936324206246823, 'pr_auc_samples': 0.3836284914071797, 'ddi_rate': 0.09941520467836257, 'mean_medications': 29.166666666666664}, 'medi': {'indication_mismatch': 106, 'indication_match': 102, 'history_rescue': 83}, 'requests': 15, 'cost': 0.00548486, 'prompt_tokens': [2097, 3424], 'candidate_names': [394, 394], 'ddi_pairs': [1383, 1383], 'cross_batch_pairs': 817, 'similar_visits': [45, 45], 'history_visits': [12, 12], 'prescription_ndc_rows': [6789, 8920]}\n", |
There was a problem hiding this comment.
[medium] Tutorial prints hard-coded results that cannot be reproduced from the repo
The reference_run dict (line 174), the epochs10 dict (line 228) and the mimic4 dict (line 341) are literal numbers that the notebook displays as results. The cells say the source commit, provider route and checkpoints were not recorded and the commands were reconstructed, so no one can regenerate these figures from the repository. The MIMIC-IV table comes from a fake responder that assigns 0.8 to every boundary drug, so its PR-AUC drop reads as a result when it only exercises code paths. Fix: remove the literal result tables from the committed notebook and keep the offline synthetic walkthrough and the command text. Put the recorded numbers in the PR description, or have the script write its metrics to a file that is committed with its command and the commit it came from.
|
|
||
| This is a pipeline smoke test, not a meaningful performance comparison or a reproduction of the paper. SafeDrug is trained for only one epoch on a tiny demo. Access to cached or downloadable PyHealth medical-code resources is needed. An LLM is needed only for model-generated refinement. Omitting `--model` uses a no-op response for a smoke test, so the two sets of metrics must match. `--demo-refinement` uses a deterministic fake responder to exercise score updates; its predictions have no clinical meaning. The example prints no patient prompts, but the LLM receives clinical information; use a backend appropriate for the dataset's access terms. | ||
|
|
||
| ## Using the postprocessor |
There was a problem hiding this comment.
[low] README is longer than the user needs
The 'Using the postprocessor', 'Candidate batching' and token-budget sections are long paragraphs that mix required inputs, internal prompt layout and warnings. Cut them to the required inputs, the evidence-is-not-a-hard-constraint warning and the example commands, and move the prompt-layout details to the GiantMed docstring or the docs page.
There was a problem hiding this comment.
AI Review
suggestion: approve
decision: human review
Thank you for contributing GiantMed. It adds an inference-time postprocessor that refines uncertain SafeDrug medication probabilities using similar training visits, optional MEDI evidence filtering, DDI context and an LLM callable. It also adds an optional explicit NDC-to-ATC3 mapping for the MIMIC-III and MIMIC-IV drug-recommendation tasks, plus MIMIC-III and MIMIC-IV demo examples, docs and tests. This looks ready to merge.
- Correctness: The diff matches the description. Malformed, partial or unmatched-tag responses keep the backbone scores. The new task argument leaves defaults and default cache identity unchanged, and tests check this.
- Coverage:
pyhealth/models/giantmed.pyis at 96.69% andpyhealth/tasks/drug_recommendation.pyat 94.98%, both above the 80% bar. The whole repository is at 88.88%, above 60%. - Links between components: The examples use SafeDrug and the drug-recommendation tasks. The task option exists so labels and MEDI index keys match. The MIMIC-IV entry point reuses the MIMIC-III example's
main. The description and README explain these links. - Documentation: The API page, README and notebook match the code. They state the limitations clearly: smoke test only, external inputs not bundled, and DDI evidence is not a hard constraint.
Optional suggestions:
- The notebook's result tables are hard-coded recorded transcripts. They are clearly labeled as not recomputed, and the original commits and checkpoints weren't recorded. You could shorten them, or keep only the synthetic walkthrough, so readers aren't led to expect reproducibility.
- The README is long and dense. Splitting it into short sections (usage, MEDI mappings, token budgeting) would make it easier to scan.
Reviewed commit db255dc
solarsys
left a comment
There was a problem hiding this comment.
Approved by a maintainer. The AI review suggests approve on the current commit, and the build passes.
Contributor: Giovanni Dall'Olio
Contribution type: Paper implementation and examples
GiantMed refines uncertain medication probabilities from a trained EHR model using similar training visits, medication history, drug-interaction evidence and an LLM. This PR adds a SafeDrug-compatible inference postprocessor, optional MEDI evidence filtering, and MIMIC-III and MIMIC-IV demo examples. It follows Lv et al. and the authors' reference code, with the adaptations noted below.
Files to review:
pyhealth/models/giantmed.py: retrieval, prompt construction, budgeted candidate batching, response parsing, MEDI filtering and an optional Hugging Face generator.pyhealth/tasks/drug_recommendation.py: optional explicit NDC-to-ATC3 mappings for MIMIC-III/IV; defaults and default cache identity are unchanged.examples/drug_recommendation/giantmed_mimic3.py,giantmed_mimic4.py, the README and output-free notebook: demo setup, patient-level comparison and interpretation.tests/core/test_giantmed.pyand the drug-recommendation tests: synthetic and demo-fixture checks, including mapping, ICD systems, medication history and prompt edge cases.docs/api/models/pyhealth.models.GiantMed.rst: public API and backend-interface notes.General-purpose optional experiment tracking was separated into #1619; this PR does not depend on it.
Validation:
Latest follow-up: MIMIC-III accepts
.csvor.csv.gzprescriptions, with an offline regression test for both; historical notebook tables are labeled as recorded transcripts, and the committed notebook has no dates or saved outputs. Focused suite: 105 passed, 1 skipped; notebook executed and contribution rules passed locally.Latest review follow-up: use SafeDrug's public DDI matrix (tested equal to the layer adjacency), support compressed and uncompressed MIMIC-IV prescription files, support both MIMIC-IV entry-point invocation forms, and exercise both dataset branches with a deterministic offline responder and stub backbone. The output-free notebook includes date-free recorded-run provenance; original source commits and checkpoints were not recorded, and the commands are reconstructed. Focused tests and doctests: 104 passed, 1 skipped; the notebook executed and contribution rules passed locally.
Review follow-up: budgeted and batched prompts state that each listed interaction pair applies in both directions; unmatched or nested thinking tags leave backbone scores unchanged. The renderer version is now v2. Added parser and prompt tests plus a synthetic offline example-flow test using a stub backbone; the latter is not a real-model experiment. After merging upstream, the focused GiantMed, drug-recommendation and SafeDrug tests and doctests passed (99 passed, 1 skipped); contribution rules passed locally. The output-free notebook was executed and clarifies that recorded results need separately obtained inputs.
After merging upstream master and separating tracking, focused GiantMed, drug-recommendation and SafeDrug tests and GiantMed doctests: 91 passed, 1 skipped. Contribution rules passed locally. The focused notebook executed locally and is committed without outputs.
Previously, GitHub CI measured 94.98% coverage for the drug-recommendation module. New CI runs will measure the updated merge commit.
With the prior prompt renderer, on five MIMIC-III demo visits, Qwen3-14B through OpenRouter used the reference NDC-to-RxCUI-to-first-ATC3 mapping and a separately expanded ingredient cache. With the final ten-epoch SafeDrug checkpoint, GiantMed vs SafeDrug Jaccard was 0.336 vs 0.319, F1 0.500 vs 0.482, PR-AUC 0.611 vs 0.616, and DDI rate 0.102 vs 0.085. This sampled smoke test is not a clinical evaluation or paper reproduction.
On the open MIMIC-IV demo, five held-out visits were tested with a deterministic fake responder, not an actual LLM; no MIMIC-IV prompts were sent externally. MEDI evidence checks included both ICD-9 and ICD-10 indications. The reference NDC mapping covered 9,380/15,456 usable prescription rows; unmapped rows were excluded.
Scope and limitations:
9_and10_diagnosis codes are matched against MEDI ICD-9-CM and ICD-10-CM indications separately; unprefixed codes retain the MIMIC-III ICD-9 interpretation. A previous-visit history rescue can retain evidence without an ingredient match.