Repository navigation
MedMod in-hospital mortality (2/4): Early Fusion and ConVIRT models - #1638
Conversation
Part 2 of 4 of sunlabuiuc#1609. Co-authored-by: rainiehu <57816421+Rainie-Hu@users.noreply.github.com>
Test CoverageTotal: 87.07% (50242 / 57702 lines)
|
|
/review |
|
/review |
There was a problem hiding this comment.
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:
- Put frozen encoders in eval mode when the model is built, not only when
train()oreval()is called. A freshly constructedEHRCXREarlyFusion(withfreeze_encoders=True) orConVIRTLinearProbestarts in PyTorch's default training mode. If you callmodel(**batch)directly, the frozen LSTM applies dropout and the frozen ResNet updates its BatchNorm running statistics. That contradicts the docstrings.Trainercallstrain()each epoch, so it is not affected. The fix is to callself.train(self.training), orself.train(), at the end of each__init__. Please also add a test that runs a direct forward pass on a fresh model, without callingtrain()first, and checks that the BatchNorm running statistics are unchanged. The current tests calltrain()first, so they miss this.
Optional suggestions:
- In
EHRCXREarlyFusion, raise a ValueError whenaugment_cxr=Trueis combined with a module backbone such asnn.Identity(). ConVIRT already does this check. EHRCXREarlyFusionignores thelengthsof 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_dictandcxr_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
|
/review |
There was a problem hiding this comment.
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) raisesValueErrorwhen the batch has fewer than 2 samples.get_dataloaderdoes not drop the last partial batch. If the dataset size leaves a final batch of one sample,ConVIRTpretraining 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 usedrop_last. Please add a test for the single-sample final batch.
Optional suggestions:
- The "48 hourly bins" example in the
ehr_feature_keydocstring ofEHRCXREarlyFusiondoesn't match the task's defaultbin_hours=2, which gives 24 steps. Please align it. - The
cxr_feature_keynote in the same docstring is hard to follow. A shorter wording would help. - With
augment_cxr=True, the colour jitter clamps ImageNet-normalized inputs, unlesscxr_meanandcxr_stdare passed. Please say so in the docs. - The padded-lengths packing path in
ConVIRTisn't produced by any task in this PR. A short note on which task or caller uses it would help.
Reviewed commit fc72944
|
/review |
There was a problem hiding this comment.
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:
- The ConVIRT docstring (the
ehr_feature_keyargument) refers toMedModEHRSequenceProcessorfrom #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. - 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.
- The
cxr_mean/cxr_stdun-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 whenpaired_only=False. You document this, and a one-line warning in the class docs might help. augment_cxr=Truewithcxr_feature_key=Nonedoes 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>
|
/review |
1 similar comment
|
/review |
| 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 |
There was a problem hiding this comment.
[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``. |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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_resnetandvalue_tensorfromehr_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.pyis at 96.18% andehr_cxr_early_fusion.pyat 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=Trueis silently ignored whencxr_feature_key=None. You could raise a ValueError instead.EHRCXREarlyFusionignorescxr_mask. This is documented, but a short warning in the docstring example might help users of unpaired data.
Reviewed commit f655949
|
/merge |
…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>
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>
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.cxr_backbone, with its output sizecxr_feature_dim). The MedSigLIP extension passesnn.Identity()and feeds stored embeddings. The code that computes the embeddings comes in part 3.Difference from PyHealth's MedFuse model:
MedFusefuses the two modalities with an LSTM over the EHR and image features and trains its encoders.EHRCXREarlyFusionprojects 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:
ConVIRTreusesbuild_resnetandvalue_tensorfromehr_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 modelpyhealth/models/convirt.py- ConVIRT and the linear probetests/core/test_ehr_cxr_early_fusion.py,tests/core/test_convirt.py- testspyhealth/models/__init__.py; docs pages for both models and their index entriesTesting: all 40 tests pass on small sample datasets of random tensors, with no network access.
python tools/check_pr_rules.pypasses.🤖 Generated with Claude Code