From 30e0c1586202da9e4ad9a416a0de7c261c2808a9 Mon Sep 17 00:00:00 2001 From: dhtrg <87437721+dhtrg@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:42:40 -0500 Subject: [PATCH 1/4] Add the Early Fusion and ConVIRT models for MedMod Part 2 of 4 of sunlabuiuc/PyHealth#1609. Co-authored-by: rainiehu <57816421+Rainie-Hu@users.noreply.github.com> --- docs/api/models.rst | 2 + docs/api/models/pyhealth.models.ConVIRT.rst | 21 + .../pyhealth.models.EHRCXREarlyFusion.rst | 14 + pyhealth/models/__init__.py | 2 + pyhealth/models/convirt.py | 467 ++++++++++++++++++ pyhealth/models/ehr_cxr_early_fusion.py | 310 ++++++++++++ tests/core/test_convirt.py | 276 +++++++++++ tests/core/test_ehr_cxr_early_fusion.py | 168 +++++++ 8 files changed, 1260 insertions(+) create mode 100644 docs/api/models/pyhealth.models.ConVIRT.rst create mode 100644 docs/api/models/pyhealth.models.EHRCXREarlyFusion.rst create mode 100644 pyhealth/models/convirt.py create mode 100644 pyhealth/models/ehr_cxr_early_fusion.py create mode 100644 tests/core/test_convirt.py create mode 100644 tests/core/test_ehr_cxr_early_fusion.py diff --git a/docs/api/models.rst b/docs/api/models.rst index 2f00a013fa..7e6ef931bb 100644 --- a/docs/api/models.rst +++ b/docs/api/models.rst @@ -336,6 +336,8 @@ API Reference models/pyhealth.models.Agent models/pyhealth.models.GRASP models/pyhealth.models.MedFuse + models/pyhealth.models.EHRCXREarlyFusion + models/pyhealth.models.ConVIRT models/pyhealth.models.MAESTRO models/pyhealth.models.DAFT models/pyhealth.models.DiPro diff --git a/docs/api/models/pyhealth.models.ConVIRT.rst b/docs/api/models/pyhealth.models.ConVIRT.rst new file mode 100644 index 0000000000..37d5cf3bba --- /dev/null +++ b/docs/api/models/pyhealth.models.ConVIRT.rst @@ -0,0 +1,21 @@ +pyhealth.models.ConVIRT +======================= + +ConVIRT contrastive pretraining of an EHR LSTM and a chest X-ray ResNet, and +a linear probe on the frozen encoders, as evaluated in MedMod. + +Reference: Elsharief et al., "MedMod: Multimodal Benchmark for Medical +Prediction Tasks with Electronic Health Records and Chest X-Ray Scans." +CHIL 2025. https://proceedings.mlr.press/v287/elsharief25a.html + +.. autoclass:: pyhealth.models.ConVIRT + :members: + :undoc-members: + :show-inheritance: + +.. autoclass:: pyhealth.models.ConVIRTLinearProbe + :members: + :undoc-members: + :show-inheritance: + +.. autofunction:: pyhealth.models.convirt.info_nce_loss diff --git a/docs/api/models/pyhealth.models.EHRCXREarlyFusion.rst b/docs/api/models/pyhealth.models.EHRCXREarlyFusion.rst new file mode 100644 index 0000000000..da4963da85 --- /dev/null +++ b/docs/api/models/pyhealth.models.EHRCXREarlyFusion.rst @@ -0,0 +1,14 @@ +pyhealth.models.EHRCXREarlyFusion +================================= + +Early fusion of an EHR LSTM and a chest X-ray ResNet, the Early Fusion +baseline of MedMod for in-hospital mortality. + +Reference: Elsharief et al., "MedMod: Multimodal Benchmark for Medical +Prediction Tasks with Electronic Health Records and Chest X-Ray Scans." +CHIL 2025. https://proceedings.mlr.press/v287/elsharief25a.html + +.. autoclass:: pyhealth.models.EHRCXREarlyFusion + :members: + :undoc-members: + :show-inheritance: diff --git a/pyhealth/models/__init__.py b/pyhealth/models/__init__.py index b62e102ada..72490e2be0 100644 --- a/pyhealth/models/__init__.py +++ b/pyhealth/models/__init__.py @@ -61,6 +61,8 @@ from .daft import DAFT as DAFT, DAFTBlock as DAFTBlock, DAFTLayer as DAFTLayer from .maestro import MAESTRO as MAESTRO from .medfuse import MedFuse, MedFuseLayer +from .ehr_cxr_early_fusion import EHRCXREarlyFusion as EHRCXREarlyFusion +from .convirt import ConVIRT as ConVIRT, ConVIRTLinearProbe as ConVIRTLinearProbe from .medlink import MedLink from .micron import MICRON, MICRONLayer from .mlp import MLP diff --git a/pyhealth/models/convirt.py b/pyhealth/models/convirt.py new file mode 100644 index 0000000000..ee541b9495 --- /dev/null +++ b/pyhealth/models/convirt.py @@ -0,0 +1,467 @@ +# Authors: Yuqing Hu (yhu672@gatech.edu), Hanh Trang Do (hdo61@gatech.edu) +# Paper: MedMod: Multimodal Benchmark for Medical Prediction Tasks with +# Electronic Health Records and Chest X-Ray Scans (Elsharief et al., 2025) +# https://proceedings.mlr.press/v287/elsharief25a.html +# Description: ConVIRT contrastive pretraining of an EHR LSTM and a chest +# X-ray ResNet, and a linear probe on the frozen encoders. + +from __future__ import annotations + +import copy +from collections.abc import Sequence + +import torch +import torch.nn.functional as F +from torch import nn +from torch.utils.data import DataLoader +from torchvision import transforms + +from pyhealth.datasets import SampleDataset +from pyhealth.models.base_model import BaseModel +from pyhealth.models.ehr_cxr_early_fusion import build_resnet, value_tensor + +IMAGENET_MEAN = (0.485, 0.456, 0.406) +IMAGENET_STD = (0.229, 0.224, 0.225) + + +def info_nce_loss( + z_ehr: torch.Tensor, z_cxr: torch.Tensor, temperature: float = 0.01 +) -> torch.Tensor: + """Bidirectional InfoNCE loss between paired EHR and image embeddings. + + Row ``i`` of ``z_ehr`` and row ``i`` of ``z_cxr`` are a positive pair, and + every other row of the batch is a negative. The cosine similarities are + divided by ``temperature``. As in the MedMod code, the denominator of each + term holds the negatives only: the positive pair is masked out of it. + + Args: + z_ehr: EHR embeddings, ``[batch, dim]``. + z_cxr: Image embeddings, ``[batch, dim]``. + temperature: Softmax temperature. + + Returns: + The mean loss, a scalar. + + Examples: + >>> z = torch.eye(3) + >>> bool(info_nce_loss(z, z, temperature=0.5) < info_nce_loss(z, z.flip(0))) + True + """ + if z_ehr.shape != z_cxr.shape or z_ehr.dim() != 2: + raise ValueError("z_ehr and z_cxr must both have shape [batch, dim].") + if z_ehr.size(0) < 2: + raise ValueError("InfoNCE needs at least 2 samples per batch.") + similarity = ( + F.normalize(z_cxr, dim=-1) @ F.normalize(z_ehr, dim=-1).T + ) / temperature + positive = torch.eye(similarity.size(0), dtype=torch.bool, device=z_ehr.device) + negatives = similarity.masked_fill(positive, -9e15) + cxr_to_ehr = similarity[positive] - torch.logsumexp(negatives, dim=1) + ehr_to_cxr = similarity[positive] - torch.logsumexp(negatives, dim=0) + return -(cxr_to_ehr + ehr_to_cxr).mean() + + +class _SimCLRAugmentation(nn.Module): + """SimCLRv2-style augmentation of one image, as in the MedMod code. + + Random affine, random crop of 60 to 100% of the side, resize back, random + flip, colour jitter (80% of the time) and random grayscale. It expects + pixel values in ``[0, 1]``. + """ + + def __init__(self) -> None: + super().__init__() + self.affine = transforms.RandomAffine( + degrees=(-45, 45), translate=(0.1, 0.1), scale=(0.7, 1.5), shear=(-25, 25) + ) + self.flip = transforms.RandomHorizontalFlip() + self.jitter = transforms.ColorJitter(0.8, 0.8, 0.8, 0.2) + self.gray = transforms.RandomGrayscale(p=0.2) + + def forward(self, image: torch.Tensor) -> torch.Tensor: + size = image.shape[-1] + image = self.affine(image) + crop = int(torch.empty(1).uniform_(0.6 * size, size).item()) + image = transforms.RandomCrop(crop)(image) + image = transforms.functional.resize(image, [size, size], antialias=True) + image = self.flip(image) + if torch.rand(1).item() < 0.8: + image = self.jitter(image) + return self.gray(image) + + +class _ConVIRTEncoders(nn.Module): + """The EHR LSTM and the image ResNet of ConVIRT. + + Returns the encoder outputs, which are the features that the linear probe + reads, before the projection heads. + """ + + def __init__( + self, + ehr_dim: int, + ehr_hidden_dim: int, + ehr_num_layers: int, + cxr_backbone: str | nn.Module, + cxr_feature_dim: int | None, + augment_cxr: bool, + cxr_mean: Sequence[float] | None, + cxr_std: Sequence[float] | None, + ) -> None: + super().__init__() + self.ehr_encoder = nn.LSTM( + ehr_dim, ehr_hidden_dim, ehr_num_layers, batch_first=True + ) + self._init_lstm(self.ehr_encoder) + if isinstance(cxr_backbone, str): + self.cxr_encoder, self.cxr_dim = build_resnet(cxr_backbone) + else: + self.cxr_encoder, self.cxr_dim = cxr_backbone, cxr_feature_dim + self.ehr_dim = ehr_hidden_dim + self.augmentation = _SimCLRAugmentation() if augment_cxr else None + self.register_buffer( + "cxr_mean", + None if cxr_mean is None else torch.tensor(cxr_mean).view(1, -1, 1, 1), + ) + self.register_buffer( + "cxr_std", + None if cxr_std is None else torch.tensor(cxr_std).view(1, -1, 1, 1), + ) + + @staticmethod + def _init_lstm(lstm: nn.LSTM) -> None: + """Orthogonal recurrent weights, as in the MedMod EHR encoder.""" + for name, parameter in lstm.named_parameters(): + if name.startswith("weight_hh"): + nn.init.orthogonal_(parameter) + elif name.startswith("weight_ih"): + nn.init.xavier_uniform_(parameter) + else: + nn.init.zeros_(parameter) + + def forward( + self, + ehr: torch.Tensor, + cxr: torch.Tensor, + lengths: torch.Tensor | None = None, + ) -> tuple[torch.Tensor, torch.Tensor]: + if lengths is not None: + # Zero-padded stays of different lengths: packing makes the LSTM + # stop at each stay's last bin, as MedMod's EHR encoder does. + ehr = nn.utils.rnn.pack_padded_sequence( + ehr, lengths.cpu(), batch_first=True, enforce_sorted=False + ) + if self.cxr_mean is not None: + # MedMod feeds ConVIRT pixel values in [0, 1], without ImageNet + # normalization, so undo the normalization of the input. + cxr = cxr * self.cxr_std + self.cxr_mean + if self.augmentation is not None and self.training: + cxr = torch.stack([self.augmentation(image) for image in cxr]) + _, (hidden, _) = self.ehr_encoder(ehr) + return hidden[-1], self.cxr_encoder(cxr) + + +def _projection_head(in_dim: int, dim: int) -> nn.Sequential: + """Linear-ReLU-Linear-ReLU-Linear (no bias), as the MedMod heads.""" + return nn.Sequential( + nn.Linear(in_dim, dim), + nn.ReLU(inplace=True), + nn.Linear(dim, dim), + nn.ReLU(inplace=True), + nn.Linear(dim, dim, bias=False), + ) + + +class ConVIRT(BaseModel): + """ConVIRT contrastive pretraining of an EHR LSTM and a chest X-ray ResNet. + + The EHR time series and the image of the same ICU stay are two views of + one sample. Each encoder is followed by a projection head, and + :func:`info_nce_loss` pulls the two embeddings of a stay together and + pushes those of different stays apart. Both encoders start from random + weights. Labels are not used. + + The model scores no label, so :class:`~pyhealth.trainer.Trainer` trains it + on the loss alone and reports the validation loss. Follow it with + :class:`ConVIRTLinearProbe`. + + Paper: + Zhang et al. (2022). Contrastive Learning of Medical Visual + Representations from Paired Images and Text. MLHC 2022. Setup as in + MedMod (Elsharief et al., 2025). + + Args: + dataset: Sample dataset used for model configuration. + ehr_feature_key: Input key of the EHR tensor ``[batch, time, dim]``. + cxr_feature_key: Key of the image input in the batch: an image tensor + ``[batch, 3, H, W]`` for a ResNet, or ``[batch, cxr_feature_dim]`` + embeddings with ``cxr_backbone=nn.Identity()``. It need not be a + dataset input: a training loop can load the images (or look up + the embeddings) of each batch and add them under this key. + ehr_hidden_dim: Hidden size of the LSTM. + ehr_num_layers: Number of LSTM layers. + projection_dim: Size of the embeddings the loss compares. + temperature: Temperature of the InfoNCE loss. + cxr_backbone: ``"resnet18"``, ``"resnet34"`` or ``"resnet50"`` for an + untrained ResNet, or a module that maps the image input to + ``[batch, cxr_feature_dim]``. Pass ``nn.Identity()`` to feed + precomputed image embeddings (e.g. frozen MedSigLIP, 1,152 values) + under ``cxr_feature_key``. A module is used as given, so freeze + it beforehand if it should not train. + cxr_feature_dim: Output size of ``cxr_backbone`` when it is a module. + Leave it unset for a ResNet name, which sets its own size. + augment_cxr: Whether to augment images in training mode, with the + SimCLRv2-style transforms of MedMod. + cxr_mean: Mean the images were normalized with, to undo before + encoding, as MedMod feeds ConVIRT pixel values in ``[0, 1]``. + Default None for images that are not normalized. For + ImageNet-normalized images pass :data:`IMAGENET_MEAN`. + cxr_std: Standard deviation the images were normalized with, e.g. + :data:`IMAGENET_STD`. Default None. + + Examples: + >>> from pyhealth.datasets import create_sample_dataset, get_dataloader + >>> samples = [ + ... { + ... "patient_id": f"p{i}", + ... "visit_id": f"v{i}", + ... "ehr": torch.randn(4, 6).tolist(), + ... "cxr": torch.randn(3, 32, 32).tolist(), + ... "label": i % 2, + ... } + ... for i in range(4) + ... ] + >>> dataset = create_sample_dataset( + ... samples=samples, + ... input_schema={"ehr": "tensor", "cxr": "tensor"}, + ... output_schema={"label": "binary"}, + ... ) + >>> model = ConVIRT(dataset, ehr_hidden_dim=8, projection_dim=8, + ... cxr_backbone="resnet18") + >>> batch = next(iter(get_dataloader(dataset, batch_size=4))) + >>> model(**batch)["loss"].dim() + 0 + """ + + def __init__( + self, + dataset: SampleDataset, + ehr_feature_key: str = "ehr", + cxr_feature_key: str = "cxr", + ehr_hidden_dim: int = 128, + ehr_num_layers: int = 1, + projection_dim: int = 128, + temperature: float = 0.01, + cxr_backbone: str | nn.Module = "resnet34", + cxr_feature_dim: int | None = None, + augment_cxr: bool = False, + cxr_mean: Sequence[float] | None = None, + cxr_std: Sequence[float] | None = None, + ) -> None: + super().__init__(dataset=dataset) + if temperature <= 0: + raise ValueError("temperature must be positive.") + if isinstance(cxr_backbone, str) and cxr_feature_dim is not None: + raise ValueError( + "cxr_feature_dim is only for a module backbone; a ResNet sets " + "its own output size." + ) + if not isinstance(cxr_backbone, str): + if cxr_feature_dim is None: + raise ValueError("cxr_feature_dim is required for a module.") + if augment_cxr or cxr_mean is not None: + raise ValueError("Augmentation and un-normalization need images.") + if (cxr_mean is None) != (cxr_std is None): + raise ValueError("Pass both cxr_mean and cxr_std, or neither.") + if ehr_feature_key not in self.feature_keys: + raise ValueError( + f"ehr_feature_key '{ehr_feature_key}' is not an input of the " + f"dataset: {self.feature_keys}." + ) + self.ehr_feature_key = ehr_feature_key + self.cxr_feature_key = cxr_feature_key + self.temperature = temperature + + self.encoders = _ConVIRTEncoders( + _infer_ehr_dim(dataset, ehr_feature_key), + ehr_hidden_dim, + ehr_num_layers, + cxr_backbone, + cxr_feature_dim, + augment_cxr, + cxr_mean, + cxr_std, + ) + self.ehr_head = _projection_head(ehr_hidden_dim, projection_dim) + self.cxr_head = _projection_head(self.encoders.cxr_dim, projection_dim) + + @property + def label_processors(self) -> dict: + """No label is scored, so the trainer reports the loss only.""" + return {} + + def forward( + self, **kwargs: torch.Tensor | tuple[torch.Tensor, ...] + ) -> dict[str, torch.Tensor]: + """Forward propagation. + + Args: + **kwargs: Inputs by key: the EHR tensor and the image tensor. + + Returns: + A dictionary with ``loss`` and the embeddings ``z_ehr`` and + ``z_cxr``. + """ + ehr = value_tensor( + self.dataset, self.ehr_feature_key, kwargs[self.ehr_feature_key] + ) + cxr = value_tensor( + self.dataset, self.cxr_feature_key, kwargs[self.cxr_feature_key] + ) + lengths = _ehr_lengths( + self.dataset, self.ehr_feature_key, kwargs[self.ehr_feature_key] + ) + v_ehr, v_cxr = self.encoders( + ehr.to(self.device).float(), cxr.to(self.device).float(), lengths + ) + z_ehr, z_cxr = self.ehr_head(v_ehr), self.cxr_head(v_cxr) + loss = info_nce_loss(z_ehr, z_cxr, self.temperature) + return {"loss": loss, "z_ehr": z_ehr, "z_cxr": z_cxr} + + +def _ehr_lengths( + dataset: SampleDataset, key: str, feature: torch.Tensor | tuple[torch.Tensor, ...] +) -> torch.Tensor | None: + """The true lengths of zero-padded EHR, or None for fixed-length EHR.""" + if isinstance(feature, torch.Tensor): + return None + schema = dataset.input_processors[key].schema() + return feature[schema.index("lengths")] if "lengths" in schema else None + + +def _infer_ehr_dim(dataset: SampleDataset, key: str) -> int: + """Infers the EHR feature size from the first processed sample.""" + for sample in dataset: + if key in sample: + return int(value_tensor(dataset, key, sample[key]).shape[-1]) + raise ValueError(f"No sample has the EHR key '{key}'.") + + +class ConVIRTLinearProbe(BaseModel): + """Linear probe on the frozen encoders of a pretrained :class:`ConVIRT`. + + The encoders are copied from ``convirt``, frozen and kept in eval mode, + and the projection heads are dropped. A single linear layer reads the + concatenated encoder outputs (``ehr_hidden_dim + cxr_dim`` features) and + is the only trained part. ``cxr_dim`` is 512 for a ResNet-34, giving + ``641`` parameters with the default sizes, or ``cxr_feature_dim`` for + precomputed embeddings (1,152 for MedSigLIP, giving 1,281 parameters). + + As the encoders are frozen and images are not augmented, the features can + be computed once with :meth:`extract_features`, and the layer + :attr:`linear` trained on them without the images. + + Args: + dataset: Sample dataset with the label to predict. + convirt: A pretrained :class:`ConVIRT`. + + Examples: + >>> probe = ConVIRTLinearProbe(dataset, convirt) # doctest: +SKIP + >>> probe.linear.in_features + 1 # doctest: +SKIP + 641 + """ + + def __init__(self, dataset: SampleDataset, convirt: ConVIRT) -> None: + super().__init__(dataset=dataset) + if len(self.label_keys) != 1: + raise ValueError("ConVIRTLinearProbe supports exactly one label key.") + self.ehr_feature_key = convirt.ehr_feature_key + self.cxr_feature_key = convirt.cxr_feature_key + self.label_key = self.label_keys[0] + + self.encoders = copy.deepcopy(convirt.encoders) + self.encoders.augmentation = None + for parameter in self.encoders.parameters(): + parameter.requires_grad = False + self.linear = nn.Linear( + self.encoders.ehr_dim + self.encoders.cxr_dim, + self.label_processor.output_size(), + ) + + def train(self, mode: bool = True) -> ConVIRTLinearProbe: + """Sets the training mode, keeping the frozen encoders in eval mode. + + Args: + mode: Whether to set training mode. + + Returns: + The model. + + Examples: + >>> probe.train().encoders.training # doctest: +SKIP + False + """ + super().train(mode) + self.encoders.eval() + return self + + def _features( + self, **kwargs: torch.Tensor | tuple[torch.Tensor, ...] + ) -> torch.Tensor: + ehr = value_tensor( + self.dataset, self.ehr_feature_key, kwargs[self.ehr_feature_key] + ) + cxr = value_tensor( + self.dataset, self.cxr_feature_key, kwargs[self.cxr_feature_key] + ) + lengths = _ehr_lengths( + self.dataset, self.ehr_feature_key, kwargs[self.ehr_feature_key] + ) + with torch.no_grad(): + v_ehr, v_cxr = self.encoders( + ehr.to(self.device).float(), cxr.to(self.device).float(), lengths + ) + return torch.cat([v_ehr, v_cxr], dim=-1) + + def extract_features( + self, dataloader: DataLoader + ) -> tuple[torch.Tensor, torch.Tensor]: + """Computes the encoder features and the labels of a dataloader. + + Args: + dataloader: Dataloader of the dataset. + + Returns: + The features ``[samples, ehr_hidden_dim + cxr_dim]`` and the + labels. + + Examples: + >>> features, labels = probe.extract_features(loader) # doctest: +SKIP + """ + self.eval() + features, labels = [], [] + for batch in dataloader: + features.append(self._features(**batch).cpu()) + labels.append(batch[self.label_key].cpu()) + return torch.cat(features), torch.cat(labels) + + def forward( + self, **kwargs: torch.Tensor | tuple[torch.Tensor, ...] + ) -> dict[str, torch.Tensor]: + """Forward propagation. + + Args: + **kwargs: Inputs by key: the EHR tensor, the image tensor and, to + get a loss, the label. + + Returns: + A dictionary with ``logit``, ``y_prob`` and, when the label is + given, ``loss`` and ``y_true``. + """ + logit = self.linear(self._features(**kwargs)) + results = {"logit": logit, "y_prob": self.label_processor.activation(logit)} + if self.label_key in kwargs: + y_true = kwargs[self.label_key].to(self.device) + results["loss"] = self.label_processor.loss(logit, y_true) + results["y_true"] = y_true + return results diff --git a/pyhealth/models/ehr_cxr_early_fusion.py b/pyhealth/models/ehr_cxr_early_fusion.py new file mode 100644 index 0000000000..120c973bcf --- /dev/null +++ b/pyhealth/models/ehr_cxr_early_fusion.py @@ -0,0 +1,310 @@ +# Authors: Yuqing Hu (yhu672@gatech.edu), Hanh Trang Do (hdo61@gatech.edu) +# Paper: MedMod: Multimodal Benchmark for Medical Prediction Tasks with +# Electronic Health Records and Chest X-Ray Scans (Elsharief et al., 2025) +# https://proceedings.mlr.press/v287/elsharief25a.html +# Description: Early fusion of an EHR LSTM and a chest X-ray ResNet. + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +import torch +from torch import nn + +from pyhealth.datasets import SampleDataset +from pyhealth.models.base_model import BaseModel + +_RESNETS = ("resnet18", "resnet34", "resnet50") + + +def build_resnet(name: str) -> tuple[nn.Module, int]: + """Builds an untrained torchvision ResNet without its classifier. + + Args: + name: One of ``"resnet18"``, ``"resnet34"`` and ``"resnet50"``. + + Returns: + The backbone, which maps ``[batch, 3, H, W]`` to ``[batch, dim]``, and + ``dim``. + + Examples: + >>> backbone, dim = build_resnet("resnet18") + >>> dim + 512 + """ + if name not in _RESNETS: + raise ValueError(f"Unsupported backbone '{name}'. Use one of {_RESNETS}.") + import torchvision.models as tv_models + + backbone = getattr(tv_models, name)(weights=None) + dim = backbone.fc.in_features + backbone.fc = nn.Identity() + return backbone, dim + + +def value_tensor( + dataset: SampleDataset, key: str, feature: torch.Tensor | tuple[torch.Tensor, ...] +) -> torch.Tensor: + """Returns the ``value`` tensor of an input feature. + + Args: + dataset: The dataset that holds the input processors. + key: The input key. + feature: A tensor, or a tuple of tensors described by the schema of + the processor of ``key``. + + Returns: + The value tensor. + + Examples: + >>> value_tensor(None, "ehr", torch.zeros(2, 3)).shape + torch.Size([2, 3]) + """ + if isinstance(feature, torch.Tensor): + return feature + schema = dataset.input_processors[key].schema() + if "value" not in schema: + raise ValueError(f"Feature '{key}' must provide a 'value' tensor.") + return feature[schema.index("value")] + + +class EHRCXREarlyFusion(BaseModel): + """Early fusion of an EHR LSTM and a chest X-ray (CXR) ResNet. + + The EHR time series goes through an LSTM and the image through a ResNet. + The image feature is projected to the size of the EHR feature, the two are + concatenated and a linear layer gives the logit. This is the Early Fusion + baseline of MedMod (Elsharief et al., 2025), which builds on the fusion + code of MedFuse (Hayat et al., 2022). With ``freeze_encoders=True`` the + two encoders are not trained: only the projection and the classifier are. + With ``freeze_encoders=False`` all parts are trained. + + Frozen encoders stay in eval mode during training, so the ResNet's + BatchNorm statistics do not change and the LSTM applies no dropout. + MedFuse instead sets the whole model to train mode, frozen encoders + included, so results can differ slightly from its code. + + 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``. + + Pretrained weights are passed as state dicts, so that this class stays + independent of how a checkpoint file is laid out. They are loaded strictly + into :attr:`ehr_encoder` (an ``nn.LSTM``) and :attr:`cxr_encoder` (a + ResNet without its ``fc`` layer). + + Args: + dataset: Sample dataset used for model configuration. + ehr_feature_key: Input key of the EHR tensor ``[batch, time, dim]``. + cxr_feature_key: Key of the image tensor ``[batch, 3, H, W]`` in the + batch. It need not be a dataset input: a training loop can load + and augment the images of each batch and add them under this key. + None gives an EHR-only model, whose classifier reads the EHR + feature alone. It is used to pretrain the LSTM. + ehr_hidden_dim: Hidden size of the LSTM. + ehr_num_layers: Number of LSTM layers. + dropout: Dropout between the LSTM layers. + cxr_backbone: ``"resnet18"``, ``"resnet34"`` or ``"resnet50"`` for an + untrained torchvision ResNet, or a module that maps images to + ``[batch, cxr_feature_dim]`` (for example a frozen MedSigLIP). + cxr_feature_dim: Output size of ``cxr_backbone`` when it is a module. + Leave it unset for a ResNet name, which sets its own size. + freeze_encoders: Whether to freeze the LSTM and the image encoder. + Frozen encoders also stay in eval mode when the model is set to + train mode, so BatchNorm statistics do not change. + ehr_state_dict: Optional weights of :attr:`ehr_encoder`. + cxr_state_dict: Optional weights of :attr:`cxr_encoder`. + augment_cxr: Whether to augment images in training mode: horizontal + flip and a random affine transform, as in MedFuse. + + Examples: + >>> from pyhealth.datasets import create_sample_dataset, get_dataloader + >>> samples = [ + ... { + ... "patient_id": f"p{i}", + ... "visit_id": f"v{i}", + ... "ehr": torch.randn(4, 6).tolist(), + ... "cxr": torch.randn(3, 32, 32).tolist(), + ... "label": i % 2, + ... } + ... for i in range(4) + ... ] + >>> dataset = create_sample_dataset( + ... samples=samples, + ... input_schema={"ehr": "tensor", "cxr": "tensor"}, + ... output_schema={"label": "binary"}, + ... ) + >>> model = EHRCXREarlyFusion( + ... dataset, ehr_hidden_dim=8, ehr_num_layers=1, cxr_backbone="resnet18" + ... ) + >>> batch = next(iter(get_dataloader(dataset, batch_size=4))) + >>> model(**batch)["y_prob"].shape + torch.Size([4, 1]) + """ + + def __init__( + self, + dataset: SampleDataset, + ehr_feature_key: str = "ehr", + cxr_feature_key: str | None = "cxr", + ehr_hidden_dim: int = 256, + ehr_num_layers: int = 2, + dropout: float = 0.3, + cxr_backbone: str | nn.Module = "resnet34", + cxr_feature_dim: int | None = None, + freeze_encoders: bool = True, + ehr_state_dict: Mapping[str, Any] | None = None, + cxr_state_dict: Mapping[str, Any] | None = None, + augment_cxr: bool = False, + ) -> None: + super().__init__(dataset=dataset) + if len(self.label_keys) != 1: + raise ValueError("EHRCXREarlyFusion supports exactly one label key.") + if ehr_feature_key not in self.feature_keys: + raise ValueError( + f"ehr_feature_key '{ehr_feature_key}' is not an input of the " + f"dataset: {self.feature_keys}." + ) + if cxr_feature_key is None and freeze_encoders: + raise ValueError( + "An EHR-only model has nothing else to train: set " + "freeze_encoders=False." + ) + self.ehr_feature_key = ehr_feature_key + self.cxr_feature_key = cxr_feature_key + self.label_key = self.label_keys[0] + self.freeze_encoders = freeze_encoders + self.augment_cxr = augment_cxr + + self.ehr_encoder = nn.LSTM( + input_size=self._infer_ehr_dim(), + hidden_size=ehr_hidden_dim, + num_layers=ehr_num_layers, + batch_first=True, + dropout=dropout if ehr_num_layers > 1 else 0.0, + ) + if ehr_state_dict is not None: + self.ehr_encoder.load_state_dict(ehr_state_dict) + + self.cxr_encoder: nn.Module | None = None + self.projection: nn.Linear | None = None + classifier_in = ehr_hidden_dim + if cxr_feature_key is not None: + if isinstance(cxr_backbone, str): + if cxr_feature_dim is not None: + raise ValueError( + "cxr_feature_dim is only for a module backbone; a " + "ResNet sets its own output size." + ) + self.cxr_encoder, cxr_dim = build_resnet(cxr_backbone) + else: + if cxr_feature_dim is None: + raise ValueError("cxr_feature_dim is required for a module.") + self.cxr_encoder, cxr_dim = cxr_backbone, cxr_feature_dim + if cxr_state_dict is not None: + self.cxr_encoder.load_state_dict(cxr_state_dict) + self.projection = nn.Linear(cxr_dim, ehr_hidden_dim) + classifier_in = 2 * ehr_hidden_dim + elif cxr_state_dict is not None: + raise ValueError("cxr_state_dict needs a cxr_feature_key.") + + if freeze_encoders: + for module in (self.ehr_encoder, self.cxr_encoder): + for parameter in module.parameters(): + 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 + + @staticmethod + def _build_augmentation() -> nn.Module: + """Flip and affine transform of the MedFuse training images.""" + from torchvision import transforms + + return transforms.Compose( + [ + transforms.RandomHorizontalFlip(), + transforms.RandomAffine( + degrees=45, translate=(0.15, 0.15), scale=(0.85, 1.15), shear=0 + ), + ] + ) + + def _infer_ehr_dim(self) -> int: + """Infers the EHR feature size from the first processed sample.""" + for sample in self.dataset: + if self.ehr_feature_key in sample: + value = value_tensor( + self.dataset, self.ehr_feature_key, sample[self.ehr_feature_key] + ) + return int(value.shape[-1]) + raise ValueError(f"No sample has the EHR key '{self.ehr_feature_key}'.") + + def train(self, mode: bool = True) -> EHRCXREarlyFusion: + """Sets the training mode, keeping frozen encoders in eval mode. + + Args: + mode: Whether to set training mode. + + Returns: + The model. + + Examples: + >>> model.train().training # doctest: +SKIP + True + """ + super().train(mode) + if self.freeze_encoders: + self.ehr_encoder.eval() + if self.cxr_encoder is not None: + self.cxr_encoder.eval() + return self + + def _augment(self, cxr: torch.Tensor) -> torch.Tensor: + """Augments each image on its own, as one transform per call.""" + return torch.stack([self.augmentation(image) for image in cxr]) + + def forward( + self, **kwargs: torch.Tensor | tuple[torch.Tensor, ...] + ) -> dict[str, torch.Tensor]: + """Forward propagation. + + Args: + **kwargs: Inputs by key: the EHR tensor, the image tensor (unless + EHR-only) and, to get a loss, the label. + + Returns: + A dictionary with ``logit``, ``y_prob`` and, when the label is + given, ``loss`` and ``y_true``. + """ + train_encoders = torch.is_grad_enabled() and not self.freeze_encoders + + ehr = value_tensor( + self.dataset, self.ehr_feature_key, kwargs[self.ehr_feature_key] + ) + with torch.set_grad_enabled(train_encoders): + _, (hidden, _) = self.ehr_encoder(ehr.to(self.device).float()) + features = hidden[-1] + + if self.cxr_encoder is not None: + cxr = ( + value_tensor( + self.dataset, self.cxr_feature_key, kwargs[self.cxr_feature_key] + ) + .to(self.device) + .float() + ) + if self.augmentation is not None and self.training: + cxr = self._augment(cxr) + with torch.set_grad_enabled(train_encoders): + cxr_features = self.cxr_encoder(cxr) + features = torch.cat([features, self.projection(cxr_features)], dim=-1) + + logit = self.classifier(features) + results = {"logit": logit, "y_prob": self.label_processor.activation(logit)} + if self.label_key in kwargs: + y_true = kwargs[self.label_key].to(self.device) + results["loss"] = self.label_processor.loss(logit, y_true) + results["y_true"] = y_true + return results diff --git a/tests/core/test_convirt.py b/tests/core/test_convirt.py new file mode 100644 index 0000000000..43a9b4f1ea --- /dev/null +++ b/tests/core/test_convirt.py @@ -0,0 +1,276 @@ +import unittest + +import torch +from torch import nn + +from pyhealth.datasets import create_sample_dataset, get_dataloader +from pyhealth.models import ConVIRT, ConVIRTLinearProbe +from pyhealth.models.convirt import info_nce_loss +from pyhealth.trainer import Trainer + +HIDDEN = 8 +EHR_DIM = 6 + + +def _dataset(n: int = 8): + generator = torch.Generator().manual_seed(11) + samples = [ + { + "patient_id": f"p{i}", + "visit_id": f"v{i}", + "ehr": torch.randn(5, EHR_DIM, generator=generator).tolist(), + "cxr": torch.randn(3, 32, 32, generator=generator).tolist(), + "label": i % 2, + } + for i in range(n) + ] + return create_sample_dataset( + samples=samples, + input_schema={"ehr": "tensor", "cxr": "tensor"}, + output_schema={"label": "binary"}, + dataset_name="convirt_test", + ) + + +def _convirt(dataset, **kwargs): + options = { + "ehr_hidden_dim": HIDDEN, + "projection_dim": HIDDEN, + "cxr_backbone": "resnet18", + } + options.update(kwargs) + return ConVIRT(dataset, **options) + + +class TestInfoNCE(unittest.TestCase): + def test_matches_a_loop_over_samples(self) -> None: + generator = torch.Generator().manual_seed(0) + z_ehr = torch.randn(5, 4, generator=generator) + z_cxr = torch.randn(5, 4, generator=generator) + temperature = 0.1 + sim = ( + torch.nn.functional.cosine_similarity(z_cxr[:, None], z_ehr[None], dim=-1) + / temperature + ) + total = 0.0 + for i in range(5): + others = [j for j in range(5) if j != i] + total += sim[i, i] - torch.logsumexp(sim[i, others], dim=0) + total += sim[i, i] - torch.logsumexp(sim[others, i], dim=0) + self.assertTrue( + torch.allclose( + info_nce_loss(z_ehr, z_cxr, temperature), -total / 5, atol=1e-5 + ) + ) + + def test_is_symmetric_in_the_two_modalities(self) -> None: + generator = torch.Generator().manual_seed(1) + a, b = ( + torch.randn(6, 4, generator=generator), + torch.randn(6, 4, generator=generator), + ) + self.assertTrue( + torch.allclose(info_nce_loss(a, b), info_nce_loss(b, a), atol=1e-5) + ) + + def test_aligned_pairs_have_lower_loss(self) -> None: + z = torch.randn(6, 4, generator=torch.Generator().manual_seed(2)) + self.assertLess(info_nce_loss(z, z), info_nce_loss(z, z.roll(1, dims=0))) + + def test_needs_a_batch_of_two(self) -> None: + with self.assertRaises(ValueError): + info_nce_loss(torch.randn(1, 4), torch.randn(1, 4)) + + +class TestConVIRT(unittest.TestCase): + @classmethod + def setUpClass(cls) -> None: + cls.dataset = _dataset() + cls.batch = next(iter(get_dataloader(cls.dataset, batch_size=8))) + + def test_precomputed_image_embeddings(self) -> None: + model = _convirt(self.dataset, cxr_backbone=nn.Identity(), cxr_feature_dim=10) + batch = dict(self.batch, cxr=torch.randn(8, 10)) + self.assertTrue(torch.isfinite(model(**batch)["loss"])) + self.assertEqual(model.cxr_head[0].in_features, 10) + probe = ConVIRTLinearProbe(self.dataset, model) + self.assertEqual(probe.linear.in_features, HIDDEN + 10) + with self.assertRaises(ValueError): + _convirt(self.dataset, cxr_backbone=nn.Identity()) + with self.assertRaises(ValueError): + _convirt(self.dataset, cxr_backbone="resnet18", cxr_feature_dim=10) + + def test_forward_outputs(self) -> None: + output = _convirt(self.dataset)(**self.batch) + self.assertEqual(set(output), {"loss", "z_ehr", "z_cxr"}) + self.assertEqual(output["loss"].dim(), 0) + self.assertTrue(torch.isfinite(output["loss"])) + self.assertEqual(output["z_ehr"].shape, (8, HIDDEN)) + self.assertEqual(output["z_cxr"].shape, (8, HIDDEN)) + + def test_scores_no_label(self) -> None: + self.assertEqual(_convirt(self.dataset).label_processors, {}) + + def test_all_parameters_get_gradients(self) -> None: + model = _convirt(self.dataset) + model(**self.batch)["loss"].backward() + missing = [ + n + for n, p in model.named_parameters() + if p.grad is None and n != "_dummy_param" + ] + self.assertEqual(missing, []) + + def test_loss_falls_on_a_fixed_batch(self) -> None: + torch.manual_seed(0) + model = _convirt(self.dataset) + optimizer = torch.optim.Adam(model.parameters(), lr=1e-2) + model.train() + first = model(**self.batch)["loss"].item() + for _ in range(5): + optimizer.zero_grad() + loss = model(**self.batch)["loss"] + loss.backward() + optimizer.step() + self.assertLess(loss.item(), first) + + def test_trainer_trains_on_the_loss_alone(self) -> None: + model = _convirt(self.dataset) + loader = get_dataloader(self.dataset, batch_size=4) + trainer = Trainer(model=model, device="cpu", enable_logging=False) + trainer.train( + train_dataloader=loader, + val_dataloader=loader, + epochs=1, + monitor="loss", + monitor_criterion="min", + ) + self.assertEqual(set(trainer.evaluate(loader)), {"loss"}) + + def test_augmentation_runs_in_training_mode_only(self) -> None: + model = _convirt(self.dataset, augment_cxr=True) + model.train() + self.assertTrue(torch.isfinite(model(**self.batch)["loss"])) + model.eval() + first = model(**self.batch)["z_cxr"] + second = model(**self.batch)["z_cxr"] + self.assertTrue(torch.equal(first, second)) + + def test_invalid_arguments(self) -> None: + with self.assertRaises(ValueError): + _convirt(self.dataset, temperature=0.0) + with self.assertRaises(ValueError): + _convirt(self.dataset, ehr_feature_key="missing") + with self.assertRaises(ValueError): + _convirt(self.dataset, cxr_mean=(0.5, 0.5, 0.5)) + + def test_images_are_used_as_given_by_default(self) -> None: + self.assertIsNone(_convirt(self.dataset).encoders.cxr_mean) + + def test_images_added_to_the_batch_by_the_training_loop(self) -> None: + dataset = create_sample_dataset( + samples=[ + { + "patient_id": f"p{i}", + "ehr": torch.randn(5, EHR_DIM).tolist(), + "label": i % 2, + } + for i in range(4) + ], + input_schema={"ehr": "tensor"}, + output_schema={"label": "binary"}, + dataset_name="convirt_no_image_input", + ) + batch = next(iter(get_dataloader(dataset, batch_size=4))) + batch["cxr"] = torch.rand(4, 3, 32, 32) + self.assertTrue(torch.isfinite(_convirt(dataset)(**batch)["loss"])) + + +class TestConVIRTPacking(unittest.TestCase): + def test_padding_does_not_change_the_ehr_feature(self) -> None: + encoders = _convirt(_dataset()).encoders.eval() + short, long = torch.randn(1, 3, EHR_DIM), torch.randn(1, 5, EHR_DIM) + padded = torch.cat( + [torch.cat([short, torch.zeros(1, 2, EHR_DIM)], dim=1), long] + ) + images = torch.rand(2, 3, 32, 32) + with torch.no_grad(): + batched, _ = encoders(padded, images, torch.tensor([3, 5])) + alone, _ = encoders(short, images[:1]) + self.assertTrue(torch.allclose(batched[0], alone[0], atol=1e-6)) + + +class TestConVIRTLinearProbe(unittest.TestCase): + @classmethod + def setUpClass(cls) -> None: + cls.dataset = _dataset() + cls.loader = get_dataloader(cls.dataset, batch_size=4) + cls.batch = next(iter(get_dataloader(cls.dataset, batch_size=8))) + + def _probe(self): + return ConVIRTLinearProbe(self.dataset, _convirt(self.dataset)) + + def test_only_the_linear_layer_is_trained(self) -> None: + probe = self._probe() + trainable = [ + n + for n, p in probe.named_parameters() + if p.requires_grad and n != "_dummy_param" + ] + self.assertEqual(trainable, ["linear.weight", "linear.bias"]) + self.assertEqual(probe.linear.weight.numel() + 1, HIDDEN + 512 + 1) + + def test_forward_outputs(self) -> None: + output = self._probe()(**self.batch) + self.assertEqual(set(output), {"logit", "y_prob", "loss", "y_true"}) + self.assertEqual(output["logit"].shape, (8, 1)) + + def test_encoders_are_frozen_and_stay_in_eval_mode(self) -> None: + probe = self._probe() + before = probe.encoders.cxr_encoder.bn1.running_mean.clone() + probe.train() + probe(**self.batch)["loss"].backward() + self.assertFalse(probe.encoders.training) + self.assertTrue( + torch.equal(before, probe.encoders.cxr_encoder.bn1.running_mean) + ) + self.assertTrue(all(p.grad is None for p in probe.encoders.parameters())) + + def test_probe_does_not_share_weights_with_the_pretrained_model(self) -> None: + convirt = _convirt(self.dataset) + probe = ConVIRTLinearProbe(self.dataset, convirt) + with torch.no_grad(): + probe.encoders.ehr_encoder.weight_ih_l0.add_(1.0) + self.assertTrue(convirt.encoders.ehr_encoder.weight_ih_l0.requires_grad) + self.assertFalse( + torch.equal( + probe.encoders.ehr_encoder.weight_ih_l0, + convirt.encoders.ehr_encoder.weight_ih_l0, + ) + ) + + def test_cached_features_match_the_forward_pass(self) -> None: + probe = self._probe() + features, labels = probe.extract_features(self.loader) + self.assertEqual(features.shape, (8, HIDDEN + 512)) + self.assertEqual(labels.shape[0], 8) + full = next(iter(get_dataloader(self.dataset, batch_size=8, shuffle=False))) + probe.eval() + with torch.no_grad(): + expected = probe(**full)["logit"] + cached = probe.linear(features) + self.assertTrue(torch.allclose(expected, cached, atol=1e-5)) + + def test_state_dict_round_trip(self) -> None: + source = self._probe() + target = self._probe() + target.load_state_dict(source.state_dict()) + source.eval() + target.eval() + self.assertTrue( + torch.equal(source(**self.batch)["logit"], target(**self.batch)["logit"]) + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/core/test_ehr_cxr_early_fusion.py b/tests/core/test_ehr_cxr_early_fusion.py new file mode 100644 index 0000000000..fc34750481 --- /dev/null +++ b/tests/core/test_ehr_cxr_early_fusion.py @@ -0,0 +1,168 @@ +import unittest + +import torch +from torch import nn + +from pyhealth.datasets import create_sample_dataset, get_dataloader +from pyhealth.models import EHRCXREarlyFusion + +HIDDEN = 8 +EHR_DIM = 6 + + +def _dataset(n: int = 4): + generator = torch.Generator().manual_seed(7) + samples = [ + { + "patient_id": f"p{i}", + "visit_id": f"v{i}", + "ehr": torch.randn(5, EHR_DIM, generator=generator).tolist(), + "cxr": torch.randn(3, 32, 32, generator=generator).tolist(), + "label": i % 2, + } + for i in range(n) + ] + return create_sample_dataset( + samples=samples, + input_schema={"ehr": "tensor", "cxr": "tensor"}, + output_schema={"label": "binary"}, + dataset_name="early_fusion_test", + ) + + +def _model(dataset, **kwargs): + options = { + "ehr_hidden_dim": HIDDEN, + "ehr_num_layers": 2, + "cxr_backbone": "resnet18", + } + options.update(kwargs) + return EHRCXREarlyFusion(dataset, **options) + + +class TestEHRCXREarlyFusion(unittest.TestCase): + @classmethod + def setUpClass(cls) -> None: + cls.dataset = _dataset() + cls.batch = next(iter(get_dataloader(cls.dataset, batch_size=4))) + + def test_forward_outputs(self) -> None: + output = _model(self.dataset)(**self.batch) + self.assertEqual(set(output), {"logit", "y_prob", "loss", "y_true"}) + self.assertEqual(output["logit"].shape, (4, 1)) + self.assertTrue(((output["y_prob"] >= 0) & (output["y_prob"] <= 1)).all()) + self.assertTrue(torch.isfinite(output["loss"])) + + def test_forward_without_label_has_no_loss(self) -> None: + batch = {k: v for k, v in self.batch.items() if k != "label"} + output = _model(self.dataset)(**batch) + self.assertNotIn("loss", output) + + def test_trainable_parameters_when_frozen(self) -> None: + model = _model(self.dataset) + trainable = sum(p.numel() for p in model.parameters() if p.requires_grad) + projection = 512 * HIDDEN + HIDDEN + classifier = 2 * HIDDEN + 1 + self.assertEqual(trainable, projection + classifier) + + def test_frozen_encoders_get_no_gradient(self) -> None: + model = _model(self.dataset) + model.train() + model(**self.batch)["loss"].backward() + for encoder in (model.ehr_encoder, model.cxr_encoder): + self.assertTrue(all(p.grad is None for p in encoder.parameters())) + self.assertIsNotNone(model.projection.weight.grad) + self.assertIsNotNone(model.classifier.weight.grad) + + def test_frozen_encoders_stay_in_eval_mode(self) -> None: + model = _model(self.dataset) + model.train() + self.assertTrue(model.training) + self.assertFalse(model.ehr_encoder.training) + self.assertFalse(model.cxr_encoder.training) + + def test_frozen_batchnorm_statistics_do_not_change(self) -> None: + model = _model(self.dataset) + before = model.cxr_encoder.bn1.running_mean.clone() + model.train() + model(**self.batch) + self.assertTrue(torch.equal(before, model.cxr_encoder.bn1.running_mean)) + + def test_unfrozen_encoders_are_trained(self) -> None: + model = _model(self.dataset, freeze_encoders=False) + model.train() + self.assertTrue(model.cxr_encoder.training) + model(**self.batch)["loss"].backward() + self.assertIsNotNone(model.ehr_encoder.weight_ih_l0.grad) + self.assertIsNotNone(model.cxr_encoder.conv1.weight.grad) + + def test_state_dicts_are_loaded(self) -> None: + source = _model(self.dataset, freeze_encoders=False) + target = _model( + self.dataset, + ehr_state_dict=source.ehr_encoder.state_dict(), + cxr_state_dict=source.cxr_encoder.state_dict(), + ) + for name, value in source.ehr_encoder.state_dict().items(): + self.assertTrue(torch.equal(value, target.ehr_encoder.state_dict()[name])) + for name, value in source.cxr_encoder.state_dict().items(): + self.assertTrue(torch.equal(value, target.cxr_encoder.state_dict()[name])) + + def test_mismatched_state_dict_is_rejected(self) -> None: + with self.assertRaises(RuntimeError): + _model(self.dataset, cxr_state_dict={"conv1.weight": torch.zeros(1)}) + + def test_ehr_only_model(self) -> None: + with self.assertRaises(ValueError): + _model(self.dataset, cxr_feature_key=None) + model = _model(self.dataset, cxr_feature_key=None, freeze_encoders=False) + batch = {k: v for k, v in self.batch.items() if k != "cxr"} + output = model(**batch) + self.assertEqual(output["logit"].shape, (4, 1)) + self.assertEqual(model.classifier.in_features, HIDDEN) + + def test_module_backbone(self) -> None: + backbone = nn.Sequential(nn.Flatten(), nn.Linear(3 * 32 * 32, 10)) + model = _model(self.dataset, cxr_backbone=backbone, cxr_feature_dim=10) + self.assertEqual(model(**self.batch)["logit"].shape, (4, 1)) + with self.assertRaises(ValueError): + _model(self.dataset, cxr_backbone=backbone) + with self.assertRaises(ValueError): + _model(self.dataset, cxr_backbone="resnet18", cxr_feature_dim=10) + + def test_augmentation_only_in_training_mode(self) -> None: + model = _model(self.dataset, augment_cxr=True) + model.train() + self.assertEqual(model(**self.batch)["logit"].shape, (4, 1)) + model.eval() + first = model(**self.batch)["logit"] + second = model(**self.batch)["logit"] + self.assertTrue(torch.equal(first, second)) + + def test_images_added_to_the_batch_by_the_training_loop(self) -> None: + dataset = create_sample_dataset( + samples=[ + { + "patient_id": f"p{i}", + "ehr": torch.randn(5, EHR_DIM).tolist(), + "label": i % 2, + } + for i in range(4) + ], + input_schema={"ehr": "tensor"}, + output_schema={"label": "binary"}, + dataset_name="early_fusion_no_image_input", + ) + batch = next(iter(get_dataloader(dataset, batch_size=4))) + batch["cxr"] = torch.randn(4, 3, 32, 32) + self.assertEqual(_model(dataset)(**batch)["logit"].shape, (4, 1)) + + def test_unknown_backbone_and_keys_are_rejected(self) -> None: + with self.assertRaises(ValueError): + _model(self.dataset, cxr_backbone="vgg") + with self.assertRaises(ValueError): + _model(self.dataset, ehr_feature_key="missing") + + +if __name__ == "__main__": + unittest.main() From fc7294458ed8e5ada20df16a854b158b5c5a22f0 Mon Sep 17 00:00:00 2001 From: rainiehu <57816421+Rainie-Hu@users.noreply.github.com> Date: Fri, 27 Nov 2026 13:04:33 -0800 Subject: [PATCH 2/4] Put frozen encoders in eval mode at construction; reject augmentation without images --- pyhealth/models/convirt.py | 16 ++++++++----- pyhealth/models/ehr_cxr_early_fusion.py | 32 +++++++++++++++++-------- tests/core/test_convirt.py | 10 ++++++++ tests/core/test_ehr_cxr_early_fusion.py | 20 ++++++++++++++++ 4 files changed, 62 insertions(+), 16 deletions(-) diff --git a/pyhealth/models/convirt.py b/pyhealth/models/convirt.py index ee541b9495..af6972c782 100644 --- a/pyhealth/models/convirt.py +++ b/pyhealth/models/convirt.py @@ -350,12 +350,13 @@ def _infer_ehr_dim(dataset: SampleDataset, key: str) -> int: class ConVIRTLinearProbe(BaseModel): """Linear probe on the frozen encoders of a pretrained :class:`ConVIRT`. - The encoders are copied from ``convirt``, frozen and kept in eval mode, - and the projection heads are dropped. A single linear layer reads the - concatenated encoder outputs (``ehr_hidden_dim + cxr_dim`` features) and - is the only trained part. ``cxr_dim`` is 512 for a ResNet-34, giving - ``641`` parameters with the default sizes, or ``cxr_feature_dim`` for - precomputed embeddings (1,152 for MedSigLIP, giving 1,281 parameters). + The encoders are copied from ``convirt``, frozen and kept in eval mode + from construction on, and the projection heads are dropped. A single + linear layer reads the concatenated encoder outputs + (``ehr_hidden_dim + cxr_dim`` features) and is the only trained part. + ``cxr_dim`` is 512 for a ResNet-34, giving ``641`` parameters with the + default sizes, or ``cxr_feature_dim`` for precomputed embeddings (1,152 + for MedSigLIP, giving 1,281 parameters). As the encoders are frozen and images are not augmented, the features can be computed once with :meth:`extract_features`, and the layer @@ -387,6 +388,9 @@ def __init__(self, dataset: SampleDataset, convirt: ConVIRT) -> None: self.encoders.ehr_dim + self.encoders.cxr_dim, self.label_processor.output_size(), ) + # The copied encoders keep ConVIRT's train mode; put them in eval mode + # now, not only on the first train() or eval() call. + self.train(self.training) def train(self, mode: bool = True) -> ConVIRTLinearProbe: """Sets the training mode, keeping the frozen encoders in eval mode. diff --git a/pyhealth/models/ehr_cxr_early_fusion.py b/pyhealth/models/ehr_cxr_early_fusion.py index 120c973bcf..7b011a8247 100644 --- a/pyhealth/models/ehr_cxr_early_fusion.py +++ b/pyhealth/models/ehr_cxr_early_fusion.py @@ -75,15 +75,18 @@ class EHRCXREarlyFusion(BaseModel): The EHR time series goes through an LSTM and the image through a ResNet. The image feature is projected to the size of the EHR feature, the two are concatenated and a linear layer gives the logit. This is the Early Fusion - baseline of MedMod (Elsharief et al., 2025), which builds on the fusion - code of MedFuse (Hayat et al., 2022). With ``freeze_encoders=True`` the - two encoders are not trained: only the projection and the classifier are. - With ``freeze_encoders=False`` all parts are trained. - - Frozen encoders stay in eval mode during training, so the ResNet's - BatchNorm statistics do not change and the LSTM applies no dropout. - MedFuse instead sets the whole model to train mode, frozen encoders - included, so results can differ slightly from its code. + baseline of MedMod (Elsharief et al., 2025), which builds on the original + MedFuse code (Hayat et al., 2022, https://github.com/nyuad-cai/MedFuse), + not on PyHealth's :class:`~pyhealth.models.MedFuse`. With + ``freeze_encoders=True`` the two encoders are not trained: only the + projection and the classifier are. With ``freeze_encoders=False`` all + parts are trained. + + Frozen encoders are in eval mode from construction on and stay in it when + the model is set to train mode, so the ResNet's BatchNorm statistics do + not change and the LSTM applies no dropout. The original MedFuse code + instead sets the whole model to train mode, frozen encoders included, so + results can differ slightly from it. The model expects samples that have an image. With :class:`~pyhealth.tasks.EHRCXRMortalityMIMIC4` use ``paired_only=True``, @@ -97,6 +100,9 @@ class EHRCXREarlyFusion(BaseModel): Args: dataset: Sample dataset used for model configuration. ehr_feature_key: Input key of the EHR tensor ``[batch, time, dim]``. + All samples must have the same number of time steps (e.g. the + 48 hourly bins of MedMod's in-hospital mortality task): the LSTM + reads the last step, so zero padding is not skipped. cxr_feature_key: Key of the image tensor ``[batch, 3, H, W]`` in the batch. It need not be a dataset input: a training loop can load and augment the images of each batch and add them under this key. @@ -116,7 +122,8 @@ class EHRCXREarlyFusion(BaseModel): ehr_state_dict: Optional weights of :attr:`ehr_encoder`. cxr_state_dict: Optional weights of :attr:`cxr_encoder`. augment_cxr: Whether to augment images in training mode: horizontal - flip and a random affine transform, as in MedFuse. + flip and a random affine transform, as in MedFuse. Only for a + ResNet backbone, which reads images. Examples: >>> from pyhealth.datasets import create_sample_dataset, get_dataloader @@ -201,6 +208,8 @@ def __init__( else: if cxr_feature_dim is None: raise ValueError("cxr_feature_dim is required for a module.") + if augment_cxr: + raise ValueError("Augmentation needs images (a ResNet backbone).") self.cxr_encoder, cxr_dim = cxr_backbone, cxr_feature_dim if cxr_state_dict is not None: self.cxr_encoder.load_state_dict(cxr_state_dict) @@ -216,6 +225,9 @@ def __init__( self.classifier = nn.Linear(classifier_in, self.label_processor.output_size()) self.augmentation = self._build_augmentation() if augment_cxr else None + # A new module is in train mode; this puts frozen encoders in eval mode + # now, not only on the first train() or eval() call. + self.train(self.training) @staticmethod def _build_augmentation() -> nn.Module: diff --git a/tests/core/test_convirt.py b/tests/core/test_convirt.py index 43a9b4f1ea..79556754f7 100644 --- a/tests/core/test_convirt.py +++ b/tests/core/test_convirt.py @@ -225,6 +225,16 @@ def test_forward_outputs(self) -> None: self.assertEqual(set(output), {"logit", "y_prob", "loss", "y_true"}) self.assertEqual(output["logit"].shape, (8, 1)) + def test_fresh_probe_keeps_encoders_in_eval_mode(self) -> None: + # No train() or eval() call before the forward pass. + probe = self._probe() + self.assertFalse(probe.encoders.training) + before = probe.encoders.cxr_encoder.bn1.running_mean.clone() + probe(**self.batch) + self.assertTrue( + torch.equal(before, probe.encoders.cxr_encoder.bn1.running_mean) + ) + def test_encoders_are_frozen_and_stay_in_eval_mode(self) -> None: probe = self._probe() before = probe.encoders.cxr_encoder.bn1.running_mean.clone() diff --git a/tests/core/test_ehr_cxr_early_fusion.py b/tests/core/test_ehr_cxr_early_fusion.py index fc34750481..70a977679a 100644 --- a/tests/core/test_ehr_cxr_early_fusion.py +++ b/tests/core/test_ehr_cxr_early_fusion.py @@ -88,6 +88,19 @@ def test_frozen_batchnorm_statistics_do_not_change(self) -> None: model(**self.batch) self.assertTrue(torch.equal(before, model.cxr_encoder.bn1.running_mean)) + def test_fresh_model_keeps_frozen_encoders_in_eval_mode(self) -> None: + # No train() or eval() call before the forward passes. + model = _model(self.dataset) + self.assertTrue(model.training) + self.assertFalse(model.ehr_encoder.training) + self.assertFalse(model.cxr_encoder.training) + before = model.cxr_encoder.bn1.running_mean.clone() + first = model(**self.batch)["logit"] + second = model(**self.batch)["logit"] + self.assertTrue(torch.equal(before, model.cxr_encoder.bn1.running_mean)) + # The 2-layer LSTM's dropout would make the two passes differ. + self.assertTrue(torch.equal(first, second)) + def test_unfrozen_encoders_are_trained(self) -> None: model = _model(self.dataset, freeze_encoders=False) model.train() @@ -129,6 +142,13 @@ def test_module_backbone(self) -> None: _model(self.dataset, cxr_backbone=backbone) with self.assertRaises(ValueError): _model(self.dataset, cxr_backbone="resnet18", cxr_feature_dim=10) + with self.assertRaises(ValueError): + _model( + self.dataset, + cxr_backbone=nn.Identity(), + cxr_feature_dim=10, + augment_cxr=True, + ) def test_augmentation_only_in_training_mode(self) -> None: model = _model(self.dataset, augment_cxr=True) From 5bbfa4f76753fe3af9c17664cbe444fea79347e0 Mon Sep 17 00:00:00 2001 From: rainiehu <57816421+Rainie-Hu@users.noreply.github.com> Date: Fri, 27 Nov 2026 13:59:06 -0800 Subject: [PATCH 3/4] Handle a one-sample ConVIRT batch; clarify EHR length, EHR-only and augmentation docs --- pyhealth/models/convirt.py | 23 +++++++++++- pyhealth/models/ehr_cxr_early_fusion.py | 16 ++++---- tests/core/test_convirt.py | 50 +++++++++++++++++++++++++ 3 files changed, 80 insertions(+), 9 deletions(-) diff --git a/pyhealth/models/convirt.py b/pyhealth/models/convirt.py index af6972c782..2fba8b17fe 100644 --- a/pyhealth/models/convirt.py +++ b/pyhealth/models/convirt.py @@ -185,6 +185,12 @@ class ConVIRT(BaseModel): on the loss alone and reports the validation loss. Follow it with :class:`ConVIRTLinearProbe`. + The loss compares each pair with the other pairs of its batch, so a batch + of one sample has no negatives: its loss is zero and it changes nothing. + Use ``get_dataloader(..., drop_last=True)`` for pretraining, as MedMod + does, so every batch has the full set of negatives; a last batch of one + sample in validation would also lower the mean validation loss. + Paper: Zhang et al. (2022). Contrastive Learning of Medical Visual Representations from Paired Images and Text. MLHC 2022. Setup as in @@ -193,6 +199,12 @@ class ConVIRT(BaseModel): Args: dataset: Sample dataset used for model configuration. ehr_feature_key: Input key of the EHR tensor ``[batch, time, dim]``. + Stays of different lengths may come zero-padded with their + lengths, when the key's processor schema is + ``("value", "lengths")``; the LSTM then packs them and stops at + each stay's last step. MedMod's ConVIRT pretraining on whole ICU + stays gets its EHR this way, from the ``MedModEHRSequenceProcessor`` + of the MedMod dataset PR (#1637). cxr_feature_key: Key of the image input in the batch: an image tensor ``[batch, 3, H, W]`` for a ResNet, or ``[batch, cxr_feature_dim]`` embeddings with ``cxr_backbone=nn.Identity()``. It need not be a @@ -211,7 +223,9 @@ class ConVIRT(BaseModel): cxr_feature_dim: Output size of ``cxr_backbone`` when it is a module. Leave it unset for a ResNet name, which sets its own size. augment_cxr: Whether to augment images in training mode, with the - SimCLRv2-style transforms of MedMod. + SimCLRv2-style transforms of MedMod. They expect pixels in + ``[0, 1]`` (the colour jitter clamps to that range), so for + ImageNet-normalized images also pass ``cxr_mean`` and ``cxr_std``. cxr_mean: Mean the images were normalized with, to undo before encoding, as MedMod feeds ConVIRT pixel values in ``[0, 1]``. Default None for images that are not normalized. For @@ -325,7 +339,12 @@ def forward( ehr.to(self.device).float(), cxr.to(self.device).float(), lengths ) z_ehr, z_cxr = self.ehr_head(v_ehr), self.cxr_head(v_cxr) - loss = info_nce_loss(z_ehr, z_cxr, self.temperature) + if z_ehr.size(0) < 2: + # A single pair has no negatives. A zero loss that keeps the graph + # lets backward() run, so a last batch of one sample is a no-op. + loss = (z_ehr.sum() + z_cxr.sum()) * 0.0 + else: + loss = info_nce_loss(z_ehr, z_cxr, self.temperature) return {"loss": loss, "z_ehr": z_ehr, "z_cxr": z_cxr} diff --git a/pyhealth/models/ehr_cxr_early_fusion.py b/pyhealth/models/ehr_cxr_early_fusion.py index 7b011a8247..a58f43214a 100644 --- a/pyhealth/models/ehr_cxr_early_fusion.py +++ b/pyhealth/models/ehr_cxr_early_fusion.py @@ -100,14 +100,16 @@ class EHRCXREarlyFusion(BaseModel): Args: dataset: Sample dataset used for model configuration. ehr_feature_key: Input key of the EHR tensor ``[batch, time, dim]``. - All samples must have the same number of time steps (e.g. the - 48 hourly bins of MedMod's in-hospital mortality task): the LSTM - reads the last step, so zero padding is not skipped. + All samples must have the same number of time steps, e.g. 24 for + :class:`~pyhealth.tasks.EHRCXRMortalityMIMIC4` with its default + 2-hour bins over 48 hours, or 48 with 1-hour bins (``bin_hours=1``, + MedMod's setting). The LSTM reads the last step, so zero padding + is not skipped. cxr_feature_key: Key of the image tensor ``[batch, 3, H, W]`` in the - batch. It need not be a dataset input: a training loop can load - and augment the images of each batch and add them under this key. - None gives an EHR-only model, whose classifier reads the EHR - feature alone. It is used to pretrain the LSTM. + batch. It need not be a dataset input: a training loop can add the + images of each batch under this key. With ``None`` the model is + EHR-only: with ``freeze_encoders=False``, only the LSTM and the + classifier are trained, e.g. to pretrain the LSTM on EHR alone. ehr_hidden_dim: Hidden size of the LSTM. ehr_num_layers: Number of LSTM layers. dropout: Dropout between the LSTM layers. diff --git a/tests/core/test_convirt.py b/tests/core/test_convirt.py index 79556754f7..3a6ae5e469 100644 --- a/tests/core/test_convirt.py +++ b/tests/core/test_convirt.py @@ -200,6 +200,56 @@ def test_padding_does_not_change_the_ehr_feature(self) -> None: self.assertTrue(torch.allclose(batched[0], alone[0], atol=1e-6)) +class TestConVIRTSingleSampleBatch(unittest.TestCase): + """A last batch of one sample (dataset size mod batch size == 1).""" + + @classmethod + def setUpClass(cls) -> None: + # 64 x 64 images: in train mode, the ResNet's last BatchNorm needs more + # than one value per channel, which a 32 x 32 image of one sample lacks. + generator = torch.Generator().manual_seed(5) + cls.dataset = create_sample_dataset( + samples=[ + { + "patient_id": f"p{i}", + "visit_id": f"v{i}", + "ehr": torch.randn(5, EHR_DIM, generator=generator).tolist(), + "cxr": torch.randn(3, 64, 64, generator=generator).tolist(), + "label": i % 2, + } + for i in range(9) + ], + input_schema={"ehr": "tensor", "cxr": "tensor"}, + output_schema={"label": "binary"}, + dataset_name="convirt_single_sample_test", + ) + + def test_one_sample_batch_has_zero_loss_that_backpropagates(self) -> None: + model = _convirt(self.dataset) + model.train() + batch = next(iter(get_dataloader(self.dataset, batch_size=1))) + loss = model(**batch)["loss"] + self.assertEqual(loss.item(), 0.0) + loss.backward() + grads = [p.grad for n, p in model.named_parameters() if n != "_dummy_param"] + self.assertTrue(all(g is not None and not g.any() for g in grads)) + + def test_trainer_epoch_ending_in_one_sample_batch(self) -> None: + # 9 samples, batch 4: batches of 4, 4 and 1, in training and validation. + loader = get_dataloader(self.dataset, batch_size=4) + trainer = Trainer( + model=_convirt(self.dataset), device="cpu", enable_logging=False + ) + trainer.train( + train_dataloader=loader, + val_dataloader=loader, + epochs=1, + monitor="loss", + monitor_criterion="min", + ) + self.assertTrue(torch.isfinite(torch.tensor(trainer.evaluate(loader)["loss"]))) + + class TestConVIRTLinearProbe(unittest.TestCase): @classmethod def setUpClass(cls) -> None: From f655949ac2f1a89202c4eecdd657047a8ac28eef Mon Sep 17 00:00:00 2001 From: dhtrg <87437721+dhtrg@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:34:58 -0500 Subject: [PATCH 4/4] 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> --- pyhealth/models/convirt.py | 15 ++++++++------- tests/core/test_convirt.py | 16 +++++++++++++++- 2 files changed, 23 insertions(+), 8 deletions(-) diff --git a/pyhealth/models/convirt.py b/pyhealth/models/convirt.py index 2fba8b17fe..d2912e049d 100644 --- a/pyhealth/models/convirt.py +++ b/pyhealth/models/convirt.py @@ -186,10 +186,13 @@ class ConVIRT(BaseModel): :class:`ConVIRTLinearProbe`. The loss compares each pair with the other pairs of its batch, so a batch - of one sample has no negatives: its loss is zero and it changes nothing. - Use ``get_dataloader(..., drop_last=True)`` for pretraining, as MedMod - does, so every batch has the full set of negatives; a last batch of one - sample in validation would also lower the mean validation loss. + of one sample has no negatives: its loss is zero and gives no gradient. + It is not a full no-op: in train mode the ResNet's BatchNorm still updates + its running statistics (and raises an error for very small images), and + an optimizer with momentum or weight decay still moves the weights. Use + ``get_dataloader(..., drop_last=True)`` for pretraining, as MedMod does, + so every batch has the full set of negatives. In validation, a last batch + of one sample would also lower the mean loss. Paper: Zhang et al. (2022). Contrastive Learning of Medical Visual @@ -202,9 +205,7 @@ class ConVIRT(BaseModel): Stays of different lengths may come zero-padded with their lengths, when the key's processor schema is ``("value", "lengths")``; the LSTM then packs them and stops at - each stay's last step. MedMod's ConVIRT pretraining on whole ICU - stays gets its EHR this way, from the ``MedModEHRSequenceProcessor`` - of the MedMod dataset PR (#1637). + each stay's last step. cxr_feature_key: Key of the image input in the batch: an image tensor ``[batch, 3, H, W]`` for a ResNet, or ``[batch, cxr_feature_dim]`` embeddings with ``cxr_backbone=nn.Identity()``. It need not be a diff --git a/tests/core/test_convirt.py b/tests/core/test_convirt.py index 3a6ae5e469..e6c64c2701 100644 --- a/tests/core/test_convirt.py +++ b/tests/core/test_convirt.py @@ -5,7 +5,7 @@ from pyhealth.datasets import create_sample_dataset, get_dataloader from pyhealth.models import ConVIRT, ConVIRTLinearProbe -from pyhealth.models.convirt import info_nce_loss +from pyhealth.models.convirt import IMAGENET_MEAN, IMAGENET_STD, info_nce_loss from pyhealth.trainer import Trainer HIDDEN = 8 @@ -167,6 +167,20 @@ def test_invalid_arguments(self) -> None: def test_images_are_used_as_given_by_default(self) -> None: self.assertIsNone(_convirt(self.dataset).encoders.cxr_mean) + def test_cxr_mean_and_std_undo_the_normalization(self) -> None: + model = _convirt(self.dataset, cxr_mean=IMAGENET_MEAN, cxr_std=IMAGENET_STD) + model.eval() + raw = torch.rand(2, 3, 32, 32, generator=torch.Generator().manual_seed(0)) + mean = torch.tensor(IMAGENET_MEAN).view(1, -1, 1, 1) + std = torch.tensor(IMAGENET_STD).view(1, -1, 1, 1) + ehr = torch.randn(2, 5, EHR_DIM, generator=torch.Generator().manual_seed(1)) + with torch.no_grad(): + _, from_normalized = model.encoders(ehr, (raw - mean) / std) + model.encoders.cxr_mean = None + model.encoders.cxr_std = None + _, from_raw = model.encoders(ehr, raw) + torch.testing.assert_close(from_normalized, from_raw) + def test_images_added_to_the_batch_by_the_training_loop(self) -> None: dataset = create_sample_dataset( samples=[