Skip to content

MedMod in-hospital mortality (2/4): Early Fusion and ConVIRT models - #1638

Merged
github-actions[bot] merged 4 commits into
sunlabuiuc:masterfrom
Rainie-Hu:medmod-ihm-models
Nov 27, 2026
Merged

github-actions[bot] merged 4 commits into
sunlabuiuc:masterfrom
Rainie-Hu:medmod-ihm-models

Conversation

@Rainie-Hu

@Rainie-Hu Rainie-Hu commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Contributors: Yuqing Hu (GT username yhu672, yhu672@gatech.edu) and Hanh Trang Do (GT username hdo61, hdo61@gatech.edu), Georgia Tech CSE 6250

Contribution Type: Model (part 2 of the Full Pipeline contribution #1609)

Part 2 of 4 of #1609. #1609 was too large for review, so it is split into: 1. dataset, task and processor (#1637); 2. models (this PR); 3. image tools, synthetic data, MedSigLIP embeddings, pretraining samples, examples and results (#1639, draft until 1 and 2 merge); 4. runner scripts and Colab notebook (#1640, draft until 3 merges). This PR needs nothing from the others.

Paper: Elsharief, S., et al. (2025). MedMod: Multimodal Benchmark for Medical Prediction Tasks with Electronic Health Records and Chest X-Ray Scans. CHIL 2025, PMLR 287. https://proceedings.mlr.press/v287/elsharief25a.html (code: https://github.com/nyuad-cai/MedMod)

What it adds:

  • EHRCXREarlyFusion: EHR LSTM + ResNet-34. The encoders take pretrained weights as state dicts and are frozen by default, as in the paper's Early Fusion.
  • ConVIRT: contrastive pretraining of an EHR LSTM and a ResNet-34.
  • ConVIRTLinearProbe: a linear probe on the frozen ConVIRT encoders.
  • Both models accept any image encoder module instead of the ResNet-34 (cxr_backbone, with its output size cxr_feature_dim). The MedSigLIP extension passes nn.Identity() and feeds stored embeddings. The code that computes the embeddings comes in part 3.

Difference from PyHealth's MedFuse model: MedFuse fuses the two modalities with an LSTM over the EHR and image features and trains its encoders. EHRCXREarlyFusion projects the image feature, concatenates it with the EHR feature and trains only the projection and a linear classifier, on top of frozen pretrained encoders, as in the MedMod paper.

Links to other components: ConVIRT reuses build_resnet and value_tensor from ehr_cxr_early_fusion.py (our own Early Fusion model, added in this PR), so both models build the ResNet and read inputs the same way. Neither model imports or changes existing models.

Files to review:

  • pyhealth/models/ehr_cxr_early_fusion.py - Early Fusion model
  • pyhealth/models/convirt.py - ConVIRT and the linear probe
  • tests/core/test_ehr_cxr_early_fusion.py, tests/core/test_convirt.py - tests
  • registration in pyhealth/models/__init__.py; docs pages for both models and their index entries

Testing: all 40 tests pass on small sample datasets of random tensors, with no network access. python tools/check_pr_rules.py passes.

🤖 Generated with Claude Code

Part 2 of 4 of sunlabuiuc#1609.

Co-authored-by: rainiehu <57816421+Rainie-Hu@users.noreply.github.com>
@Rainie-Hu Rainie-Hu changed the title Part 2 of 4 of sunlabuiuc/PyHealth#1609. Add the Early Fusion and ConVIRT models for MedMod Nov 27, 2026
@solarsys solarsys added the status: automatic The PR will go through automatic review process. label Nov 27, 2026
@github-actions

github-actions Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

Test Coverage

Total: 87.07% (50242 / 57702 lines)

Modified file Coverage Lines
pyhealth/models/__init__.py 100.00% 101 / 101
pyhealth/models/convirt.py 96.18% 151 / 157
pyhealth/models/ehr_cxr_early_fusion.py 93.33% 98 / 105

Workflow run · f655949

@solarsys

Copy link
Copy Markdown
Collaborator

/review

@Rainie-Hu Rainie-Hu changed the title Add the Early Fusion and ConVIRT models for MedMod MedMod in-hospital mortality (2/4): Early Fusion and ConVIRT models Nov 27, 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 30e0c15

@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 EHRCXREarlyFusion, ConVIRT and ConVIRTLinearProbe from the MedMod paper, with docs and tests. It is close. Coverage is good: the whole repository is at 87.07%, convirt.py at 95.45% and ehr_cxr_early_fusion.py at 93.14%, all above the bar. The link where ConVIRT reuses build_resnet and value_tensor is named in your description with a reason.

To get this merged:

  1. Put frozen encoders in eval mode when the model is built, not only when train() or eval() is called. A freshly constructed EHRCXREarlyFusion (with freeze_encoders=True) or ConVIRTLinearProbe starts in PyTorch's default training mode. If you call model(**batch) directly, the frozen LSTM applies dropout and the frozen ResNet updates its BatchNorm running statistics. That contradicts the docstrings. Trainer calls train() each epoch, so it is not affected. The fix is to call self.train(self.training), or self.train(), at the end of each __init__. Please also add a test that runs a direct forward pass on a fresh model, without calling train() first, and checks that the BatchNorm running statistics are unchanged. The current tests call train() first, so they miss this.

Optional suggestions:

  • In EHRCXREarlyFusion, raise a ValueError when augment_cxr=True is combined with a module backbone such as nn.Identity(). ConVIRT already does this check.
  • EHRCXREarlyFusion ignores the lengths of padded EHR input, while ConVIRT packs the sequences. Either handle it the same way or mention it in the docstring.
  • The description says "pretrained encoders", but the default encoders are untrained and need ehr_state_dict and cxr_state_dict. A short note would help readers.
  • The docstring comparison with MedFuse's code is hard for a reader to check. You could shorten it.

Reviewed commit 30e0c15

@Rainie-Hu

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 fc72944

@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 the MedMod Early Fusion model (EHRCXREarlyFusion), ConVIRT contrastive pretraining, and a ConVIRTLinearProbe. It comes with docs and 37 tests. The change is close. The description names the link from convirt.py to build_resnet and value_tensor, and it gives the paper link. Coverage is 95.5% for convirt.py, 93.3% for ehr_cxr_early_fusion.py and 87% for the whole repository. That meets the bar.

To get this merged:

  • info_nce_loss (convirt.py) raises ValueError when the batch has fewer than 2 samples. get_dataloader does not drop the last partial batch. If the dataset size leaves a final batch of one sample, ConVIRT pretraining with the Trainer will crash at the end of an epoch. Please handle this case. For example, skip the loss for that batch, or return a zero loss that keeps the graph. If you would rather not change the behaviour, say clearly in the docs how to avoid the crash and make the example loaders use drop_last. Please add a test for the single-sample final batch.

Optional suggestions:

  • The "48 hourly bins" example in the ehr_feature_key docstring of EHRCXREarlyFusion doesn't match the task's default bin_hours=2, which gives 24 steps. Please align it.
  • The cxr_feature_key note in the same docstring is hard to follow. A shorter wording would help.
  • With augment_cxr=True, the colour jitter clamps ImageNet-normalized inputs, unless cxr_mean and cxr_std are passed. Please say so in the docs.
  • The padded-lengths packing path in ConVIRT isn't produced by any task in this PR. A short note on which task or caller uses it would help.

Reviewed commit fc72944

@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 5bbfa4f

@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 EHRCXREarlyFusion, ConVIRT and ConVIRTLinearProbe from the MedMod paper, with docs and a thorough test suite. Coverage is well above the bar: 95.5% for convirt.py, 93.3% for ehr_cxr_early_fusion.py and 87% for the repository. The models are self-contained. ConVIRT reuses build_resnet and value_tensor from your Early Fusion file, and the description explains this. The change is close to ready.

To get this merged:

  1. The ConVIRT docstring (the ehr_feature_key argument) refers to MedModEHRSequenceProcessor from #1637, which isn't in this repository. The description says this PR needs nothing from the others. Please reword the docstring so it doesn't depend on an unmerged PR. For example, say that any processor with a ("value", "lengths") schema works, and drop the PR reference.
  2. The ConVIRT docstring says a one-sample batch "changes nothing". That isn't strictly true. In train mode the ResNet's BatchNorm statistics update, and optimizer momentum or weight decay can still move the weights. A tiny image can also make BatchNorm raise an error. Please soften the wording, for example "contributes no gradient from the loss", and recommend drop_last=True.
  3. The cxr_mean/cxr_std un-normalization path has no test. Please add one that checks that the encoder input is un-normalized, for example that passing normalized images with IMAGENET_MEAN and IMAGENET_STD gives the same embeddings as the raw images without them.

Optional suggestions:

  • EHRCXREarlyFusion doesn't read cxr_mask. Unpaired stays get zero images when paired_only=False. You document this, and a one-line warning in the class docs might help.
  • augment_cxr=True with cxr_feature_key=None does nothing. You could raise an error in that case.

Reviewed commit 5bbfa4f

…on test

The ehr_feature_key docstring no longer names a processor from an
unmerged PR. The one-sample batch note now says the batch gives no gradient
but is not a full no-op (BatchNorm statistics, optimizer momentum). A new
test checks that cxr_mean and cxr_std undo ImageNet normalization.

Co-authored-by: rainiehu <57816421+Rainie-Hu@users.noreply.github.com>
@Rainie-Hu

Copy link
Copy Markdown
Contributor Author

/review

1 similar comment
@Rainie-Hu

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 f655949

parameter.requires_grad = False

self.classifier = nn.Linear(classifier_in, self.label_processor.output_size())
self.augmentation = self._build_augmentation() if augment_cxr else None

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] augment_cxr is silently ignored in EHR-only mode

When cxr_feature_key is None the model has no image encoder, but line 229 still builds the augmentation pipeline whenever augment_cxr=True, and the check at line 178 does not reject that combination. The flag does nothing and the caller is not told. Either raise a ValueError for augment_cxr with cxr_feature_key=None, or build the augmentation only when cxr_feature_key is not None.


The model expects samples that have an image. With
:class:`~pyhealth.tasks.EHRCXRMortalityMIMIC4` use ``paired_only=True``,
or select the samples with ``cxr_mask == 1``.

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] Model ignores cxr_mask, so default task settings feed zero images

EHRCXRMortalityMIMIC4 defaults to paired_only=False, so unpaired stays reach this model with an all-zero image and cxr_mask=0. The model never reads cxr_mask, so those stays are scored as if they had an image. The docstring states this and gives the workaround. Consider either reading cxr_mask in forward or documenting paired_only=True as the required setting for this model.

@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. It adds EHRCXREarlyFusion, ConVIRT and ConVIRTLinearProbe, which are MedMod's Early Fusion and contrastive pretraining baselines. Each comes with docs and tests. It looks ready to merge.

  • Self-contained: The change only adds new models, their docs and their exports. It doesn't modify base classes or other shared code.
  • Sharing: ConVIRT reuses build_resnet and value_tensor from ehr_cxr_early_fusion.py. The description names this link and gives a reason for it.
  • Difference from MedFuse: The description explains how this model differs from PyHealth's MedFuse, so it doesn't duplicate an existing component.
  • Coverage: convirt.py is at 96.18% and ehr_cxr_early_fusion.py at 93.33%, both above the 80% bar. The whole repository is at 87.07%, above the 60% bar.
  • Docs: The docs match the code.

Optional suggestions:

  • augment_cxr=True is silently ignored when cxr_feature_key=None. You could raise a ValueError instead.
  • EHRCXREarlyFusion ignores cxr_mask. This is documented, but a short warning in the docstring example might help users of unpaired data.

Reviewed commit f655949

@Rainie-Hu

Copy link
Copy Markdown
Contributor Author

/merge

@github-actions
github-actions Bot merged commit 1aaeaea into sunlabuiuc:master Nov 27, 2026
3 checks passed
NathanCYee pushed a commit to NathanCYee/PyHealth that referenced this pull request Nov 28, 2026
…unlabuiuc#1638)

* Add the Early Fusion and ConVIRT models for MedMod

Part 2 of 4 of sunlabuiuc#1609.

Co-authored-by: rainiehu <57816421+Rainie-Hu@users.noreply.github.com>

* Put frozen encoders in eval mode at construction; reject augmentation without images

* Handle a one-sample ConVIRT batch; clarify EHR length, EHR-only and augmentation docs

* Address the third AI review of part 2: ConVIRT docs and a normalization test

The ehr_feature_key docstring no longer names a processor from an
unmerged PR. The one-sample batch note now says the batch gives no gradient
but is not a full no-op (BatchNorm statistics, optimizer momentum). A new
test checks that cxr_mean and cxr_std undo ImageNet normalization.

Co-authored-by: rainiehu <57816421+Rainie-Hu@users.noreply.github.com>

---------

Co-authored-by: dhtrg <87437721+dhtrg@users.noreply.github.com>
dhtrg added a commit to Rainie-Hu/PyHealth that referenced this pull request Nov 30, 2026
Same code as sunlabuiuc#1637-sunlabuiuc#1640 after their reviews. sunlabuiuc#1638 is merged as 1aaeaea.

Co-authored-by: rainiehu <57816421+Rainie-Hu@users.noreply.github.com>
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.

3 participants