Repository navigation
[BTY-28] Add EviCare diagnosis prediction with deep-model-guided in-context reasoning - #1599
thekavishshah wants to merge 6 commits into
Conversation
Test CoverageTotal: 86.93% (49512 / 56957 lines)
|
|
/review |
There was a problem hiding this comment.
Previous review
AI Review
suggestion: approve
decision: need change
Thank you for this contribution. It adds EviCare(R), an LLM re-ranker guided by a trained model, along with MIMIC-III and MIMIC-IV CCS diagnosis tasks, the paper's metrics, docs, an example script and offline tests. The description is candid about scope and about the numbers not being reproduced. The change looks ready to merge.
Coverage meets the bar. pyhealth/models/evicare.py is at 99.7% and pyhealth/tasks/evicare_diagnosis.py at 99.5%, against the 80% per-file bar. The whole repository is at 86.4%, against the 60% bar.
Every link between components is named in the description with a purpose: RETAIN as the default guide, CrossMap/InnerMap for the default CCS mapping, and OpenAILLM in the example.
Optional suggestions:
-
Co-occurrence in the novel setting.
fit_cooccurrencereads each patient's codes from their samples (history plus targets). In the novel setting, a patient with no sample is left out ofG. This happens when none of their later visits adds a new code. SoGcan differ slightly fromAᵀAover all training patients. Counts for patients who do have samples are correct, since history plus novel targets covers all of their codes. Fitting from the raw task output, or noting this in the docs, would remove the difference. A dataset-path test in the novel setting would also help. -
Example endpoint settings. The example's
extra_bodysendstop_kandchat_template_kwargs. Some non-vLLM OpenAI-compatible endpoints may reject these. A short note in the docs, or a flag to omit them, would help. -
Warning: this PR can't be approved automatically because the review found a high-severity problem (see the inline comments). To stay on automatic review, fix it, then comment
/review. If the next review finds this again, the PR switches tostatus: manual.
Reviewed commit 06587d7
Next-visit CCS diagnosis prediction on MIMIC-III and MIMIC-IV in the overall and novel settings of EviCare (Zhang et al., KDD 2026), with a CCSMapping helper (PyHealth CrossMap tables by default, or a CSV). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
EviCare wraps a guide model (RETAIN by default) as a BaseModel and adds candidate selection, evidential prioritization, co-occurrence relational evidence (G = A^T A on training patients), prompt building, a robust 'Answer:' parser with guide-order fallback, and visit-level P@k / code-level Acc@k metrics. The tasks gain sample_mode, defaulting to one sample per visit as in the paper's TRANS-based pipeline. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
examples/diagnosis_prediction/evicare_mimic3.py runs the full pipeline on the bundled MIMIC-III/IV demos with an offline fake-LLM mode or any OpenAI-compatible endpoint (official decoding defaults), and refuses to send credentialed data to remote endpoints. Docs pages for the model and tasks list every difference from the paper and the official code. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
fit_cooccurrence rebuilt each patient's codes from samples' history_ccs + ccs_targets. In the novel setting ccs_targets drops codes already seen, and a target with no new code gives no sample, so patients whose admissions repeat earlier codes never reached G and codes seen only in them dropped out of its vocabulary (also with sample_mode="last"). - Task: patient_codes(patient) and patient_code_sets(dataset, patient_ids) read every CCS code of every usable admission from the patients themselves, independent of setting and sample_mode. - CooccurrenceGraph.fit takes a vocab; from_samples is removed. - EviCare.fit_cooccurrence takes patient code sets (rejects a sample dataset) and includes all guide label codes in G's vocabulary. - Example: split eligible patients (not sample patients), fit G from the kept training patients' code sets; add --no-extra-body for endpoints that reject top_k / chat_template_kwargs. - Docs: G-fitting workflow and the endpoint note. - Tests: novel repeat patient counted, no-sample-only code in vocab, sample_mode="last", hand-computed A^T A in both settings, dataset path. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
06587d7 to
042689a
Compare
|
/review |
There was a problem hiding this comment.
Previous review
AI Review
suggestion: approve
decision: approve
Thank you for this contribution. It adds EviCare(R), which uses a RETAIN guide model with LLM re-ranking, and it adds MIMIC-III and MIMIC-IV next-visit CCS tasks. The tasks cover the overall and novel settings and use a patient-level co-occurrence graph. The PR also includes an example script, docs, a CSV fixture and 90 offline tests. It looks ready to merge.
Core code: I found no changes to base classes, the Trainer, registries or shared utilities. The edits to the two __init__.py files only add exports, and the docs edits only add toctree entries.
Sharing between components: Your description names every link and says why. These are RETAIN as the default guide, CrossMap for the ICD-to-CCS mapping, and OpenAILLM in the example.
Datasets: No new dataset class is added.
Coverage: Coverage meets the bar. evicare.py is at 99.7% and evicare_diagnosis.py at 99.6%. The whole repository is at 86.9%.
Optional suggestions:
- In the novel setting the prompt shows only the last visit. Relational evidence in
_predict_oneis computed from the full history, so it can name a historical code that the prompt never shows. Either restrict the relations to the displayed codes or note the behaviour in the docs. predictdoes not check that the dataset was built with the samesettingas the model. A short check or a warning would catch a mismatch early.- The example docstring says the fake-LLM run takes "about a minute", while the PR description says 5–15 s. Please make the two agree.
_iter_patientsis tested only with aSimpleNamespacestub. A test against a real small dataset would be a nice addition.
Reviewed commit 042689a
|
/review |
| One :class:`EviCarePrediction` per sample, in dataset order. | ||
|
|
||
| Raises: | ||
| ValueError: If relational evidence is on and |
There was a problem hiding this comment.
[medium] predict docstring says it raises without an LLM, but it raises only when an LLM is given
The Raises section says predict raises ValueError when relational evidence is on and fit_cooccurrence has not been called. The check at line 1002 runs only when llm is not None, so predict(dataset) without an LLM returns the guide ranking with no error. Fix: state that the error applies when an llm is passed.
| ccs_names: Mapping[str, str] | None = None, | ||
| use_relations: bool = True, | ||
| max_prompt_visits: int | None = None, | ||
| embedding_dim: int = 16, |
There was a problem hiding this comment.
[low] embedding_dim and guide_kwargs are silently ignored with a guide class or instance
embedding_dim is used only when guide_model is None. EviCare(ds, guide_model=RNN, embedding_dim=64) silently builds RNN with its own defaults, and guide_kwargs are dropped when a guide instance is passed. test_guide_class_and_instance passes embedding_dim=8 with RNN and asserts nothing about it. Fix: raise ValueError when embedding_dim or guide_kwargs are given alongside a guide class or instance.
| ) | ||
|
|
||
|
|
||
| class _EviCareDiagnosisPrediction(BaseTask): |
There was a problem hiding this comment.
[low] New task repeats the visit and sampling logic of the existing next-visit task without saying why
_EviCareDiagnosisPrediction re-implements the visit grouping, min_visits check, all_prefixes/last sampling and sample assembly that _NextVisitDiagnosisPrediction (pyhealth/tasks/next_visit_diagnosis_prediction.py:65) already provides for NextVisitDiagnosisPredictionMIMIC3/4. It is not redundant because the novel setting, CCS labels and evidence fields are new, but the description does not explain why it is a separate class rather than an option on the existing tasks. Fix: add a sentence to the description on why the logic is kept separate.
| ids = [str(p) for p in dataset.unique_patient_ids] | ||
| if wanted is not None: | ||
| ids = [p for p in ids if p in wanted] | ||
| for start in range(0, len(ids), batch_size): |
There was a problem hiding this comment.
[low] patient_code_sets scans the full event table once per batch
For each batch of 1000 patients, the lazy global_event_df is filtered and collected again, so a full MIMIC-III run reads the event table about 46 times. Fix: collect the event_type-filtered frame once and partition it by patient, or query all patients in one pass.
There was a problem hiding this comment.
AI Review
suggestion: need change
decision: need change
Thank you for this contribution, Kavish. It adds EviCare(R) to PyHealth: a guide-model-plus-LLM re-ranker, two MIMIC tasks with novel and overall settings, a CCSMapping, docs, an example script and 90 offline tests. The write-up is clear, and the design keeps the guide trainable with the standard Trainer. Coverage is above the bar: 99.68% for evicare.py, 99.58% for evicare_diagnosis.py and 86.93% for the whole repository. You have also stated plainly that the paper's numbers are not reproduced.
It is close. One small fix remains.
To get this merged:
- In
EviCare.predict(pyhealth/models/evicare.py), the docstring'sRaisessection says aValueErroris raised when relational evidence is on andfit_cooccurrencehas not been called. The code only checks this when anllmis passed, and the guide-only path never uses relations. Please either reword the docstring to say "when anllmis given and…", or change the code to match the docstring.
Optional suggestions:
embedding_dimandguide_kwargsare silently ignored whenguide_modelis an already-built instance, andembedding_dimis also ignored when it is a class. A short note in the docstring, or a warning, would avoid surprises.patient_code_setsre-collects the event table once per batch. Collecting it once could be faster on full MIMIC.- The new tasks copy some grouping and sampling logic from
NextVisitDiagnosisPredictionMIMIC3/4. Copying is fine, but a sentence in the description on why this is a separate task (the novel setting, CCS labels and the evidence fields) would help reviewers.
Reviewed commit f07d8e4
…Y-28) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Contributor: Kavish Shah (kshah77@asu.edu, GitHub: thekavishshah)
Contribution Type: New Model + Task (BTY-28, partial: EviCare(R); BoxLM guide remaining)
Description:
Implements EviCare (Zhang et al., EviCare: Enhancing Diagnosis Prediction with Deep Model-Guided Evidence for In-Context Reasoning, KDD 2026, paper, doi, official code) for PyHealth 2.x.
Scope: this PR covers EviCare(R) only, with RETAIN as the guide model. BoxLM, the guide of the paper's main variant EviCare(B), is not included and is the remaining scope of BTY-28.
EviCareaccepts any PyHealth model that returns per-label logits, so a BoxLM guide can be added in a follow-up without changing this API.EviCare predicts the CCS categories of a patient's next visit with an off-the-shelf LLM, without fine-tuning. A trained deep model (the guide) supplies the prompt evidence: the top-K candidates (K = 50), the patient's history grouped as ICD → CCS and sorted by guide logit (Eqs. 7–8), and relational evidence from a co-occurrence matrix
G = AᵀAover the training patients (each row ofAholds every CCS code of the patient's admissions) that links each new candidate to its most co-occurring historical code (Eqs. 9–10). The LLM re-ranks the candidates (Answer: <CCS 1>, ...). Both of the paper's settings are supported: overall (all next-visit codes) and novel (only codes absent from the history).Design choices:
EviCareis aBaseModelwhoseforwardis the guide's, so the guide trains with the standardTrainer.fit_cooccurrence,predictandevaluateadd the LLM stage. The evidence fields (history_icd_names,history_ccs,days_ago) are left out of the schema. They pass throughSampleBuilderunchanged, so the guide only seesconditions.fit_cooccurrencetakes patient-level code sets fromtask.patient_code_sets(dataset, patient_ids=...), which reads every CCS code of every usable admission from the patients themselves. Samples are not enough. In the novel setting a label keeps only codes new to the patient, and a patient whose admissions only repeat earlier codes gives no sample at all. SoGand its vocabulary do not depend onsettingorsample_mode. The vocabulary is the guide's label codes plus every training-patient code, so every candidate has a row. Passing a sample dataset raises aTypeErrorthat names the right call. I chose a task method over a separate helper or a newCooccurrenceGraphconstructor because the task already owns the ICD → CCS mapping, admission filtering andmin_visits, so rows ofAuse exactly the patients and codes behind the samples.llm(system, prompt) -> strcallable, following thepyhealth.autoimproveconvention (ClaudeLLM,OpenAILLM, and vLLM or other OpenAI-compatible servers). The tests make no network calls.parse_answerkeeps only candidates, matched by name or code. It ignores<think>blocks and reasoning before the lastAnswer:, drops hallucinated codes and duplicates, and matches whole items, never substrings (some CCS names contain other CCS names).merge_rankingfills the rest in guide order, so a malformed reply or a failed call (logged and recorded inEviCarePrediction.error) falls back to the guide's ranking.EviCareDiagnosisPredictionMIMIC3/4(setting="overall"|"novel",sample_mode="all_prefixes"|"last"). These are separate fromNextVisitDiagnosisPredictionMIMIC3/4because EviCare needs three things those tasks do not give: the novel setting (labels restricted to codes new to the patient), CCS category labels instead of raw ICD codes, and the per-visit evidence fields (history_icd_names,history_ccs,days_ago) that the prompt is built from. ICD → CCS mapping is aCCSMapping: by default PyHealth's single-level CCS throughCrossMap(285 categories, the same ICD-9 table as the official code). A user CSV (ccs_mapping=path) can supply any other grouping, such as CCSR. The mapping has a content-digestrepr, so the task cache is keyed by the mapping actually used.pyhealth/models/evicare.py; sharedpyhealth/metricsis untouched. Visit-level P@k divides each visit's hits bymin(k, |truth|); code-level Acc@k is total hits over total true codes. Both have novel variants.--root(credentialed data) to a non-local endpoint unless--allow-remote-llmis passed. The PhysioNet DUA forbids sharing MIMIC with online services.Assumptions where the paper is silent (also in the docs):
model/qwen3-8B.yamlsettings (non-thinking mode, temperature 0.7, top-p 0.8, top-k 20, max 256 new tokens) are the example's defaults. The paper gives none.all_prefixes, the default). This follows the TRANS preprocessing that EviCare's data pipeline builds on and the paper's visit-averaged P@k. It differs fromNextVisitDiagnosisPredictionMIMIC3, which defaults to"last".Differences from the paper / official code:
use_relations=Falseturns it off.--train-fraction(the paper's main tables use 5%).Known limitation:
patient_code_setscollects the event table again for every batch of patients. This is fine on the demo datasets, but I have not timed it on full MIMIC-III/IV, so fittingGon a full training split may be slow.Reproduction status (honest): I do not have credentialed MIMIC access or a GPU, so the paper's numbers are NOT reproduced. No real LLM endpoint was available either, so the LLM stage ran only with an offline fake LLM: a deterministic heuristic that reads the candidates from the prompt and adds noise to exercise the parser. The fake-LLM runs only verify that the pipeline works; their metrics mean nothing. What was run:
90 unit tests and 19 doctests on synthetic data (109 passed, 4 skipped, about 11 s), covering:
AᵀAand hand counts, with one row per patientGbuilt from patient code sets, not samples: in the novel setting a patient whose two admissions are both {98, 106} is counted; a code found only in patients without samples is in the vocabulary;sample_mode="last";Gequals a hand-writtenAᵀAover all patients in both settings<think>blocks, numbered lists, names containing commasCoverage is 99% on both new modules.
examples/diagnosis_prediction/evicare_mimic3.pyend to end on the bundled MIMIC-III demo (overall: 29 samples; novel: 25) and MIMIC-IV demo (novel: 7), with--fake-llm, guide only, and the remote-endpoint guard. Each run takes 5–15 s on a laptop CPU. With 2–5 test visits the printed metrics are noise, so I am not reporting them as results.For reference, the paper's results (mean ± std, Qwen3-8B). The paper's main tables train the deep models, and the guide, on 5% of the training data; the example's
--train-fraction 0.05matches this. All values below were checked against Tables 2, 3 and 8 of arXiv 2604.10455v1.The paper does not say whether the ± is over folds or seeds. Its own tables disagree in places. The MIMIC-III EviCare(B) row above (Table 2) matches the full model in the ablation (Table 4) and Table 7 (P@10: novel 24.41, overall 51.73). Table 9, labelled only "EviCare", reports novel 22.03 / 24.58 / 14.56 / 22.12 and overall 52.01 / 55.23 / 36.67 / 52.11, and Table 5 also gives novel P@10 24.58. I quote Table 2.
If a maintainer with MIMIC access and a GPU can serve Qwen3-8B locally (
vllm serve Qwen/Qwen3-8B) and runpython examples/diagnosis_prediction/evicare_mimic3.py --root <mimic-iii> --setting novel --train-fraction 0.05 --epochs 50 --llm Qwen/Qwen3-8B --base-url http://localhost:8000/v1, I'd be glad to add the numbers.Files to Review:
pyhealth/models/evicare.py:EviCare,EviCarePrediction,CooccurrenceGraph, the evidence and prompt builders,parse_answer/merge_ranking, and the P@k / Acc@k metricspyhealth/tasks/evicare_diagnosis.py:EviCareDiagnosisPredictionMIMIC3/4(includingpatient_code_sets),CCSMappingtests/core/test_evicare.py: 90 tests (synthetic, offline)test-resources/core/evicare/ccs_mapping_tiny.csv: 13-row ICD → CCS fixture (real codes and names, checked against CrossMap)docs/api/models/pyhealth.models.EviCare.rst,docs/api/tasks/pyhealth.tasks.evicare_diagnosis.rstand toctree entriesexamples/diagnosis_prediction/evicare_mimic3.py: full pipeline: 7:1:2 split over all eligible patients (patients without samples still get a split),--train-fraction, guide training,Gfrom the kept training patients' code sets, then the guide-only baseline vs EviCare. Takes--fake-llmor--llm/--base-urlwith the official decoding defaults, and guards against sending credentialed data to remote endpoints.top_kand Qwen3'schat_template_kwargsare sent in the request body for vLLM/SGLang;--no-extra-bodydrops them for OpenAI-compatible endpoints that reject them.pyhealth/models/__init__.py,pyhealth/tasks/__init__.py: exportsChecks:
tools/check_pr_rules.pypasses;ruffclean on new files;pytest tests/core/test_evicare.pyplus doctests: 109 passed, 4 skipped. The two new docs pages build with Sphinx-W(autodoc + napoleon).