From 984162b3b096022a83460a6bfaaa1729b9792203 Mon Sep 17 00:00:00 2001 From: Alhibb Date: Wed, 18 Nov 2026 14:30:15 +0100 Subject: [PATCH 1/5] [BTY-50] Add UDC model for rare disease prediction to pyhealth.models --- docs/api/models.rst | 1 + docs/api/models/pyhealth.models.UDC.rst | 59 +++ pyhealth/models/__init__.py | 6 + pyhealth/models/udc.py | 608 ++++++++++++++++++++++++ tests/core/test_udc.py | 337 +++++++++++++ 5 files changed, 1011 insertions(+) create mode 100644 docs/api/models/pyhealth.models.UDC.rst create mode 100644 pyhealth/models/udc.py create mode 100644 tests/core/test_udc.py diff --git a/docs/api/models.rst b/docs/api/models.rst index 897cbaab49..70ae19ec75 100644 --- a/docs/api/models.rst +++ b/docs/api/models.rst @@ -356,4 +356,5 @@ API Reference models/pyhealth.models.APN models/pyhealth.models.TRACE models/pyhealth.models.MIRA + models/pyhealth.models.UDC diff --git a/docs/api/models/pyhealth.models.UDC.rst b/docs/api/models/pyhealth.models.UDC.rst new file mode 100644 index 0000000000..de61d19845 --- /dev/null +++ b/docs/api/models/pyhealth.models.UDC.rst @@ -0,0 +1,59 @@ +pyhealth.models.UDC +=================== + +Overview +-------- + +UDC (Zhao et al., `Unveiling Discrete Clues: Superior Healthcare Predictions +for Rare Diseases `_, The Web Conference +/ WWW 2025) predicts clinical outcomes for rare diseases from longitudinal +Electronic Health Records (EHR). + +Predicting rare diseases in EHR is notoriously difficult due to extreme +sample scarcity, long-tail code distributions, and weak co-occurrence patterns +with other medical codes. Standard continuous deep learning architectures are +dominated by frequent conditions, drowning out subtle clinical clues. + +UDC addresses this challenge by establishing condition-aware discrete clues +via Residual Vector Quantization (RVQ): + +1. **Feature Embedding & Intra-Visit Pooling**: Categorical and numeric + EHR codes across modalities (conditions, procedures, drugs) are embedded + into continuous representations via :class:`~pyhealth.models.EmbeddingModel`. + Nested visits are pooled into visit representations using configurable + intra-visit pooling (``sum``, ``mean``, ``max``, or ``attention``). +2. **Discrete Clue Encoding**: Continuous visit representations are quantized + into discrete prototypes across hierarchical codebook stages using + :class:`~pyhealth.models.udc.ResidualVectorQuantizer`. Continuous and + discrete clue representations are fused via residual LayerNorm in + :class:`~pyhealth.models.udc.DiscreteClueEncoder`. +3. **Longitudinal Visit Modeling**: A temporal sequence model (GRU, LSTM, + or Transformer) aggregates patient trajectories across visits. +4. **Outcome Prediction & Joint Loss**: Patient representations from the last + valid visit are mapped to outcome logits. The objective function jointly + optimizes the task loss and the discrete codebook commitment loss. + +Inputs and Outputs +------------------ + +UDC accepts standard PyHealth :class:`~pyhealth.datasets.SampleDataset` +batches. Both 2D sequences (``SequenceProcessor``) and 3D nested sequences +(``NestedSequenceProcessor``) are supported. Binary, multiclass, and +multilabel classification tasks are fully supported. During inference, +``forward`` returns ``y_prob``, ``logit``, ``embed``, and the discrete clue +prototype indices ``vq_indices``. + +API +--- + +.. autoclass:: pyhealth.models.UDC + :members: + :show-inheritance: + +.. autoclass:: pyhealth.models.udc.ResidualVectorQuantizer + :members: + :show-inheritance: + +.. autoclass:: pyhealth.models.udc.DiscreteClueEncoder + :members: + :show-inheritance: diff --git a/pyhealth/models/__init__.py b/pyhealth/models/__init__.py index 8d931e6cb9..ad74d16c8a 100644 --- a/pyhealth/models/__init__.py +++ b/pyhealth/models/__init__.py @@ -124,3 +124,9 @@ MIRAConfig as MIRAConfig, load_mira_checkpoint as load_mira_checkpoint, ) +from .udc import ( + UDC as UDC, + DiscreteClueEncoder as DiscreteClueEncoder, + ResidualVectorQuantizer as ResidualVectorQuantizer, +) + diff --git a/pyhealth/models/udc.py b/pyhealth/models/udc.py new file mode 100644 index 0000000000..91ad402515 --- /dev/null +++ b/pyhealth/models/udc.py @@ -0,0 +1,608 @@ +"""UDC: Unveiling Discrete Clues for Rare Disease Prediction. + +Paper: Chuang Zhao, Hui Tang, Jiheng Zhang, Xiaomeng Li. Unveiling Discrete +Clues: Superior Healthcare Predictions for Rare Diseases. The Web Conference +(WWW 2025). https://arxiv.org/abs/2501.16373 + +In Electronic Health Records (EHR), predicting rare diseases is severely +hindered by extreme sample scarcity, long-tail code distributions, and +weak disease-code co-occurrence patterns. Standard continuous representation +learning models tend to be dominated by frequent common conditions, causing +clues indicating rare conditions to be smoothed out or lost. + +UDC overcomes this by introducing condition-aware discrete clues via +Residual Vector Quantization (RVQ). By mapping continuous medical code and +visit representations to a discrete codebook hierarchy, UDC establishes +compact, distinguishable prototypes for subtle clinical clues. + +The PyHealth UDC architecture comprises: + 1. Input Feature Embedding: Projects medical codes (conditions, + procedures, drugs, etc.) into continuous representations using + :class:`~pyhealth.models.EmbeddingModel`. Nested visit sequences + are pooled into visit-level representations via configurable + intra-visit pooling (sum, mean, max, or attention). + 2. Discrete Clue Encoding: Employs :class:`ResidualVectorQuantizer` + across multiple residual codebook stages to extract discrete clue + prototypes, fusing continuous and discrete representations via + residual connection and layer normalization. + 3. Longitudinal Visit Modeling: A temporal sequence encoder (GRU, + LSTM, or Transformer) models the patient's multi-visit trajectory + over time. + 4. Prediction Head & Joint Loss: Patient representations from the + last valid visit are mapped to outcome predictions. The training + loss jointly optimizes task prediction and discrete vector + quantization commitment. + +Supports binary, multiclass, and multilabel classification tasks. +""" + +from __future__ import annotations + +from typing import Any + +import torch +import torch.nn.functional as F +from torch import nn + +from pyhealth.datasets import SampleDataset +from pyhealth.models.base_model import BaseModel +from pyhealth.models.embedding import EmbeddingModel +from pyhealth.models.utils import get_last_visit + + +class ResidualVectorQuantizer(nn.Module): + """Residual Vector Quantizer (RVQ) with straight-through gradient estimation. + + Decomposes an input continuous vector into a sum of discrete codebook + prototypes across multiple codebook stages. Each stage quantizes the + residual error left by the preceding stages, enabling a rich discrete + representation with compact individual codebooks. + + Args: + n_codebooks: Number of residual codebook stages. Default is 2. + codebook_size: Number of prototype embeddings per codebook. + Default is 128. + embedding_dim: Dimensionality of each prototype vector. + Default is 128. + commitment_cost: Commitment loss scaling factor beta. Default is 0.25. + + Examples: + >>> import torch + >>> from pyhealth.models.udc import ResidualVectorQuantizer + >>> rvq = ResidualVectorQuantizer( + ... n_codebooks=2, codebook_size=32, embedding_dim=16 + ... ) + >>> x = torch.randn(3, 5, 16) + >>> quantized, vq_loss, indices = rvq(x) + >>> quantized.shape + torch.Size([3, 5, 16]) + >>> indices.shape + torch.Size([3, 5, 2]) + >>> bool(vq_loss.detach() >= 0.0) + True + """ + + def __init__( + self, + n_codebooks: int = 2, + codebook_size: int = 128, + embedding_dim: int = 128, + commitment_cost: float = 0.25, + ) -> None: + super().__init__() + if n_codebooks <= 0: + raise ValueError(f"n_codebooks must be positive, got {n_codebooks}") + if codebook_size <= 0: + raise ValueError(f"codebook_size must be positive, got {codebook_size}") + if embedding_dim <= 0: + raise ValueError(f"embedding_dim must be positive, got {embedding_dim}") + if commitment_cost < 0: + raise ValueError( + f"commitment_cost cannot be negative, got {commitment_cost}" + ) + + self.n_codebooks = n_codebooks + self.codebook_size = codebook_size + self.embedding_dim = embedding_dim + self.commitment_cost = commitment_cost + + self.codebooks = nn.ModuleList( + [nn.Embedding(codebook_size, embedding_dim) for _ in range(n_codebooks)] + ) + for codebook in self.codebooks: + nn.init.uniform_( + codebook.weight, -1.0 / codebook_size, 1.0 / codebook_size + ) + + def forward( + self, x: torch.Tensor + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Quantizes the continuous input tensor across residual codebooks. + + Args: + x: Continuous input tensor of shape ``(..., embedding_dim)``. + + Returns: + Tuple of: + - quantized: Quantized tensor with straight-through gradient, + shape ``(..., embedding_dim)``. + - vq_loss: Scalar commitment and codebook loss. + - indices: Selected codebook prototype indices, shape + ``(..., n_codebooks)``. + """ + orig_shape = x.shape + flat_x = x.reshape(-1, self.embedding_dim) + residual = flat_x + + quantized_out = torch.zeros_like(flat_x) + all_indices: list[torch.Tensor] = [] + vq_loss = torch.tensor(0.0, device=x.device, dtype=x.dtype) + + for codebook in self.codebooks: + cb_w = codebook.weight # (codebook_size, embedding_dim) + # Pairwise squared Euclidean distance + dist = ( + residual.pow(2).sum(dim=-1, keepdim=True) + - 2 * (residual @ cb_w.t()) + + cb_w.pow(2).sum(dim=-1, keepdim=True).t() + ) + indices = torch.argmin(dist, dim=-1) + all_indices.append(indices) + + quantized_i = codebook(indices) + loss_i = F.mse_loss( + quantized_i, residual.detach() + ) + self.commitment_cost * F.mse_loss(residual, quantized_i.detach()) + vq_loss = vq_loss + loss_i + + quantized_out = quantized_out + quantized_i + residual = residual - quantized_i.detach() + + # Straight-through gradient estimator + quantized_st = flat_x + (quantized_out - flat_x).detach() + quantized_st = quantized_st.view(orig_shape) + + stacked_indices = torch.stack(all_indices, dim=-1).view( + *orig_shape[:-1], self.n_codebooks + ) + mean_vq_loss = vq_loss / self.n_codebooks + return quantized_st, mean_vq_loss, stacked_indices + + +class DiscreteClueEncoder(nn.Module): + """Encodes continuous visit representations with condition-aware discrete clues. + + In UDC, continuous embeddings for rare diseases and infrequent clinical events + suffer from noisy, sparse gradients. The Discrete Clue Encoder projects + continuous features into discrete prototype spaces using Residual Vector + Quantization (RVQ), discretizing clues into compact, distinguishable + representations that prevent frequent conditions from dominating. + + Args: + input_dim: Input feature dimension. + hidden_dim: Hidden dimension for discrete clues. + n_codebooks: Number of residual codebooks. Default is 2. + codebook_size: Number of prototype embeddings per codebook. + Default is 128. + commitment_cost: Weight beta of the commitment loss term. + Default is 0.25. + dropout: Dropout rate. Default is 0.1. + + Examples: + >>> import torch + >>> from pyhealth.models.udc import DiscreteClueEncoder + >>> encoder = DiscreteClueEncoder( + ... input_dim=16, hidden_dim=16, n_codebooks=2, codebook_size=32 + ... ) + >>> x = torch.randn(2, 4, 16) + >>> fused, vq_loss, indices = encoder(x) + >>> fused.shape + torch.Size([2, 4, 16]) + >>> indices.shape + torch.Size([2, 4, 2]) + >>> bool(vq_loss.detach() >= 0.0) + True + """ + + def __init__( + self, + input_dim: int, + hidden_dim: int, + n_codebooks: int = 2, + codebook_size: int = 128, + commitment_cost: float = 0.25, + dropout: float = 0.1, + ) -> None: + super().__init__() + self.input_dim = input_dim + self.hidden_dim = hidden_dim + + self.proj: nn.Module = ( + nn.Linear(input_dim, hidden_dim) + if input_dim != hidden_dim + else nn.Identity() + ) + self.rvq = ResidualVectorQuantizer( + n_codebooks=n_codebooks, + codebook_size=codebook_size, + embedding_dim=hidden_dim, + commitment_cost=commitment_cost, + ) + self.norm = nn.LayerNorm(hidden_dim) + self.dropout = nn.Dropout(dropout) + + def forward( + self, x: torch.Tensor + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Projects continuous representations and fuses residual discrete clues. + + Args: + x: Input continuous tensor of shape ``(..., input_dim)``. + + Returns: + Tuple of: + - fused: Discrete-clue-enhanced representation of shape + ``(..., hidden_dim)``. + - vq_loss: Residual vector quantization loss scalar. + - indices: Selected discrete clue indices of shape + ``(..., n_codebooks)``. + """ + projected = self.proj(x) + quantized, vq_loss, indices = self.rvq(projected) + fused = self.norm(projected + quantized) + fused = self.dropout(fused) + return fused, vq_loss, indices + + +class UDC(BaseModel): + """UDC: Unveiling Discrete Clues for Rare Disease Prediction. + + Paper: Chuang Zhao, Hui Tang, Jiheng Zhang, Xiaomeng Li. Unveiling Discrete + Clues: Superior Healthcare Predictions for Rare Diseases. The Web + Conference (WWW 2025). https://arxiv.org/abs/2501.16373 + + In Electronic Health Records (EHR), predicting rare diseases is severely + challenged by extreme sample sparsity, long-tail class distributions, and + weak co-occurrence patterns between rare conditions and clinical events. + Standard continuous deep learning models are overwhelmed by frequent + dominant diagnoses, obscuring subtle clinical clues essential for rare + disease detection. + + UDC resolves this by establishing condition-aware discrete clues through + Residual Vector Quantization (RVQ). Hierarchical discrete codebooks + quantize continuous visit embeddings into sharp, distinct clue prototypes, + preventing rare clinical signals from vanishing. + + Args: + dataset: The dataset to train the model. + feature_keys: Names of input feature keys to use from dataset. If None, + all feature keys in ``dataset.input_schema`` are used. + label_key: Name of the label key from dataset. If None, the single + label key from ``dataset.output_schema`` is used. + mode: Task mode ('binary', 'multiclass', 'multilabel'). If None, + inferred from the dataset's label processor. + embedding_dim: Dimension of input code embeddings. Default is 128. + hidden_dim: Dimension of hidden representations. Default is 128. + n_codebooks: Number of residual codebooks for discrete clues. + Default is 2. + codebook_size: Number of prototype entries per codebook. + Default is 128. + commitment_cost: Weight beta of commitment loss. Default is 0.25. + vq_loss_weight: Weight lambda of discrete quantization loss in the + total training loss. Default is 0.1. + intra_visit_pooling: Method to pool codes within a visit ('sum', + 'mean', 'max', 'attention'). Default is 'sum'. + temporal_model: Type of temporal sequence encoder ('gru', 'lstm', + 'transformer'). Default is 'gru'. + num_layers: Number of temporal recurrent or transformer layers. + Default is 1. + dropout: Dropout probability. Default is 0.1. + **kwargs: Additional keyword arguments. + + Examples: + >>> from pyhealth.datasets import create_sample_dataset, get_dataloader + >>> from pyhealth.models import UDC + >>> samples = [ + ... { + ... "patient_id": "p0", + ... "visit_id": "v0", + ... "conditions": [["c1", "c2"], ["c3"]], + ... "procedures": [["p1"], ["p2"]], + ... "label": 1, + ... }, + ... { + ... "patient_id": "p1", + ... "visit_id": "v1", + ... "conditions": [["c2"], ["c4", "c5"]], + ... "procedures": [["p3"], ["p1"]], + ... "label": 0, + ... }, + ... ] + >>> dataset = create_sample_dataset( + ... samples, + ... input_schema={ + ... "conditions": "nested_sequence", + ... "procedures": "nested_sequence", + ... }, + ... output_schema={"label": "binary"}, + ... ) + >>> model = UDC( + ... dataset=dataset, + ... embedding_dim=16, + ... hidden_dim=16, + ... codebook_size=32, + ... ) + >>> loader = get_dataloader(dataset, batch_size=2) + >>> batch = next(iter(loader)) + >>> out = model(**batch) + >>> sorted(out.keys()) + ['embed', 'logit', 'loss', 'vq_loss', 'y_prob', 'y_true'] + """ + + def __init__( + self, + dataset: SampleDataset, + feature_keys: list[str] | None = None, + label_key: str | None = None, + mode: str | None = None, + embedding_dim: int = 128, + hidden_dim: int = 128, + n_codebooks: int = 2, + codebook_size: int = 128, + commitment_cost: float = 0.25, + vq_loss_weight: float = 0.1, + intra_visit_pooling: str = "sum", + temporal_model: str = "gru", + num_layers: int = 1, + dropout: float = 0.1, + **kwargs: Any, + ) -> None: + super().__init__(dataset=dataset) + + if intra_visit_pooling not in ("sum", "mean", "max", "attention"): + raise ValueError( + f"Unsupported intra_visit_pooling: {intra_visit_pooling!r}. " + "Must be one of 'sum', 'mean', 'max', 'attention'." + ) + if temporal_model not in ("gru", "lstm", "transformer"): + raise ValueError( + f"Unsupported temporal_model: {temporal_model!r}. " + "Must be one of 'gru', 'lstm', 'transformer'." + ) + if embedding_dim <= 0: + raise ValueError(f"embedding_dim must be positive, got {embedding_dim}") + if hidden_dim <= 0: + raise ValueError(f"hidden_dim must be positive, got {hidden_dim}") + if n_codebooks <= 0: + raise ValueError(f"n_codebooks must be positive, got {n_codebooks}") + if codebook_size <= 0: + raise ValueError(f"codebook_size must be positive, got {codebook_size}") + if vq_loss_weight < 0: + raise ValueError( + f"vq_loss_weight cannot be negative, got {vq_loss_weight}" + ) + + if feature_keys is not None: + self.feature_keys = feature_keys + if label_key is not None: + self.label_key = label_key + else: + self.label_key = self.label_keys[0] + + self.embedding_dim = embedding_dim + self.hidden_dim = hidden_dim + self.intra_visit_pooling = intra_visit_pooling + self.temporal_model_name = temporal_model + self.vq_loss_weight = vq_loss_weight + + # Unified embedding model for input modalities + self.embedding_model = EmbeddingModel( + dataset=dataset, embedding_dim=embedding_dim + ) + + # Intra-visit attention pooling projection (if attention pooling is selected) + if self.intra_visit_pooling == "attention": + self.intra_attn = nn.Linear(embedding_dim, 1) + + # Multi-feature fusion layer + num_features = len(self.feature_keys) + fused_dim = num_features * embedding_dim + self.feat_proj = nn.Linear(fused_dim, hidden_dim) + + # Discrete Clue Encoder + self.clue_encoder = DiscreteClueEncoder( + input_dim=hidden_dim, + hidden_dim=hidden_dim, + n_codebooks=n_codebooks, + codebook_size=codebook_size, + commitment_cost=commitment_cost, + dropout=dropout, + ) + + # Temporal sequence model across longitudinal visits + if temporal_model == "gru": + self.temporal_encoder = nn.GRU( + hidden_dim, + hidden_dim, + num_layers=num_layers, + batch_first=True, + dropout=dropout if num_layers > 1 else 0.0, + ) + elif temporal_model == "lstm": + self.temporal_encoder = nn.LSTM( + hidden_dim, + hidden_dim, + num_layers=num_layers, + batch_first=True, + dropout=dropout if num_layers > 1 else 0.0, + ) + else: # transformer + nhead = 2 if hidden_dim % 2 == 0 else 1 + encoder_layer = nn.TransformerEncoderLayer( + d_model=hidden_dim, + nhead=nhead, + dim_feedforward=hidden_dim * 4, + dropout=dropout, + batch_first=True, + ) + self.temporal_encoder = nn.TransformerEncoder( + encoder_layer, + num_layers=num_layers, + enable_nested_tensor=False, + ) + + # Classification prediction head + output_size = self.label_processor.output_size() + self.fc = nn.Linear(hidden_dim, output_size) + + def _pool_intra_visit( + self, x: torch.Tensor, mask: torch.Tensor | None = None + ) -> torch.Tensor: + """Pools events/codes within each visit along dimension 2. + + Args: + x: Tensor of shape ``(B, T, K, D)``. + mask: Optional boolean mask of shape ``(B, T, K)``. + + Returns: + Pooled visit representations of shape ``(B, T, D)``. + """ + if self.intra_visit_pooling == "sum": + return torch.sum(x, dim=2) + elif self.intra_visit_pooling == "mean": + if mask is not None: + expanded_mask = mask.unsqueeze(-1).float() + sum_x = torch.sum(x * expanded_mask, dim=2) + count = expanded_mask.sum(dim=2).clamp(min=1.0) + return sum_x / count + return torch.mean(x, dim=2) + elif self.intra_visit_pooling == "max": + if mask is not None: + expanded_mask = mask.unsqueeze(-1) + x_masked = x.masked_fill(~expanded_mask, -1e9) + return torch.max(x_masked, dim=2)[0] + return torch.max(x, dim=2)[0] + else: # attention + weights = self.intra_attn(x) # (B, T, K, 1) + if mask is not None: + weights = weights.masked_fill(~mask.unsqueeze(-1), -1e9) + attn = torch.softmax(weights, dim=2) + attn = torch.nan_to_num(attn, nan=0.0) + return torch.sum(attn * x, dim=2) + + def forward(self, **kwargs: Any) -> dict[str, torch.Tensor]: + """Forward propagation for UDC. + + Args: + **kwargs: Keyword arguments containing input feature tensors and + optionally the label tensor. + + Returns: + Dictionary containing: + - loss: Total training loss (task loss + discrete clue loss). + - y_prob: Predicted outcome probabilities. + - y_true: Ground truth outcome labels (if provided). + - logit: Raw output logits. + - embed: Patient-level latent representations from the last visit. + - vq_loss: Residual vector quantization loss. + - vq_indices: Discrete prototype indices (during inference). + """ + # Unpack tuple inputs if any + cleaned_kwargs: dict[str, Any] = {} + raw_masks: dict[str, torch.Tensor | None] = {} + for key, val in kwargs.items(): + if isinstance(val, tuple): + cleaned_kwargs[key] = val[0] + if len(val) > 1 and isinstance(val[1], torch.Tensor): + raw_masks[key] = val[1] + else: + raw_masks[key] = None + else: + cleaned_kwargs[key] = val + raw_masks[key] = None + + embedded = self.embedding_model(cleaned_kwargs) + + feat_visits: list[torch.Tensor] = [] + visit_masks: list[torch.Tensor] = [] + + for feature_key in self.feature_keys: + feat = embedded[feature_key] + # Nested sequences: (B, T, K, D) + while feat.dim() > 3: + mask = raw_masks.get(feature_key) + if mask is not None and mask.dim() == feat.dim() - 1: + code_mask = mask != 0 + else: + code_mask = (feat != 0).any(dim=-1) + feat = self._pool_intra_visit(feat, code_mask) + + # Flat sequences: (B, D) -> (B, 1, D) + if feat.dim() == 2: + feat = feat.unsqueeze(1) + + # Visit mask: step is valid if any embedding dimension is nonzero + v_mask = (feat != 0).any(dim=-1) + feat_visits.append(feat) + visit_masks.append(v_mask) + + # Concatenate features along embedding dimension and project + if len(feat_visits) > 1: + # Ensure equal sequence lengths across features + max_t = max(f.shape[1] for f in feat_visits) + aligned_feats = [] + for f in feat_visits: + if f.shape[1] < max_t: + pad_len = max_t - f.shape[1] + f = F.pad(f, (0, 0, 0, pad_len)) + aligned_feats.append(f) + combined = torch.cat(aligned_feats, dim=-1) + # Patient visit mask is valid if any feature is valid at step t + overall_mask = visit_masks[0] + for m in visit_masks[1:]: + if m.shape[1] < max_t: + m = F.pad(m, (0, max_t - m.shape[1]), value=False) + overall_mask = overall_mask | m + else: + combined = feat_visits[0] + overall_mask = visit_masks[0] + + visit_repr = self.feat_proj(combined) # (B, T, hidden_dim) + + # Extract and fuse discrete clues + fused_visits, vq_loss, vq_indices = self.clue_encoder(visit_repr) + + # Temporal sequence modeling + if self.temporal_model_name in ("gru", "lstm"): + temporal_out, _ = self.temporal_encoder(fused_visits) + else: # transformer + temporal_out = self.temporal_encoder(fused_visits) + + # Extract patient representation from the last valid visit + patient_emb = get_last_visit(temporal_out, overall_mask) + + # Predict logits and outcome probabilities + logits = self.fc(patient_emb) + y_prob = self.label_processor.activation(logits) + + results: dict[str, torch.Tensor] = { + "y_prob": y_prob, + "logit": logits, + "embed": patient_emb, + "vq_loss": vq_loss, + } + + if self.label_key in kwargs: + y_true = kwargs[self.label_key] + if isinstance(y_true, tuple): + y_true = y_true[0] + if not isinstance(y_true, torch.Tensor): + y_true = torch.as_tensor(y_true, device=logits.device) + task_loss = self.label_processor.loss(logits, y_true) + total_loss = task_loss + self.vq_loss_weight * vq_loss + results["loss"] = total_loss + results["y_true"] = y_true + else: + results["vq_indices"] = vq_indices + + return results diff --git a/tests/core/test_udc.py b/tests/core/test_udc.py new file mode 100644 index 0000000000..c614f1e5ec --- /dev/null +++ b/tests/core/test_udc.py @@ -0,0 +1,337 @@ +import unittest + +import torch + +from pyhealth.datasets import create_sample_dataset, get_dataloader +from pyhealth.models import UDC, DiscreteClueEncoder, ResidualVectorQuantizer + + +class TestResidualVectorQuantizer(unittest.TestCase): + """Unit tests for ResidualVectorQuantizer.""" + + def test_init_valid(self): + rvq = ResidualVectorQuantizer( + n_codebooks=3, codebook_size=64, embedding_dim=32, commitment_cost=0.5 + ) + self.assertEqual(len(rvq.codebooks), 3) + self.assertEqual(rvq.codebook_size, 64) + self.assertEqual(rvq.embedding_dim, 32) + self.assertEqual(rvq.commitment_cost, 0.5) + + def test_init_invalid(self): + with self.assertRaises(ValueError): + ResidualVectorQuantizer(n_codebooks=0) + with self.assertRaises(ValueError): + ResidualVectorQuantizer(codebook_size=-1) + with self.assertRaises(ValueError): + ResidualVectorQuantizer(embedding_dim=0) + with self.assertRaises(ValueError): + ResidualVectorQuantizer(commitment_cost=-0.1) + + def test_forward_shapes(self): + rvq = ResidualVectorQuantizer( + n_codebooks=2, codebook_size=32, embedding_dim=16 + ) + # 2D input (B, D) + x_2d = torch.randn(4, 16) + q_2d, loss_2d, idx_2d = rvq(x_2d) + self.assertEqual(q_2d.shape, (4, 16)) + self.assertEqual(idx_2d.shape, (4, 2)) + self.assertTrue(loss_2d.item() >= 0.0) + + # 3D input (B, T, D) + x_3d = torch.randn(2, 5, 16) + q_3d, loss_3d, idx_3d = rvq(x_3d) + self.assertEqual(q_3d.shape, (2, 5, 16)) + self.assertEqual(idx_3d.shape, (2, 5, 2)) + self.assertTrue(loss_3d.item() >= 0.0) + + def test_straight_through_gradients(self): + rvq = ResidualVectorQuantizer( + n_codebooks=2, codebook_size=16, embedding_dim=8 + ) + x = torch.randn(3, 8, requires_grad=True) + q, loss, _ = rvq(x) + total_loss = q.sum() + loss + total_loss.backward() + self.assertIsNotNone(x.grad) + self.assertTrue(torch.isfinite(x.grad).all()) + + +class TestDiscreteClueEncoder(unittest.TestCase): + """Unit tests for DiscreteClueEncoder.""" + + def test_projection_matching_and_differing_dim(self): + # Matching dim + enc_same = DiscreteClueEncoder( + input_dim=16, hidden_dim=16, n_codebooks=2, codebook_size=32 + ) + self.assertIsInstance(enc_same.proj, torch.nn.Identity) + + # Differing dim + enc_diff = DiscreteClueEncoder( + input_dim=32, hidden_dim=16, n_codebooks=2, codebook_size=32 + ) + self.assertIsInstance(enc_diff.proj, torch.nn.Linear) + + def test_forward_and_backward(self): + enc = DiscreteClueEncoder( + input_dim=24, hidden_dim=16, n_codebooks=2, codebook_size=32 + ) + x = torch.randn(2, 4, 24, requires_grad=True) + fused, vq_loss, indices = enc(x) + self.assertEqual(fused.shape, (2, 4, 16)) + self.assertEqual(indices.shape, (2, 4, 2)) + self.assertTrue(vq_loss.item() >= 0.0) + + (fused.sum() + vq_loss).backward() + self.assertIsNotNone(x.grad) + self.assertTrue(torch.isfinite(x.grad).all()) + + +class TestUDC(unittest.TestCase): + """Unit tests for the full UDC model.""" + + def setUp(self): + self.samples = [ + { + "patient_id": "patient-0", + "visit_id": "visit-0", + "conditions": [["c1", "c2"], ["c3"]], + "procedures": [["p1"], ["p2", "p3"]], + "drugs": ["d1", "d2"], + "label": 1, + }, + { + "patient_id": "patient-1", + "visit_id": "visit-1", + "conditions": [["c2"], ["c4", "c5"]], + "procedures": [["p3"], ["p1"]], + "drugs": ["d3"], + "label": 0, + }, + { + "patient_id": "patient-2", + "visit_id": "visit-2", + "conditions": [["c1", "c4"]], + "procedures": [["p2"]], + "drugs": ["d1"], + "label": 1, + }, + ] + + self.input_schema = { + "conditions": "nested_sequence", + "procedures": "nested_sequence", + "drugs": "sequence", + } + + def test_invalid_args(self): + dataset = create_sample_dataset( + samples=self.samples, + input_schema=self.input_schema, + output_schema={"label": "binary"}, + ) + with self.assertRaises(ValueError): + UDC(dataset, intra_visit_pooling="invalid") + with self.assertRaises(ValueError): + UDC(dataset, temporal_model="unknown") + with self.assertRaises(ValueError): + UDC(dataset, embedding_dim=0) + with self.assertRaises(ValueError): + UDC(dataset, hidden_dim=-5) + with self.assertRaises(ValueError): + UDC(dataset, n_codebooks=0) + with self.assertRaises(ValueError): + UDC(dataset, codebook_size=0) + with self.assertRaises(ValueError): + UDC(dataset, vq_loss_weight=-1.0) + + def test_binary_classification(self): + dataset = create_sample_dataset( + samples=self.samples, + input_schema=self.input_schema, + output_schema={"label": "binary"}, + ) + model = UDC( + dataset=dataset, + embedding_dim=16, + hidden_dim=16, + codebook_size=32, + n_codebooks=2, + ) + loader = get_dataloader(dataset, batch_size=2) + batch = next(iter(loader)) + + out = model(**batch) + self.assertIn("loss", out) + self.assertIn("y_prob", out) + self.assertIn("y_true", out) + self.assertIn("logit", out) + self.assertIn("embed", out) + self.assertIn("vq_loss", out) + + self.assertTrue((out["y_prob"] >= 0.0).all()) + self.assertTrue((out["y_prob"] <= 1.0).all()) + self.assertEqual(out["logit"].shape[-1], 1) + + # Backward pass + out["loss"].backward() + for param in model.parameters(): + if param.requires_grad and param.grad is not None: + self.assertTrue(torch.isfinite(param.grad).all()) + + def test_multiclass_classification(self): + samples_mc = [ + dict(s, label=i % 3) for i, s in enumerate(self.samples) + ] + dataset = create_sample_dataset( + samples=samples_mc, + input_schema=self.input_schema, + output_schema={"label": "multiclass"}, + ) + model = UDC( + dataset=dataset, + embedding_dim=16, + hidden_dim=16, + codebook_size=32, + temporal_model="gru", + ) + loader = get_dataloader(dataset, batch_size=2) + batch = next(iter(loader)) + + out = model(**batch) + self.assertEqual(out["logit"].shape[-1], 3) + prob_sum = out["y_prob"].sum(dim=-1) + self.assertTrue(torch.allclose(prob_sum, torch.ones_like(prob_sum), atol=1e-5)) + + out["loss"].backward() + + def test_multilabel_classification(self): + samples_ml = [ + dict(s, label=[f"l{i}", f"l{i+1}"]) + for i, s in enumerate(self.samples) + ] + dataset = create_sample_dataset( + samples=samples_ml, + input_schema=self.input_schema, + output_schema={"label": "multilabel"}, + ) + model = UDC( + dataset=dataset, + embedding_dim=16, + hidden_dim=16, + codebook_size=32, + temporal_model="lstm", + ) + loader = get_dataloader(dataset, batch_size=2) + batch = next(iter(loader)) + + out = model(**batch) + self.assertTrue((out["y_prob"] >= 0.0).all()) + self.assertTrue((out["y_prob"] <= 1.0).all()) + + out["loss"].backward() + + def test_transformer_temporal_model(self): + dataset = create_sample_dataset( + samples=self.samples, + input_schema=self.input_schema, + output_schema={"label": "binary"}, + ) + model = UDC( + dataset=dataset, + embedding_dim=32, + hidden_dim=32, + temporal_model="transformer", + num_layers=1, + ) + loader = get_dataloader(dataset, batch_size=2) + batch = next(iter(loader)) + out = model(**batch) + self.assertIn("loss", out) + out["loss"].backward() + + def test_intra_visit_pooling_modes(self): + dataset = create_sample_dataset( + samples=self.samples, + input_schema=self.input_schema, + output_schema={"label": "binary"}, + ) + loader = get_dataloader(dataset, batch_size=2) + batch = next(iter(loader)) + + for pool_mode in ("sum", "mean", "max", "attention"): + model = UDC( + dataset=dataset, + embedding_dim=16, + hidden_dim=16, + intra_visit_pooling=pool_mode, + ) + out = model(**batch) + self.assertIn("loss", out) + self.assertTrue(torch.isfinite(out["loss"])) + + def test_inference_without_labels(self): + dataset = create_sample_dataset( + samples=self.samples, + input_schema=self.input_schema, + output_schema={"label": "binary"}, + ) + model = UDC(dataset=dataset, embedding_dim=16, hidden_dim=16) + loader = get_dataloader(dataset, batch_size=2) + batch = next(iter(loader)) + del batch["label"] + + model.eval() + with torch.no_grad(): + out = model(**batch) + + self.assertNotIn("loss", out) + self.assertNotIn("y_true", out) + self.assertIn("y_prob", out) + self.assertIn("logit", out) + self.assertIn("embed", out) + self.assertIn("vq_indices", out) + + def test_tuple_input_handling(self): + dataset = create_sample_dataset( + samples=self.samples, + input_schema=self.input_schema, + output_schema={"label": "binary"}, + ) + model = UDC(dataset=dataset, embedding_dim=16, hidden_dim=16) + loader = get_dataloader(dataset, batch_size=2) + batch = next(iter(loader)) + + # Pass conditions and label as (tensor, mask) tuple + cond_tensor = batch["conditions"] + batch["conditions"] = (cond_tensor, cond_tensor != 0) + batch["label"] = (batch["label"], torch.ones_like(batch["label"])) + + out = model(**batch) + self.assertIn("loss", out) + self.assertTrue(torch.isfinite(out["loss"])) + + def test_optimizer_step(self): + dataset = create_sample_dataset( + samples=self.samples, + input_schema=self.input_schema, + output_schema={"label": "binary"}, + ) + model = UDC(dataset=dataset, embedding_dim=16, hidden_dim=16) + optimizer = torch.optim.Adam(model.parameters(), lr=1e-3) + loader = get_dataloader(dataset, batch_size=2) + batch = next(iter(loader)) + + initial_weight = model.fc.weight.clone() + optimizer.zero_grad() + out = model(**batch) + out["loss"].backward() + optimizer.step() + + self.assertFalse(torch.equal(initial_weight, model.fc.weight)) + + +if __name__ == "__main__": + unittest.main() From 55cb8a4479a6a3a96bd041d51ebb434aa2060b5e Mon Sep 17 00:00:00 2001 From: Alhibb Date: Thu, 19 Nov 2026 01:37:07 +0100 Subject: [PATCH 2/5] fix(udc): address AI review on visit mask padding, max pooling empty visits, mode removal --- pyhealth/models/udc.py | 57 +++++++++++++++------ tests/core/test_udc.py | 109 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 152 insertions(+), 14 deletions(-) diff --git a/pyhealth/models/udc.py b/pyhealth/models/udc.py index 91ad402515..28b0033b8b 100644 --- a/pyhealth/models/udc.py +++ b/pyhealth/models/udc.py @@ -279,8 +279,6 @@ class UDC(BaseModel): all feature keys in ``dataset.input_schema`` are used. label_key: Name of the label key from dataset. If None, the single label key from ``dataset.output_schema`` is used. - mode: Task mode ('binary', 'multiclass', 'multilabel'). If None, - inferred from the dataset's label processor. embedding_dim: Dimension of input code embeddings. Default is 128. hidden_dim: Dimension of hidden representations. Default is 128. n_codebooks: Number of residual codebooks for discrete clues. @@ -344,7 +342,6 @@ def __init__( dataset: SampleDataset, feature_keys: list[str] | None = None, label_key: str | None = None, - mode: str | None = None, embedding_dim: int = 128, hidden_dim: int = 128, n_codebooks: int = 2, @@ -480,7 +477,9 @@ def _pool_intra_visit( if mask is not None: expanded_mask = mask.unsqueeze(-1) x_masked = x.masked_fill(~expanded_mask, -1e9) - return torch.max(x_masked, dim=2)[0] + pooled = torch.max(x_masked, dim=2)[0] + empty_visits = ~mask.any(dim=-1, keepdim=True) + return pooled.masked_fill(empty_visits, 0.0) return torch.max(x, dim=2)[0] else: # attention weights = self.intra_attn(x) # (B, T, K, 1) @@ -488,7 +487,11 @@ def _pool_intra_visit( weights = weights.masked_fill(~mask.unsqueeze(-1), -1e9) attn = torch.softmax(weights, dim=2) attn = torch.nan_to_num(attn, nan=0.0) - return torch.sum(attn * x, dim=2) + pooled = torch.sum(attn * x, dim=2) + if mask is not None: + empty_visits = ~mask.any(dim=-1, keepdim=True) + pooled = pooled.masked_fill(empty_visits, 0.0) + return pooled def forward(self, **kwargs: Any) -> dict[str, torch.Tensor]: """Forward propagation for UDC. @@ -512,11 +515,22 @@ def forward(self, **kwargs: Any) -> dict[str, torch.Tensor]: raw_masks: dict[str, torch.Tensor | None] = {} for key, val in kwargs.items(): if isinstance(val, tuple): - cleaned_kwargs[key] = val[0] - if len(val) > 1 and isinstance(val[1], torch.Tensor): - raw_masks[key] = val[1] + if ( + hasattr(self.dataset, "input_processors") + and key in self.dataset.input_processors + ): + schema = self.dataset.input_processors[key].schema() + value = val[schema.index("value")] if "value" in schema else val[0] + mask = ( + val[schema.index("mask")] + if "mask" in schema + else (val[1] if len(val) > 1 else None) + ) else: - raw_masks[key] = None + value = val[0] + mask = val[1] if len(val) > 1 else None + cleaned_kwargs[key] = value + raw_masks[key] = mask if isinstance(mask, torch.Tensor) else None else: cleaned_kwargs[key] = val raw_masks[key] = None @@ -528,6 +542,7 @@ def forward(self, **kwargs: Any) -> dict[str, torch.Tensor]: for feature_key in self.feature_keys: feat = embedded[feature_key] + v_mask = None # Nested sequences: (B, T, K, D) while feat.dim() > 3: mask = raw_masks.get(feature_key) @@ -535,14 +550,23 @@ def forward(self, **kwargs: Any) -> dict[str, torch.Tensor]: code_mask = mask != 0 else: code_mask = (feat != 0).any(dim=-1) + v_mask = code_mask.any(dim=-1) feat = self._pool_intra_visit(feat, code_mask) # Flat sequences: (B, D) -> (B, 1, D) if feat.dim() == 2: feat = feat.unsqueeze(1) - # Visit mask: step is valid if any embedding dimension is nonzero - v_mask = (feat != 0).any(dim=-1) + # Visit mask: step is valid if code_mask had valid codes or non-zero embedding + if v_mask is None: + mask = raw_masks.get(feature_key) + if mask is not None and mask.dim() == feat.dim() - 1: + v_mask = mask != 0 + else: + v_mask = (feat != 0).any(dim=-1) + else: + feat = feat.masked_fill(~v_mask.unsqueeze(-1), 0.0) + feat_visits.append(feat) visit_masks.append(v_mask) @@ -557,11 +581,16 @@ def forward(self, **kwargs: Any) -> dict[str, torch.Tensor]: f = F.pad(f, (0, 0, 0, pad_len)) aligned_feats.append(f) combined = torch.cat(aligned_feats, dim=-1) - # Patient visit mask is valid if any feature is valid at step t - overall_mask = visit_masks[0] - for m in visit_masks[1:]: + + # Pad every mask to max_t before combining + aligned_masks = [] + for m in visit_masks: if m.shape[1] < max_t: m = F.pad(m, (0, max_t - m.shape[1]), value=False) + aligned_masks.append(m) + + overall_mask = aligned_masks[0] + for m in aligned_masks[1:]: overall_mask = overall_mask | m else: combined = feat_visits[0] diff --git a/tests/core/test_udc.py b/tests/core/test_udc.py index c614f1e5ec..fbede67cf8 100644 --- a/tests/core/test_udc.py +++ b/tests/core/test_udc.py @@ -332,6 +332,115 @@ def test_optimizer_step(self): self.assertFalse(torch.equal(initial_weight, model.fc.weight)) + def test_unequal_visit_counts_across_features(self): + """Tests that features with unequal visit counts pad masks correctly.""" + unequal_samples = [ + { + "patient_id": "p0", + "visit_id": "v0", + "conditions": [["c1", "c2"]], # 1 visit + "procedures": [["p1"], ["p2"], ["p3"]], # 3 visits + "label": 1, + }, + { + "patient_id": "p1", + "visit_id": "v1", + "conditions": [["c2"], ["c3"]], # 2 visits + "procedures": [["p2"], ["p1"]], # 2 visits + "label": 0, + }, + ] + dataset = create_sample_dataset( + samples=unequal_samples, + input_schema={ + "conditions": "nested_sequence", + "procedures": "nested_sequence", + }, + output_schema={"label": "binary"}, + ) + model = UDC(dataset=dataset, embedding_dim=16, hidden_dim=16) + loader = get_dataloader(dataset, batch_size=2) + batch = next(iter(loader)) + out = model(**batch) + self.assertEqual(out["logit"].shape, (2, 1)) + self.assertTrue(torch.isfinite(out["loss"])) + + def test_max_pooling_with_padded_visits(self): + """Verifies max pooling zeroes out empty visits and does not retain -1e9.""" + samples_with_empty = [ + { + "patient_id": "p0", + "visit_id": "v0", + "conditions": [["c1", "c2"], ["c3"]], # 2 visits + "label": 1, + }, + { + "patient_id": "p1", + "visit_id": "v1", + "conditions": [["c2"], ["c4"], ["c5"], ["c1"]], # 4 visits + "label": 0, + }, + ] + dataset = create_sample_dataset( + samples=samples_with_empty, + input_schema={"conditions": "nested_sequence"}, + output_schema={"label": "binary"}, + ) + model = UDC( + dataset=dataset, + embedding_dim=16, + hidden_dim=16, + intra_visit_pooling="max", + ) + loader = get_dataloader(dataset, batch_size=2, shuffle=False) + batch = next(iter(loader)) + out = model(**batch) + self.assertTrue(torch.isfinite(out["loss"])) + # For p0, visits 2 and 3 are padding; verify embedding does not have -1e9 + self.assertFalse(torch.isnan(out["embed"]).any()) + self.assertTrue(torch.all(out["embed"] > -1e5)) + + def test_visit_mask_logic_assertion(self): + """Verifies visit mask accurately distinguishes valid vs empty padded visits.""" + samples = [ + { + "patient_id": "p0", + "visit_id": "v0", + "conditions": [["c1"]], # 1 valid visit + "label": 1, + }, + { + "patient_id": "p1", + "visit_id": "v1", + "conditions": [["c2"], ["c3"], ["c4"]], # 3 valid visits + "label": 0, + }, + ] + dataset = create_sample_dataset( + samples=samples, + input_schema={"conditions": "nested_sequence"}, + output_schema={"label": "binary"}, + ) + model = UDC(dataset=dataset, embedding_dim=16, hidden_dim=16) + loader = get_dataloader(dataset, batch_size=2, shuffle=False) + batch = next(iter(loader)) + out = model(**batch) + self.assertEqual(out["logit"].shape, (2, 1)) + + mask = batch["conditions"] != 0 + code_mask = mask != 0 + v_mask = code_mask.any(dim=-1) + + # Patient 0 has only visit 0 valid; visits 1 and 2 must be False + self.assertTrue(v_mask[0, 0].item()) + self.assertFalse(v_mask[0, 1].item()) + self.assertFalse(v_mask[0, 2].item()) + + # Patient 1 has visits 0, 1, 2 all valid + self.assertTrue(v_mask[1, 0].item()) + self.assertTrue(v_mask[1, 1].item()) + self.assertTrue(v_mask[1, 2].item()) + if __name__ == "__main__": unittest.main() From 38b66bf294071b38602a1cd29132c21b39787a9d Mon Sep 17 00:00:00 2001 From: Alhibb Date: Thu, 19 Nov 2026 02:21:28 +0100 Subject: [PATCH 3/5] fix(udc): mask transformer padding, exclude padded visits from vq_loss, add padding invariance test --- pyhealth/models/udc.py | 38 ++++++++++++++++++++-------- tests/core/test_udc.py | 57 ++++++++++++++++++++++++++---------------- 2 files changed, 63 insertions(+), 32 deletions(-) diff --git a/pyhealth/models/udc.py b/pyhealth/models/udc.py index 28b0033b8b..3059e2eca0 100644 --- a/pyhealth/models/udc.py +++ b/pyhealth/models/udc.py @@ -115,12 +115,13 @@ def __init__( ) def forward( - self, x: torch.Tensor + self, x: torch.Tensor, mask: torch.Tensor | None = None ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """Quantizes the continuous input tensor across residual codebooks. Args: x: Continuous input tensor of shape ``(..., embedding_dim)``. + mask: Optional boolean mask of shape ``(...)`` indicating valid visits. Returns: Tuple of: @@ -133,6 +134,7 @@ def forward( orig_shape = x.shape flat_x = x.reshape(-1, self.embedding_dim) residual = flat_x + flat_mask = mask.reshape(-1).bool() if mask is not None else None quantized_out = torch.zeros_like(flat_x) all_indices: list[torch.Tensor] = [] @@ -150,9 +152,16 @@ def forward( all_indices.append(indices) quantized_i = codebook(indices) - loss_i = F.mse_loss( - quantized_i, residual.detach() - ) + self.commitment_cost * F.mse_loss(residual, quantized_i.detach()) + if flat_mask is not None and flat_mask.any(): + q_valid = quantized_i[flat_mask] + res_valid = residual[flat_mask] + loss_i = F.mse_loss( + q_valid, res_valid.detach() + ) + self.commitment_cost * F.mse_loss(res_valid, q_valid.detach()) + else: + loss_i = F.mse_loss( + quantized_i, residual.detach() + ) + self.commitment_cost * F.mse_loss(residual, quantized_i.detach()) vq_loss = vq_loss + loss_i quantized_out = quantized_out + quantized_i @@ -232,12 +241,13 @@ def __init__( self.dropout = nn.Dropout(dropout) def forward( - self, x: torch.Tensor + self, x: torch.Tensor, mask: torch.Tensor | None = None ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """Projects continuous representations and fuses residual discrete clues. Args: x: Input continuous tensor of shape ``(..., input_dim)``. + mask: Optional boolean mask of shape ``(...)`` indicating valid visits. Returns: Tuple of: @@ -248,9 +258,11 @@ def forward( ``(..., n_codebooks)``. """ projected = self.proj(x) - quantized, vq_loss, indices = self.rvq(projected) + quantized, vq_loss, indices = self.rvq(projected, mask=mask) fused = self.norm(projected + quantized) fused = self.dropout(fused) + if mask is not None: + fused = fused.masked_fill(~mask.unsqueeze(-1), 0.0) return fused, vq_loss, indices @@ -334,7 +346,7 @@ class UDC(BaseModel): >>> batch = next(iter(loader)) >>> out = model(**batch) >>> sorted(out.keys()) - ['embed', 'logit', 'loss', 'vq_loss', 'y_prob', 'y_true'] + ['embed', 'logit', 'loss', 'vq_indices', 'vq_loss', 'y_prob', 'y_true'] """ def __init__( @@ -597,15 +609,20 @@ def forward(self, **kwargs: Any) -> dict[str, torch.Tensor]: overall_mask = visit_masks[0] visit_repr = self.feat_proj(combined) # (B, T, hidden_dim) + visit_repr = visit_repr.masked_fill(~overall_mask.unsqueeze(-1), 0.0) # Extract and fuse discrete clues - fused_visits, vq_loss, vq_indices = self.clue_encoder(visit_repr) + fused_visits, vq_loss, vq_indices = self.clue_encoder( + visit_repr, mask=overall_mask + ) # Temporal sequence modeling if self.temporal_model_name in ("gru", "lstm"): temporal_out, _ = self.temporal_encoder(fused_visits) else: # transformer - temporal_out = self.temporal_encoder(fused_visits) + temporal_out = self.temporal_encoder( + fused_visits, src_key_padding_mask=~overall_mask + ) # Extract patient representation from the last valid visit patient_emb = get_last_visit(temporal_out, overall_mask) @@ -619,6 +636,7 @@ def forward(self, **kwargs: Any) -> dict[str, torch.Tensor]: "logit": logits, "embed": patient_emb, "vq_loss": vq_loss, + "vq_indices": vq_indices, } if self.label_key in kwargs: @@ -631,7 +649,5 @@ def forward(self, **kwargs: Any) -> dict[str, torch.Tensor]: total_loss = task_loss + self.vq_loss_weight * vq_loss results["loss"] = total_loss results["y_true"] = y_true - else: - results["vq_indices"] = vq_indices return results diff --git a/tests/core/test_udc.py b/tests/core/test_udc.py index fbede67cf8..75afae7674 100644 --- a/tests/core/test_udc.py +++ b/tests/core/test_udc.py @@ -400,8 +400,8 @@ def test_max_pooling_with_padded_visits(self): self.assertFalse(torch.isnan(out["embed"]).any()) self.assertTrue(torch.all(out["embed"] > -1e5)) - def test_visit_mask_logic_assertion(self): - """Verifies visit mask accurately distinguishes valid vs empty padded visits.""" + def test_padding_invariance(self): + """Verifies a patient's prediction and embedding do not change when padded.""" samples = [ { "patient_id": "p0", @@ -421,25 +421,40 @@ def test_visit_mask_logic_assertion(self): input_schema={"conditions": "nested_sequence"}, output_schema={"label": "binary"}, ) - model = UDC(dataset=dataset, embedding_dim=16, hidden_dim=16) - loader = get_dataloader(dataset, batch_size=2, shuffle=False) - batch = next(iter(loader)) - out = model(**batch) - self.assertEqual(out["logit"].shape, (2, 1)) - - mask = batch["conditions"] != 0 - code_mask = mask != 0 - v_mask = code_mask.any(dim=-1) - - # Patient 0 has only visit 0 valid; visits 1 and 2 must be False - self.assertTrue(v_mask[0, 0].item()) - self.assertFalse(v_mask[0, 1].item()) - self.assertFalse(v_mask[0, 2].item()) - - # Patient 1 has visits 0, 1, 2 all valid - self.assertTrue(v_mask[1, 0].item()) - self.assertTrue(v_mask[1, 1].item()) - self.assertTrue(v_mask[1, 2].item()) + for temp_model in ("gru", "transformer"): + torch.manual_seed(42) + model = UDC( + dataset=dataset, + embedding_dim=16, + hidden_dim=16, + temporal_model=temp_model, + dropout=0.0, + ) + model.eval() + + loader = get_dataloader(dataset, batch_size=2, shuffle=False) + batch = next(iter(loader)) + + with torch.no_grad(): + out_batch = model(**batch) + batch_single = { + k: v[0:1, :1] if k == "conditions" else v[0:1] + for k, v in batch.items() + } + out_single = model(**batch_single) + + self.assertTrue( + torch.allclose( + out_batch["logit"][0], out_single["logit"][0], atol=1e-5 + ), + f"Logit padding variance on {temp_model}", + ) + self.assertTrue( + torch.allclose( + out_batch["embed"][0], out_single["embed"][0], atol=1e-5 + ), + f"Embed padding variance on {temp_model}", + ) if __name__ == "__main__": From 32ee6d0e43805c34a90bd319e078a8f600da2cda Mon Sep 17 00:00:00 2001 From: Alhibb Date: Thu, 19 Nov 2026 02:44:07 +0100 Subject: [PATCH 4/5] fix(udc): guard transformer against all-pad patients, reject >4D features, correct vq_indices docs, and strengthen max-pooling test --- docs/api/models/pyhealth.models.UDC.rst | 6 +-- pyhealth/models/udc.py | 30 ++++++++++-- tests/core/test_udc.py | 63 ++++++++++++++++++++++++- 3 files changed, 91 insertions(+), 8 deletions(-) diff --git a/docs/api/models/pyhealth.models.UDC.rst b/docs/api/models/pyhealth.models.UDC.rst index de61d19845..5056a7077c 100644 --- a/docs/api/models/pyhealth.models.UDC.rst +++ b/docs/api/models/pyhealth.models.UDC.rst @@ -39,9 +39,9 @@ Inputs and Outputs UDC accepts standard PyHealth :class:`~pyhealth.datasets.SampleDataset` batches. Both 2D sequences (``SequenceProcessor``) and 3D nested sequences (``NestedSequenceProcessor``) are supported. Binary, multiclass, and -multilabel classification tasks are fully supported. During inference, -``forward`` returns ``y_prob``, ``logit``, ``embed``, and the discrete clue -prototype indices ``vq_indices``. +multilabel classification tasks are fully supported. The ``forward`` method +returns ``y_prob``, ``logit``, ``embed``, and the discrete clue prototype +indices ``vq_indices`` (along with ``loss`` and ``vq_loss`` during training). API --- diff --git a/pyhealth/models/udc.py b/pyhealth/models/udc.py index 3059e2eca0..38078a0486 100644 --- a/pyhealth/models/udc.py +++ b/pyhealth/models/udc.py @@ -520,7 +520,7 @@ def forward(self, **kwargs: Any) -> dict[str, torch.Tensor]: - logit: Raw output logits. - embed: Patient-level latent representations from the last visit. - vq_loss: Residual vector quantization loss. - - vq_indices: Discrete prototype indices (during inference). + - vq_indices: Discrete prototype indices from vector quantization. """ # Unpack tuple inputs if any cleaned_kwargs: dict[str, Any] = {} @@ -554,11 +554,18 @@ def forward(self, **kwargs: Any) -> dict[str, torch.Tensor]: for feature_key in self.feature_keys: feat = embedded[feature_key] + if feat.dim() > 4: + raise ValueError( + f"Unsupported feature dimension {feat.dim()} for " + f"feature '{feature_key}'. Only 2D sequences (B, D), " + "3D sequences (B, T, D), and 4D nested sequences " + "(B, T, K, D) are supported." + ) v_mask = None # Nested sequences: (B, T, K, D) - while feat.dim() > 3: + if feat.dim() == 4: mask = raw_masks.get(feature_key) - if mask is not None and mask.dim() == feat.dim() - 1: + if mask is not None and mask.dim() == 3: code_mask = mask != 0 else: code_mask = (feat != 0).any(dim=-1) @@ -620,9 +627,24 @@ def forward(self, **kwargs: Any) -> dict[str, torch.Tensor]: if self.temporal_model_name in ("gru", "lstm"): temporal_out, _ = self.temporal_encoder(fused_visits) else: # transformer + if overall_mask is not None: + all_pad_patients = (~overall_mask).all(dim=-1) + padding_mask = ~overall_mask + # Unmask position 0 for all-pad patients so softmax is finite + if all_pad_patients.any(): + padding_mask = padding_mask.clone() + padding_mask[all_pad_patients, 0] = False + else: + padding_mask = None + all_pad_patients = None + temporal_out = self.temporal_encoder( - fused_visits, src_key_padding_mask=~overall_mask + fused_visits, src_key_padding_mask=padding_mask ) + if all_pad_patients is not None and all_pad_patients.any(): + temporal_out = temporal_out.masked_fill( + all_pad_patients.unsqueeze(-1).unsqueeze(-1), 0.0 + ) # Extract patient representation from the last valid visit patient_emb = get_last_visit(temporal_out, overall_mask) diff --git a/tests/core/test_udc.py b/tests/core/test_udc.py index 75afae7674..a104d75e16 100644 --- a/tests/core/test_udc.py +++ b/tests/core/test_udc.py @@ -398,7 +398,7 @@ def test_max_pooling_with_padded_visits(self): self.assertTrue(torch.isfinite(out["loss"])) # For p0, visits 2 and 3 are padding; verify embedding does not have -1e9 self.assertFalse(torch.isnan(out["embed"]).any()) - self.assertTrue(torch.all(out["embed"] > -1e5)) + self.assertTrue(torch.all(out["embed"].abs() < 50.0)) def test_padding_invariance(self): """Verifies a patient's prediction and embedding do not change when padded.""" @@ -456,6 +456,67 @@ def test_padding_invariance(self): f"Embed padding variance on {temp_model}", ) + def test_empty_patient_with_transformer(self): + """Verifies transformer handles all-pad patient without producing NaNs.""" + samples = [ + { + "patient_id": "p0", + "visit_id": "v0", + "conditions": [["c1", "c2"]], + "label": 1, + }, + { + "patient_id": "p1", + "visit_id": "v1", + "conditions": [["c3"]], + "label": 0, + }, + ] + dataset = create_sample_dataset( + samples=samples, + input_schema={"conditions": "nested_sequence"}, + output_schema={"label": "binary"}, + ) + model = UDC( + dataset=dataset, + embedding_dim=16, + hidden_dim=16, + temporal_model="transformer", + dropout=0.0, + ) + loader = get_dataloader(dataset, batch_size=2, shuffle=False) + batch = next(iter(loader)) + batch["conditions"][1].zero_() + + out = model(**batch) + self.assertFalse(torch.isnan(out["logit"]).any()) + self.assertFalse(torch.isnan(out["embed"]).any()) + self.assertTrue(torch.isfinite(out["loss"])) + out["loss"].backward() + for p in model.parameters(): + if p.grad is not None: + self.assertTrue(torch.isfinite(p.grad).all()) + + def test_unsupported_high_dim_feature(self): + """Verifies ValueError is raised for features with more than 4 dimensions.""" + dataset = create_sample_dataset( + samples=self.samples, + input_schema=self.input_schema, + output_schema={"label": "binary"}, + ) + model = UDC( + dataset=dataset, + embedding_dim=16, + hidden_dim=16, + ) + original_embed = model.embedding_model.forward + model.embedding_model.forward = lambda kw: { + "conditions": torch.zeros((2, 3, 4, 5, 16)) + } + with self.assertRaises(ValueError): + model(conditions=torch.zeros((2, 3, 4, 5))) + model.embedding_model.forward = original_embed + if __name__ == "__main__": unittest.main() From d6a3fe0aa694349954b73272515da166ecd8e537 Mon Sep 17 00:00:00 2001 From: Alhibb Date: Thu, 19 Nov 2026 03:10:15 +0100 Subject: [PATCH 5/5] fix(udc): safe (time, value) tuple handling without mask schema, clarify vq_loss and loss return docs, and test pooling outputs --- docs/api/models/pyhealth.models.UDC.rst | 5 ++- pyhealth/models/__init__.py | 1 - pyhealth/models/udc.py | 58 ++++++++++++++++++++----- tests/core/test_udc.py | 22 ++++++++++ 4 files changed, 72 insertions(+), 14 deletions(-) diff --git a/docs/api/models/pyhealth.models.UDC.rst b/docs/api/models/pyhealth.models.UDC.rst index 5056a7077c..8544c78f94 100644 --- a/docs/api/models/pyhealth.models.UDC.rst +++ b/docs/api/models/pyhealth.models.UDC.rst @@ -40,8 +40,9 @@ UDC accepts standard PyHealth :class:`~pyhealth.datasets.SampleDataset` batches. Both 2D sequences (``SequenceProcessor``) and 3D nested sequences (``NestedSequenceProcessor``) are supported. Binary, multiclass, and multilabel classification tasks are fully supported. The ``forward`` method -returns ``y_prob``, ``logit``, ``embed``, and the discrete clue prototype -indices ``vq_indices`` (along with ``loss`` and ``vq_loss`` during training). +always returns ``y_prob``, ``logit``, ``embed``, ``vq_loss``, and the +discrete clue prototype indices ``vq_indices``. When labels are provided, +``loss`` and ``y_true`` are also returned. API --- diff --git a/pyhealth/models/__init__.py b/pyhealth/models/__init__.py index ad74d16c8a..15879607df 100644 --- a/pyhealth/models/__init__.py +++ b/pyhealth/models/__init__.py @@ -129,4 +129,3 @@ DiscreteClueEncoder as DiscreteClueEncoder, ResidualVectorQuantizer as ResidualVectorQuantizer, ) - diff --git a/pyhealth/models/udc.py b/pyhealth/models/udc.py index 38078a0486..919057bd17 100644 --- a/pyhealth/models/udc.py +++ b/pyhealth/models/udc.py @@ -514,33 +514,69 @@ def forward(self, **kwargs: Any) -> dict[str, torch.Tensor]: Returns: Dictionary containing: - - loss: Total training loss (task loss + discrete clue loss). - y_prob: Predicted outcome probabilities. - - y_true: Ground truth outcome labels (if provided). - logit: Raw output logits. - embed: Patient-level latent representations from the last visit. - - vq_loss: Residual vector quantization loss. + - vq_loss: Residual vector quantization loss (always returned). - vq_indices: Discrete prototype indices from vector quantization. + - loss: Total training loss (when labels provided). + - y_true: Ground truth outcome labels (when labels provided). """ # Unpack tuple inputs if any cleaned_kwargs: dict[str, Any] = {} raw_masks: dict[str, torch.Tensor | None] = {} for key, val in kwargs.items(): if isinstance(val, tuple): + schema = ( + self.dataset.input_processors[key].schema() + if ( + hasattr(self.dataset, "input_processors") + and key in self.dataset.input_processors + ) + else None + ) if ( - hasattr(self.dataset, "input_processors") - and key in self.dataset.input_processors + schema is not None + and "time" in schema + and "value" in schema ): - schema = self.dataset.input_processors[key].schema() - value = val[schema.index("value")] if "value" in schema else val[0] + value = val[schema.index("value")] + mask = val[schema.index("mask")] if "mask" in schema else None + elif len(val) == 2: + first, second = val[0], val[1] + if ( + isinstance(second, torch.Tensor) + and second.dtype == torch.bool + ): + value = first + mask = second + elif ( + isinstance(first, torch.Tensor) + and first.is_floating_point() + and isinstance(second, torch.Tensor) + and not second.is_floating_point() + ): + # (time, value) + value = second + mask = None + else: + value = first + mask = None + elif len(val) >= 3: + value = val[1] mask = ( - val[schema.index("mask")] - if "mask" in schema - else (val[1] if len(val) > 1 else None) + val[2] + if isinstance(val[2], torch.Tensor) + and val[2].dtype == torch.bool + else None ) + elif schema is not None and "value" in schema: + value = val[schema.index("value")] + mask = val[schema.index("mask")] if "mask" in schema else None else: value = val[0] - mask = val[1] if len(val) > 1 else None + mask = None + cleaned_kwargs[key] = value raw_masks[key] = mask if isinstance(mask, torch.Tensor) else None else: diff --git a/tests/core/test_udc.py b/tests/core/test_udc.py index a104d75e16..ecc006749e 100644 --- a/tests/core/test_udc.py +++ b/tests/core/test_udc.py @@ -271,6 +271,9 @@ def test_intra_visit_pooling_modes(self): out = model(**batch) self.assertIn("loss", out) self.assertTrue(torch.isfinite(out["loss"])) + self.assertIn("embed", out) + self.assertEqual(out["embed"].shape, (2, 16)) + self.assertTrue(torch.isfinite(out["embed"]).all()) def test_inference_without_labels(self): dataset = create_sample_dataset( @@ -517,6 +520,25 @@ def test_unsupported_high_dim_feature(self): model(conditions=torch.zeros((2, 3, 4, 5))) model.embedding_model.forward = original_embed + def test_time_value_tuple_inputs(self): + """Verifies (time, value) tuple inputs compute mask from embeddings.""" + dataset = create_sample_dataset( + samples=self.samples, + input_schema=self.input_schema, + output_schema={"label": "binary"}, + ) + model = UDC(dataset=dataset, embedding_dim=16, hidden_dim=16) + loader = get_dataloader(dataset, batch_size=2) + batch = next(iter(loader)) + + cond_val = batch["conditions"] + fake_time = torch.zeros_like(cond_val, dtype=torch.float32) + batch["conditions"] = (fake_time, cond_val) + out = model(**batch) + self.assertIn("logit", out) + self.assertEqual(out["logit"].shape, (2, 1)) + self.assertTrue(torch.isfinite(out["logit"]).all()) + if __name__ == "__main__": unittest.main()