Skip to content

[Model + Task] Query-Focused EHR Summarization with ClinicalBERT Attention (McInerney et al., 2020) - #1623

Merged
solarsys merged 11 commits into
sunlabuiuc:masterfrom
rameshsudharshan:feat/query-focused-ehr
Nov 27, 2026
Merged

solarsys merged 11 commits into
sunlabuiuc:masterfrom
rameshsudharshan:feat/query-focused-ehr

Conversation

@rameshsudharshan

@rameshsudharshan rameshsudharshan commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Contributors

Course project for CSE6250 (Georgia Tech), reproducibility challenge.

Contribution Type

Model + Task, with an end-to-end example pipeline using the existing PyHealth MIMIC3Dataset.

This contribution introduces a reusable query-focused EHR task and a ClinicalBERT-based attention model for retrieving clinically relevant historical sentences conditioned on a diagnosis query.

Paper

Query-Focused EHR Summarization to Aid Imaging Diagnosis
McInerney et al. (2020)

Original paper: https://proceedings.mlr.press/v126/mcinerney20a.html

The paper investigates whether diagnosis-conditioned extractive summarization can identify relevant information from longitudinal electronic health records, helping clinicians access important patient history for imaging-related decisions.

What This Adds

1) QueryFocusedEHRTask

Introduces a task for constructing diagnosis-conditioned examples from longitudinal MIMIC-III records.

Key functionality:

  • Extracts sentences from historical clinical notes.
  • Associates notes with patient admissions.
  • Filters historical information using configurable time windows.
  • Enforces temporal cutoffs to reduce future-information leakage.
  • Generates binary weak-supervision labels from subsequent ICD-9 diagnoses.
  • Supports configurable diagnosis groups and minimum/maximum sentence counts.

2) QueryFocusedEHRModel

Implements a diagnosis-conditioned extractive summarization model using pretrained ClinicalBERT.

Key functionality:

  • Encodes historical sentences and diagnosis queries using ClinicalBERT.
  • Computes query-conditioned attention scores over historical sentences.
  • Aggregates sentence representations for binary diagnosis prediction.
  • Supports frozen and fine-tuned ClinicalBERT configurations.
  • Provides top-k sentence extraction with attention scores.
  • Supports embedding caching when the encoder is frozen.

Pretrained encoder: emilyalsentzer/Bio_ClinicalBERT

3) End-to-End Example and Ablation

The example script demonstrates:

  • Loading MIMIC-III-compatible data.
  • Constructing query-focused EHR samples.
  • Splitting examples by patient.
  • Training the attention model.
  • Evaluating downstream diagnosis prediction using AUROC and average precision.
  • Comparing against a TF-IDF retrieval baseline.
  • Evaluating configurable historical observation windows.

Example: examples/mimic3_query_focused_ehr_attention.py

4) Tests and Documentation

The contribution includes task/model tests and associated API documentation.

Task functionality includes sentence segmentation, historical note filtering, configurable observation windows, and diagnosis-based labeling.

File Guide

File or component Purpose
pyhealth/tasks/query_focused_ehr.py Query-focused EHR task and sentence extraction
pyhealth/models/query_focused_ehr.py ClinicalBERT attention model
examples/mimic3_query_focused_ehr_attention.py End-to-end example and ablation
Associated task/model tests Validation using synthetic or pseudo data
API documentation and index updates PyHealth documentation integration

Reproduction Attempt and Results

Dataset

Experiments were conducted using an augmented version of the publicly available MIMIC-III demonstration dataset.

The experimental dataset contains:

  • 100 original demonstration patients.
  • Original MIMIC-III demo diagnoses.
  • Additional synthetic historical admissions.
  • Synthetic historical clinical notes.

Important: The historical clinical notes are synthetic and do not constitute genuine patient-linked clinical narratives. This dataset was used to validate the computational pipeline rather than establish clinical performance.

Experiment Configuration

  • Encoder: Bio_ClinicalBERT
  • Encoder configuration: Frozen
  • Training: 10 epochs
  • Random seed: 42
  • Patient-disjoint train/validation/test splits
  • Metrics: AUROC and average precision

For the matched-cohort experiment, the dataset contained 214 examples from 100 patients, with 25 positive examples.

History-Window Ablation

History Window ClinicalBERT AUROC ClinicalBERT AP TF-IDF AUROC TF-IDF AP
30 days 0.667 0.222 0.500 0.100
90 days 0.778 0.491 0.500 0.100
365 days 0.642 0.195 0.500 0.100

The 90-day history window achieved the highest AUROC and average precision in this experiment.

These findings are exploratory because the test split contained only three positive examples, and the historical note text was synthetically generated.

Additional Experiment: Encoder Fine-Tuning

We compared a frozen ClinicalBERT encoder with full encoder fine-tuning using the 90-day observation window.

Configuration AUROC AP
Frozen ClinicalBERT 0.7778 0.4911
Fine-tuned ClinicalBERT 0.6049 0.1619

Fine-tuning reduced predictive performance in this small-data setting. This may reflect overfitting, although further experiments would be required to establish the cause.

The limited training dataset may also have been insufficient to reliably fine-tune all ClinicalBERT encoder parameters.

Qualitative Sentence Ranking

The model successfully produced top-k historical sentence rankings conditioned on diagnosis queries.

Inspection of selected examples showed substantial overlap between the sentences selected for pneumonia and pulmonary embolism queries. This limits the evidence for clinically meaningful query specificity in the synthetic-data experiment.

Limitations and Reproducibility

This contribution implements the core query-focused EHR summarization pipeline, including historical sentence extraction, diagnosis-conditioned ClinicalBERT attention, distant supervision using future ICD-9 diagnoses, and top-k extractive sentence ranking.

However, it is a partial reproduction of McInerney et al. (2020). The following components of the original work were not implemented or fully reproduced:

1. Original Model Variants

  • Diagnosis hierarchy-based query representations: The original paper explores incorporating diagnostic hierarchy information into query representations. Our implementation uses diagnosis-description queries with ClinicalBERT but does not reproduce the hierarchy-aware model variant.
  • Original model configurations: We implemented a PyHealth-compatible, query-conditioned attention architecture rather than reproducing every encoder, training configuration, and experimental variation described in the paper.

2. Original Clinical Evaluation

  • Radiologist-annotated sentence relevance: We did not reproduce the evaluation using expert-annotated sentence relevance labels.
  • Original summarization benchmarks: We did not reproduce the complete sentence-retrieval evaluation protocol, including all original model and baseline comparisons.

3. Dataset and Experimental Limitations

  • Full MIMIC-III clinical notes: Access to the credentialed clinical notes was unavailable during the project.
  • Synthetic historical records: We augmented the publicly available MIMIC-III demonstration dataset with synthetic historical admissions and clinical notes. These notes are not genuine patient-linked medical histories.
  • Small evaluation cohort: The matched-cohort test split contained only 30 examples, including three positive examples.
  • Clinical relevance: Although the model generates attention-based sentence rankings, we could not validate their clinical relevance against expert annotations.

4. Scope of Implemented Extensions

We implemented and evaluated a 30/90/365-day historical observation-window ablation and an additional frozen-versus-fine-tuned ClinicalBERT comparison.

These experiments demonstrate the functionality of the pipeline and investigate model behavior under different configurations. However, they do not establish that the implementation reproduces the clinical findings of the original paper.

How to Run

Install the dependencies required by PyHealth and the ClinicalBERT model.

Run the provided example from the repository root:

python examples/mimic3_query_focused_ehr_attention.py --help

The example provides options for dataset selection, model configuration, training, evaluation, and history-window experiments.

Full MIMIC-III data requires appropriate authorized access.

Summary

The contribution reproduces the central computational approach, not the complete experimental study.

Its primary deliverable is a reusable, tested PyHealth Task + Model implementation that can support more faithful evaluation when genuine longitudinal clinical notes and appropriate reference annotations become available.

@github-actions

github-actions Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Test Coverage

Total: 86.65% (47964 / 55355 lines)

Modified file Coverage Lines
pyhealth/models/__init__.py 100.00% 95 / 95
pyhealth/models/query_focused_ehr.py 90.64% 155 / 171
pyhealth/tasks/__init__.py 98.13% 105 / 107
pyhealth/tasks/query_focused_ehr.py 91.88% 147 / 160

Workflow run · 5c22bc3

@solarsys solarsys added the status: automatic The PR will go through automatic review process. label Nov 26, 2026
@solarsys

Copy link
Copy Markdown
Collaborator

/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 742cd07

@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 a query-focused EHR task and a ClinicalBERT attention model with an end-to-end example, API docs and thorough tests. Coverage is above the bar: 90.6% for the model file, 91.9% for the task file, and 86.6% for the whole repository. The change is self-contained, and the only edits to existing files are export lines in the two __init__.py files.

To get this merged:

  1. The model API doc (docs/api/models/pyhealth.models.QueryFocusedEHRModel.rst) says caching is "disabled when fine-tuning". The constructor actually raises ValueError when cache_embeddings=True and freeze_encoder=False. Please change the doc, or the code, so they agree. The model docstring says "Requires freeze_encoder=True", so rewording the doc to match is probably simplest.

Optional suggestions:

  • The default never_observed negative selection uses ICD codes from the whole patient record, including admissions after the target. The task docstring says so. Please also say it in the PR description, since it affects how the results should be read.
  • The reported ablation numbers come from an augmented demo dataset that others cannot regenerate. Consider adding a short note on how it was built.
  • The model is not tested through SampleDataset or a DataLoader. A small test of that would help.
  • The PR description repeats one sentence in the Contribution Type section.

Reviewed commit 742cd07

…nting the caching requirements with frozen and finetune options of ClinicalBERT
@rameshsudharshan

Copy link
Copy Markdown
Contributor 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 6f971d3

@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 a query-focused EHR task and a ClinicalBERT query-attention model, with an end-to-end example, docs and tests. It is close. The library code is well tested: coverage is 90.6% for the model file and 91.9% for the task file, and total repository coverage is 86.6%, so all of these meet the bar.

To get this merged:

  1. Fix how synthetic admissions become prediction targets. In --synthetic mode the example appends synthetic admissions to the ADMISSIONS table, and they have no diagnoses. QueryFocusedEHRTask.__call__ treats every admission after a patient's first as a target. Each synthetic admission after the first therefore produces label-0 samples for diagnosis groups the patient never had. These samples enter the 214-example, 25-positive cohort and confound the AUROC/AP results. Please exclude synthetic admissions as targets, for example by filtering the samples to the original admissions in the example. Alternatively, add a task option that restricts targets to admissions that have diagnosis records. Then re-run and update the reported numbers. The description already says the numbers have not been reproduced.
  2. Add a test for write_synthetic_augmented_demo. It is about 150 lines and untested. A small fake demo ZIP passed through --demo-zip would be enough. It should check the admission and note counts, the unique hadm_id values, that note timestamps fall before the target admission, and that the diagnosis rows are unchanged.

Optional suggestions:

  • The docs/api/models/pyhealth.models.QueryFocusedEHRModel.rst page says "inspired by". The description calls the work a partial reproduction, so you could state that limitation on the docs page too.
  • A short note in the example about the never_observed negative sampling using later admissions is already in the task docs. Mentioning it in the example would help users.

Reviewed commit 6f971d3

@rameshsudharshan

Copy link
Copy Markdown
Contributor 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 5c22bc3

continue

# Do not silently accept notes without timestamps.
if not isinstance(timestamp, datetime):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[medium] Notes without CHARTTIME are silently dropped, including the discharge summaries the example asks for

Notes whose timestamp is not a datetime are skipped here, and the timestamp comes from charttime (pyhealth/datasets/configs/mimic3.yaml). In MIMIC-III NOTEEVENTS, discharge summaries commonly have a null CHARTTIME (only CHARTDATE is set), so they would never contribute history. The example's default note_categories (examples/mimic3_query_focused_ehr_attention.py:398) includes "Discharge summary", which therefore likely does nothing on real data, and nothing in the docs says so. Please check this against real MIMIC-III data and either fall back to chartdate/storetime for timing, or document the exclusion and remove the category from the example defaults.

# Conservative strategy: select a negative only if
# the diagnosis group is never recorded for this patient.
# Groups observed at other admissions are excluded.
is_valid_negative = not bool(

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[medium] Default negative selection depends on later admissions, which the description does not disclose

With the default negative_sampling="never_observed", a group is a valid negative only if its codes appear nowhere in the patient's record, including admissions after the target. This uses future diagnoses to decide which samples exist, and it changes the class balance and the negative population used for the reported AUROC/AP. The PR description says the task "enforces temporal cutoffs to reduce future-information leakage" and does not mention this default. Please state this in the PR description and in the reported results, or consider making target_absent the default and documenting never_observed as a retrospective option.

baseline preprocessing. Clinical abbreviations and
templated reports may require more advanced segmentation.

Examples:

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] Examples block in split_clinical_sentences is misindented inside Notes

The Examples: heading sits at a different indent from the Notes section, so the rendered docstring will not show it as a separate section. Align it with the other section headings.

@@ -0,0 +1,1001 @@
"""Query-focused EHR summarization reproduction example.

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] Example is 1001 lines and mixes several concerns

The script contains synthetic data generators (CSV tables, direct samples, HashTokenizer, TinyEncoder), a TF-IDF baseline, cohort matching, and the ablation loop in one file. Trimming the synthetic generators or moving them out of the example would make the real pipeline easier to follow. The synthetic-mimic run also writes the MIMIC3Dataset cache to the default cache directory because cache_dir is not set, so each run leaves a new cache entry behind.

@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 this contribution, Sudharshan and Rejaul. It adds a QueryFocusedEHRTask and a ClinicalBERT-based QueryFocusedEHRModel for diagnosis-conditioned sentence attention over MIMIC-III history. It also adds an end-to-end example with a TF-IDF baseline and history-window ablation, API docs, and tests. The description is candid about its limits: synthetic notes, a small test split, and a partial reproduction of the paper.

This looks ready to merge.

  • Scope: The change adds two new components and registers them in pyhealth/models/init.py and pyhealth/tasks/init.py. It doesn't change BaseModel or BaseTask, and it doesn't remove, rename or rebind any existing export. Neither component depends on another concrete component.
  • Coverage: The new files are above the 80% bar. pyhealth/models/query_focused_ehr.py is at 90.6% and pyhealth/tasks/query_focused_ehr.py is at 91.9%. The two modified init.py files are at 100% and 98.1%. Whole-repository coverage is 86.65%, above the 60% bar.
  • Docs and description: The API pages match the code, including the negative_sampling modes and the cache restriction that requires freeze_encoder=True. The description matches what the diff does.

Optional suggestions:

  • The example script is about 1,000 lines. You could move the synthetic MIMIC table generator into a helper or the tests, so the example stays focused.
  • normalize_icd in the example duplicates normalize_icd9 in the task module. Copying is fine, but a short comment would help readers.
  • In the model's forward docstring, you could say how the model is meant to be used with Trainer and a SampleDataset. Your example uses a custom training loop.
  • The history-window results are exploratory, with only three positive test examples. Keep that caveat close to the results table in the docs too.

Reviewed commit 5c22bc3

@rameshsudharshan

Copy link
Copy Markdown
Contributor Author

/merge

@github-actions

Copy link
Copy Markdown

Can't merge yet: GitHub refused the merge (HTTP 403): Resource not accessible by integration

@rameshsudharshan

Copy link
Copy Markdown
Contributor Author

/merge

Sorry about that, I read in the CONTRIBUTING.md ("Once the AI approves your latest commit, comment /merge to merge your pull request into PyHealth yourself.")

didn't intend to cause any issues

@solarsys
solarsys merged commit 3ffb562 into sunlabuiuc:master Nov 27, 2026
3 checks passed
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.

2 participants