From 5ac1caab1f9a03d79cc57ec937cda61871930375 Mon Sep 17 00:00:00 2001 From: Rian Date: Tue, 3 Nov 2026 02:49:58 -0500 Subject: [PATCH 01/17] Give time embeddings a 10-year multi-scale span. Wavelengths are now log-spaced from 1 hour to 10 years instead of normalizing every frequency by 720 hours, which aliased any stay past 30 days onto the first. The model default follows the new span. Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95 --- pyhealth/models/unified_embedding.py | 66 +++++++++++++++++++++------- tests/core/test_unified_embedding.py | 17 ++++++- 2 files changed, 65 insertions(+), 18 deletions(-) diff --git a/pyhealth/models/unified_embedding.py b/pyhealth/models/unified_embedding.py index 7619d2de53..7b3a4291bb 100644 --- a/pyhealth/models/unified_embedding.py +++ b/pyhealth/models/unified_embedding.py @@ -35,10 +35,13 @@ class SinusoidalTimeEmbedding(nn.Module): - """Continuous sinusoidal embedding for scalar time values (in hours). + """Multi-scale sinusoidal embedding for times in hours. - Identical in spirit to the positional encoding in "Attention is All You - Need" but operating on real-valued timestamps rather than integer positions. + Wavelengths are spaced geometrically from ``min_hours`` (within-stay + resolution) to ``max_hours`` (longitudinal span). The previous encoding + mapped ``t / 720 * 2π``, so every frequency wrapped every 30 days: a later + stay at +9606h produced the same embedding as +6h even after the task + stopped resetting the clock. Examples: >>> embedding = SinusoidalTimeEmbedding(dim=2, max_hours=24.0) @@ -50,30 +53,44 @@ class SinusoidalTimeEmbedding(nn.Module): Args: dim: Output embedding dimension (must be even). - max_hours: Maximum expected time value in hours. Values are normalised - to ``[0, 2π]`` before the sin/cos projection. Default 720 (30 days). + max_hours: Longest wavelength in hours. Default 87600 (10 years). + min_hours: Shortest wavelength in hours. Default 1.0. Shape: Input: ``(*, )`` float tensor of times in hours Output: ``(*, dim)`` """ - def __init__(self, dim: int, max_hours: float = 720.0): + def __init__( + self, + dim: int, + max_hours: float = 87600.0, + min_hours: float = 1.0, + ): super().__init__() assert dim % 2 == 0, f"dim must be even, got {dim}" + if min_hours <= 0 or max_hours <= min_hours: + raise ValueError( + f"need 0 < min_hours < max_hours, got min={min_hours}, max={max_hours}" + ) self.dim = dim - self.max_hours = max_hours + self.max_hours = float(max_hours) + self.min_hours = float(min_hours) half = dim // 2 - freqs = torch.exp( - -math.log(10000.0) * torch.arange(half, dtype=torch.float32) / max(half - 1, 1) + periods = torch.exp( + torch.linspace( + math.log(self.min_hours), + math.log(self.max_hours), + half, + dtype=torch.float32, + ) ) - self.register_buffer("freqs", freqs) # (dim//2,) + self.register_buffer("freqs", 2 * math.pi / periods) def forward(self, t: torch.Tensor) -> torch.Tensor: """:param t: ``(...,)`` float, times in hours.""" - t_norm = t / self.max_hours * 2 * math.pi # (...,) - args = t_norm.unsqueeze(-1) * self.freqs # (..., dim//2) - return torch.cat([args.sin(), args.cos()], dim=-1) # (..., dim) + args = t.unsqueeze(-1).to(dtype=self.freqs.dtype) * self.freqs + return torch.cat([args.sin(), args.cos()], dim=-1) def _build_image_encoder(embedding_dim: int) -> nn.Module: @@ -136,8 +153,8 @@ class UnifiedMultimodalEmbeddingModel(nn.Module): ``dataset.input_processors`` directly. embedding_dim: Shared embedding dimension ``E'``. time_embedding: ``"sinusoidal"`` (default) or ``"learned"``. - max_time_hours: Normalisation constant for the time embedding. - Defaults to 720 h (30 days). + max_time_hours: Longest wavelength of the time embedding, in hours. + Defaults to 87600 (10 years). Shortest wavelength is 1 hour. Example:: @@ -149,6 +166,23 @@ class UnifiedMultimodalEmbeddingModel(nn.Module): out = model(inputs) seq = out["sequence"] # (B, S_total, 128) mask = out["mask"] # (B, S_total) float, 1=valid 0=pad + + Minimal example: + + >>> import torch + >>> from pyhealth.processors import StageNetProcessor + >>> from pyhealth.models.unified_embedding import ( + ... UnifiedMultimodalEmbeddingModel, + ... ) + >>> proc = StageNetProcessor() + >>> proc.fit([{"codes": ([0.0], ["A"])}], "codes") + >>> model = UnifiedMultimodalEmbeddingModel({"codes": proc}, embedding_dim=8) + >>> out = model({"codes": { + ... "value": torch.zeros(1, 1, dtype=torch.long), + ... "time": torch.zeros(1, 1), + ... }}) + >>> out["sequence"].shape + torch.Size([1, 1, 8]) """ def __init__( @@ -156,7 +190,7 @@ def __init__( processors: dict[str, Any], embedding_dim: int = 128, time_embedding: str = "sinusoidal", - max_time_hours: float = 720.0, + max_time_hours: float = 87600.0, ): super().__init__() self.embedding_dim = embedding_dim diff --git a/tests/core/test_unified_embedding.py b/tests/core/test_unified_embedding.py index 1b34c0d5ac..4c1033b005 100644 --- a/tests/core/test_unified_embedding.py +++ b/tests/core/test_unified_embedding.py @@ -16,14 +16,27 @@ def test_dim_two_is_finite(self): self.assertTrue(torch.isfinite(result).all()) def test_standard_dimension_values_are_unchanged(self): + # Wavelengths run 1h..24h here; the old t/720 formulation wrapped + # every frequency every 30 days, aliasing later stays onto earlier ones. embedding = SinusoidalTimeEmbedding(dim=6, max_hours=24.0) time = torch.tensor([6.0]) - frequencies = torch.tensor([1.0, 0.01, 0.0001]) - arguments = time.unsqueeze(-1) / 24.0 * 2 * math.pi * frequencies + periods = torch.exp(torch.linspace(math.log(1.0), math.log(24.0), 3)) + arguments = time.unsqueeze(-1) * (2 * math.pi / periods) expected = torch.cat([arguments.sin(), arguments.cos()], dim=-1) self.assertTrue(torch.allclose(embedding(time), expected)) + def test_long_span_stays_monotonic_in_phase(self): + embedding = SinusoidalTimeEmbedding(dim=6) + early = embedding(torch.tensor([6.0])) + late = embedding(torch.tensor([9606.0])) + + self.assertFalse(torch.allclose(early, late)) + + def test_invalid_span_raises(self): + with self.assertRaises(ValueError): + SinusoidalTimeEmbedding(dim=6, max_hours=1.0, min_hours=24.0) + if __name__ == "__main__": unittest.main() From c6ca07fb2721398750252dabfeed91b4bbc40c87 Mon Sep 17 00:00:00 2001 From: Rian Date: Tue, 3 Nov 2026 02:50:36 -0500 Subject: [PATCH 02/17] Reuse unimodal encoders and pool patch image tokens in the unified model. Fields accept pre-built EmbeddingModel, VisionEmbeddingModel, or TextEmbedding modules through field_embeddings instead of always training new encoders. The default image encoder is now PatchEmbedding with mean pooling, matching VisionEmbeddingModel, replacing the resnet18 stub. Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95 --- pyhealth/models/unified_embedding.py | 251 ++++++++++++++++++++----- tests/core/test_unified_field_reuse.py | 107 +++++++++++ 2 files changed, 315 insertions(+), 43 deletions(-) create mode 100644 tests/core/test_unified_field_reuse.py diff --git a/pyhealth/models/unified_embedding.py b/pyhealth/models/unified_embedding.py index 7b3a4291bb..bb21869cb4 100644 --- a/pyhealth/models/unified_embedding.py +++ b/pyhealth/models/unified_embedding.py @@ -29,6 +29,7 @@ import torch.nn as nn from pyhealth.processors.base_processor import ModalityType, TemporalFeatureProcessor +from pyhealth.models.vision_embedding import PatchEmbedding # ── Helpers ─────────────────────────────────────────────────────────────────── @@ -93,29 +94,12 @@ def forward(self, t: torch.Tensor) -> torch.Tensor: return torch.cat([args.sin(), args.cos()], dim=-1) -def _build_image_encoder(embedding_dim: int) -> nn.Module: - """Lightweight 5-layer CNN encoder: C × H × W → embedding_dim. +class _MeanPool(nn.Module): + """Pool a sequence of patch embeddings to a single vector via global mean.""" - Uses ``torchvision.models.resnet18`` pre-trained backbone, strips the - final FC layer, and adds a projection to ``embedding_dim``. Falls back to - a toy Conv-pool-flatten network if torchvision is not installed. - """ - try: - import torchvision.models as tv - - backbone = tv.resnet18(weights=None) - in_features = backbone.fc.in_features - backbone.fc = nn.Linear(in_features, embedding_dim) - return backbone - except ImportError: - # Minimal fallback: single conv → global avg pool → linear - return nn.Sequential( - nn.Conv2d(3, 32, 3, padding=1), - nn.ReLU(), - nn.AdaptiveAvgPool2d(1), - nn.Flatten(), - nn.Linear(32, embedding_dim), - ) + def forward(self, x: torch.Tensor) -> torch.Tensor: + # (B, num_patches, E) -> (B, E) + return x.mean(dim=1) # ── Main model ─────────────────────────────────────────────────────────────── @@ -147,6 +131,15 @@ class UnifiedMultimodalEmbeddingModel(nn.Module): 6. Add ``SinusoidalTimeEmbedding(time)`` + ``type_embedding(modality_idx)``. 7. Return ``{"sequence", "time", "mask", "type_ids"}``. + Unimodal model reuse via ``field_embeddings``:: + + vision_model = VisionEmbeddingModel(dataset, embedding_dim=128) + unified = UnifiedMultimodalEmbeddingModel( + processors=dataset.input_processors, + embedding_dim=128, + field_embeddings={"chest_xray": vision_model}, + ) + Args: processors: ``dict[field_name, TemporalFeatureProcessor]`` — the processors for each temporal field in the dataset. Pass @@ -155,6 +148,21 @@ class UnifiedMultimodalEmbeddingModel(nn.Module): time_embedding: ``"sinusoidal"`` (default) or ``"learned"``. max_time_hours: Longest wavelength of the time embedding, in hours. Defaults to 87600 (10 years). Shortest wavelength is 1 hour. + image_size: Image size (H=W) assumed for IMAGE fields when using + PatchEmbedding. Defaults to 224. + image_channels: Number of input channels for IMAGE fields. Defaults to 3. + patch_size: Patch size for IMAGE PatchEmbedding encoder. Defaults to 16. + image_pool: Pooling strategy applied to IMAGE patch tokens to produce + one vector per image event. Only ``"mean"`` (global mean pooling) + is currently implemented. Defaults to ``"mean"``. + field_embeddings: Optional mapping of field names to pre-built unimodal + embedding models (``EmbeddingModel``, ``VisionEmbeddingModel``, or + ``TextEmbedding``). The core encoder module is extracted from each + pre-built model; fields not present here use internally-built + encoders. Defaults to None. + freeze_text_encoder: If True, freeze TEXT encoder weights + (``requires_grad=False``) so notes encode deterministically. + Defaults to False. Example:: @@ -191,9 +199,23 @@ def __init__( embedding_dim: int = 128, time_embedding: str = "sinusoidal", max_time_hours: float = 87600.0, + image_size: int = 224, + image_channels: int = 3, + patch_size: int = 16, + image_pool: str = "mean", + field_embeddings: dict[str, Any] | None = None, + freeze_text_encoder: bool = False, ): super().__init__() - self.embedding_dim = embedding_dim + if image_pool != "mean": + raise NotImplementedError( + f"Only image_pool='mean' is implemented, got {image_pool!r}." + ) + self._embedding_dim = embedding_dim + self._freeze_text_encoder = freeze_text_encoder + self._frozen_text_fields: set[str] = set() + self.image_pool = image_pool + _field_embeddings = field_embeddings or {} self.encoders: nn.ModuleDict = nn.ModuleDict() self.projections: nn.ModuleDict = nn.ModuleDict() @@ -210,35 +232,35 @@ def __init__( m = processor.modality() self.modality_types[field_name] = m + pre_built = _field_embeddings.get(field_name) if m == ModalityType.CODE: - vocab_size = processor.value_dim() - self.encoders[field_name] = nn.Embedding( - vocab_size, embedding_dim, padding_idx=0 + self.encoders[field_name] = self._build_code_encoder( + field_name, processor, pre_built, embedding_dim ) elif m == ModalityType.TEXT: - if processor.is_token(): - from transformers import AutoModel - - bert = AutoModel.from_pretrained(processor.tokenizer_model) - self.encoders[field_name] = bert - hidden = bert.config.hidden_size - if hidden != embedding_dim: - self.projections[field_name] = nn.Linear(hidden, embedding_dim) - else: - raise ValueError( - f"TEXT processor '{field_name}' must use a tokenizer " - f"(set tokenizer_model=...) to be used with " - f"UnifiedMultimodalEmbeddingModel." - ) + self._build_text_encoder( + field_name, processor, pre_built, embedding_dim, + freeze=freeze_text_encoder, + ) elif m == ModalityType.IMAGE: - self.encoders[field_name] = _build_image_encoder(embedding_dim) + self.encoders[field_name] = self._build_image_encoder( + field_name, + processor, + pre_built, + embedding_dim, + image_size, + image_channels, + patch_size, + image_pool, + ) elif m in (ModalityType.NUMERIC, ModalityType.SIGNAL): - in_features = processor.value_dim() - self.encoders[field_name] = nn.Linear(in_features, embedding_dim) + self.encoders[field_name] = self._build_numeric_encoder( + field_name, processor, pre_built, embedding_dim + ) else: raise NotImplementedError( @@ -258,6 +280,149 @@ def __init__( else: raise NotImplementedError("Only 'sinusoidal' time embedding is implemented.") + # ── Encoder builders ────────────────────────────────────────────────────── + + def _build_code_encoder( + self, + field_name: str, + processor: TemporalFeatureProcessor, + pre_built: Any, + embedding_dim: int, + ) -> nn.Module: + """Build CODE encoder: nn.Embedding, optionally from a pre-built EmbeddingModel.""" + if ( + pre_built is not None + and hasattr(pre_built, "embedding_layers") + and field_name in pre_built.embedding_layers + ): + layer = pre_built.embedding_layers[field_name] + pre_dim = getattr(pre_built, "embedding_dim", embedding_dim) + if pre_dim != embedding_dim: + return nn.Sequential(layer, nn.Linear(pre_dim, embedding_dim)) + return layer + + vocab_size = processor.value_dim() + return nn.Embedding(vocab_size, embedding_dim, padding_idx=0) + + def _build_text_encoder( + self, + field_name: str, + processor: TemporalFeatureProcessor, + pre_built: Any, + embedding_dim: int, + freeze: bool = False, + ) -> None: + """Build TEXT encoder: BERT + projection, optionally from TextEmbedding.""" + + def _set_projection( + pre_dim: int, proj_source: nn.Module | None = None + ) -> None: + if pre_dim != embedding_dim: + if proj_source is not None: + self.projections[field_name] = nn.Sequential( + proj_source, + nn.Linear(pre_dim, embedding_dim), + ) + else: + self.projections[field_name] = nn.Linear(pre_dim, embedding_dim) + elif proj_source is not None: + self.projections[field_name] = proj_source + + if ( + pre_built is not None + and hasattr(pre_built, "transformer") + and hasattr(pre_built, "fc") + ): + self.encoders[field_name] = pre_built.transformer + if freeze: + for p in pre_built.transformer.parameters(): + p.requires_grad = False + self._frozen_text_fields.add(field_name) + pre_dim = getattr(pre_built, "embedding_dim", embedding_dim) + _set_projection(pre_dim, pre_built.fc) + return + + if processor.is_token(): + from transformers import AutoModel + + bert = AutoModel.from_pretrained(processor.tokenizer_model) + if freeze: + for p in bert.parameters(): + p.requires_grad = False + self._frozen_text_fields.add(field_name) + self.encoders[field_name] = bert + hidden = bert.config.hidden_size + if hidden != embedding_dim: + self.projections[field_name] = nn.Linear(hidden, embedding_dim) + else: + raise ValueError( + f"TEXT processor '{field_name}' must either supply a pre-built " + f"TextEmbedding via field_embeddings or use a tokenizer " + f"(set tokenizer_model=...) to be used with " + f"UnifiedMultimodalEmbeddingModel." + ) + + def _build_image_encoder( + self, + field_name: str, + processor: TemporalFeatureProcessor, + pre_built: Any, + embedding_dim: int, + image_size: int, + image_channels: int, + patch_size: int, + image_pool: str, + ) -> nn.Module: + """Build IMAGE encoder: backbone + pool, optionally from VisionEmbeddingModel.""" + pool_layers: dict[str, nn.Module] = {"mean": _MeanPool()} + pool_layer = pool_layers[image_pool] + + if ( + pre_built is not None + and hasattr(pre_built, "embedding_layers") + and field_name in pre_built.embedding_layers + ): + backbone = pre_built.embedding_layers[field_name] + pre_dim = getattr(pre_built, "embedding_dim", embedding_dim) + if pre_dim != embedding_dim: + return nn.Sequential( + backbone, pool_layer, nn.Linear(pre_dim, embedding_dim) + ) + return nn.Sequential(backbone, pool_layer) + + _image_size = getattr(processor, "image_size", image_size) + _in_channels = getattr(processor, "in_channels", image_channels) + return nn.Sequential( + PatchEmbedding(_image_size, patch_size, _in_channels, embedding_dim), + pool_layer, + ) + + def _build_numeric_encoder( + self, + field_name: str, + processor: TemporalFeatureProcessor, + pre_built: Any, + embedding_dim: int, + ) -> nn.Module: + """Build NUMERIC/SIGNAL encoder: nn.Linear, optionally from EmbeddingModel.""" + if ( + pre_built is not None + and hasattr(pre_built, "embedding_layers") + and field_name in pre_built.embedding_layers + ): + layer = pre_built.embedding_layers[field_name] + pre_dim = getattr(pre_built, "embedding_dim", embedding_dim) + if pre_dim != embedding_dim: + return nn.Sequential(layer, nn.Linear(pre_dim, embedding_dim)) + return layer + + in_features = processor.value_dim() + return nn.Linear(in_features, embedding_dim) + + @property + def embedding_dim(self) -> int: + return self._embedding_dim + # ── Forward ─────────────────────────────────────────────────────────────── def forward( diff --git a/tests/core/test_unified_field_reuse.py b/tests/core/test_unified_field_reuse.py new file mode 100644 index 0000000000..e32f3369d1 --- /dev/null +++ b/tests/core/test_unified_field_reuse.py @@ -0,0 +1,107 @@ +"""Field-embedding reuse and patch image encoder for the unified model.""" + +import unittest +from types import SimpleNamespace + +import torch +import torch.nn as nn + +from pyhealth.processors import ( + StageNetProcessor, + StageNetTensorProcessor, + TimeImageProcessor, + TupleTimeTextProcessor, +) +from pyhealth.models.unified_embedding import UnifiedMultimodalEmbeddingModel + + +def _code_processor(): + proc = StageNetProcessor() + proc.fit([{"codes": ([0.0], ["A", "B"])}], "codes") + return proc + + +class TestFieldEmbeddingReuse(unittest.TestCase): + def test_code_encoder_reuses_prebuilt_layer(self): + proc = _code_processor() + layer = nn.Embedding(proc.value_dim(), 8, padding_idx=0) + pre = SimpleNamespace( + embedding_layers=nn.ModuleDict({"codes": layer}), embedding_dim=8 + ) + model = UnifiedMultimodalEmbeddingModel( + {"codes": proc}, embedding_dim=8, field_embeddings={"codes": pre} + ) + self.assertIs(model.encoders["codes"], layer) + + def test_code_reuse_projects_when_dims_differ(self): + proc = _code_processor() + layer = nn.Embedding(proc.value_dim(), 4, padding_idx=0) + pre = SimpleNamespace( + embedding_layers=nn.ModuleDict({"codes": layer}), embedding_dim=4 + ) + model = UnifiedMultimodalEmbeddingModel( + {"codes": proc}, embedding_dim=8, field_embeddings={"codes": pre} + ) + out = model( + { + "codes": { + "value": torch.zeros(1, 2, dtype=torch.long), + "time": torch.zeros(1, 2), + } + } + ) + self.assertEqual(out["sequence"].shape, (1, 2, 8)) + + def test_vision_reuse_wraps_backbone_with_mean_pool(self): + proc = TimeImageProcessor(image_size=16) + backbone = nn.Identity() + pre = SimpleNamespace( + embedding_layers=nn.ModuleDict({"cxr": backbone}), embedding_dim=8 + ) + model = UnifiedMultimodalEmbeddingModel( + {"cxr": proc}, embedding_dim=8, field_embeddings={"cxr": pre} + ) + encoder = model.encoders["cxr"] + self.assertIsInstance(encoder, nn.Sequential) + self.assertIs(encoder[0], backbone) + + def test_text_freeze_marks_field_frozen(self): + proc = TupleTimeTextProcessor() + transformer = nn.Linear(4, 4) + pre = SimpleNamespace(transformer=transformer, fc=nn.Linear(4, 8)) + model = UnifiedMultimodalEmbeddingModel( + {"notes": proc}, + embedding_dim=8, + field_embeddings={"notes": pre}, + freeze_text_encoder=True, + ) + self.assertIn("notes", model._frozen_text_fields) + self.assertTrue( + all(not p.requires_grad for p in transformer.parameters()) + ) + + def test_default_image_encoder_is_patch_plus_mean_pool(self): + proc = TimeImageProcessor(image_size=16) + model = UnifiedMultimodalEmbeddingModel( + {"cxr": proc}, embedding_dim=8, image_size=16, patch_size=8 + ) + out = model( + { + "cxr": { + "value": torch.zeros(1, 2, 3, 16, 16), + "time": torch.zeros(1, 2), + } + } + ) + self.assertEqual(out["sequence"].shape, (1, 2, 8)) + + def test_unknown_image_pool_raises(self): + proc = TimeImageProcessor(image_size=16) + with self.assertRaises(NotImplementedError): + UnifiedMultimodalEmbeddingModel( + {"cxr": proc}, embedding_dim=8, image_pool="max" + ) + + +if __name__ == "__main__": + unittest.main() From 3f3c3f229276f80de3d313241d162a761be42871 Mon Sep 17 00:00:00 2001 From: Rian Date: Tue, 3 Nov 2026 02:50:52 -0500 Subject: [PATCH 03/17] Flatten nested code events and expose the content embedding. A (B, S, C) code field now encodes to (B, S*C, E) with time and mask expanded along the codes instead of failing on the 3D input. Forward also returns token_emb, the pre-time/type content sequence for masked-modeling targets. Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95 --- pyhealth/models/unified_embedding.py | 56 ++++++++++++++++- tests/core/test_unified_nested_codes.py | 84 +++++++++++++++++++++++++ 2 files changed, 139 insertions(+), 1 deletion(-) create mode 100644 tests/core/test_unified_nested_codes.py diff --git a/pyhealth/models/unified_embedding.py b/pyhealth/models/unified_embedding.py index bb21869cb4..d61800ca67 100644 --- a/pyhealth/models/unified_embedding.py +++ b/pyhealth/models/unified_embedding.py @@ -23,6 +23,7 @@ from __future__ import annotations import math +import warnings from typing import Any import torch @@ -273,6 +274,7 @@ def __init__( mod: i for i, mod in enumerate(unique_modalities) } self.type_embedding = nn.Embedding(len(unique_modalities), embedding_dim) + self._warned_nested_code_flatten = False # Time embedding if time_embedding == "sinusoidal": @@ -444,6 +446,8 @@ def forward( * ``"time"`` — ``(B, S_total)`` timestamps (hours) * ``"mask"`` — ``(B, S_total)`` 1=real event, 0=padding * ``"type_ids"`` — ``(B, S_total)`` modality index per event + * ``"token_emb"`` — ``(B, S_total, E')`` content-only event embedding + (before time/type are added); the target for masked modeling. """ all_embeddings: list[torch.Tensor] = [] all_times: list[torch.Tensor] = [] @@ -464,7 +468,51 @@ def forward( # ── Encode ──────────────────────────────────────────────────── if modality == ModalityType.CODE: - emb = encoder(value) # (B, S, E') + # CODE values may be either: + # - flat indices: (B, S) + # - nested indices: (B, S, C) where C is codes-per-event + # For nested indices, flatten to (B, S*C, E') so code-level + # detail is preserved, and expand time/mask to match. + if value.dim() == 2: + emb = encoder(value) # (B, S, E') + elif value.dim() == 3: + bsz, seq_len, per_event_codes = value.shape + token_emb = encoder(value.long()) # (B, S, C, E') + emb = token_emb.reshape(bsz, seq_len * per_event_codes, -1) + + if not self._warned_nested_code_flatten: + warnings.warn( + ( + "UnifiedMultimodalEmbeddingModel detected " + f"nested CODE input for '{field_name}' with " + f"shape={tuple(value.shape)}. Flattening to " + f"(B, S*C, E) and repeating time along C." + ), + stacklevel=2, + ) + self._warned_nested_code_flatten = True + + if time is not None: + time = ( + time.unsqueeze(-1) + .expand(-1, -1, per_event_codes) + .reshape(bsz, seq_len * per_event_codes) + ) + + if mask is not None: + if mask.dim() == 2: + mask = ( + mask.unsqueeze(-1) + .expand(-1, -1, per_event_codes) + .reshape(bsz, seq_len * per_event_codes) + ) + elif mask.dim() == 3: + mask = mask.reshape(bsz, seq_len * per_event_codes) + else: + raise ValueError( + f"Unsupported CODE value rank for '{field_name}': " + f"shape={tuple(value.shape)}" + ) elif modality == ModalityType.TEXT: b, n, l = value.shape @@ -531,4 +579,10 @@ def forward( "time": cat_time, # (B, S_total) "mask": cat_mask, # (B, S_total) "type_ids": cat_types, # (B, S_total) + # Per-event content embedding BEFORE time/type are added (same sort + # order as ``sequence``). Masked-modeling pretrainers should + # reconstruct THIS rather than ``sequence``: the time/type + # components are largely recoverable from event position, so + # including them in the target dilutes the content signal. + "token_emb": cat_emb, # (B, S_total, E') } diff --git a/tests/core/test_unified_nested_codes.py b/tests/core/test_unified_nested_codes.py new file mode 100644 index 0000000000..bfc4a8942b --- /dev/null +++ b/tests/core/test_unified_nested_codes.py @@ -0,0 +1,84 @@ +"""Nested CODE flattening and content-embedding output for the unified model.""" + +import unittest +import warnings + +import torch + +from pyhealth.processors import StageNetProcessor +from pyhealth.models.unified_embedding import UnifiedMultimodalEmbeddingModel + + +class TestNestedCodes(unittest.TestCase): + def _model(self): + proc = StageNetProcessor() + proc.fit([{"codes": ([0.0], [["A", "B"]])}], "codes") + return UnifiedMultimodalEmbeddingModel({"codes": proc}, embedding_dim=8) + + def test_nested_codes_flatten_with_time_expansion(self): + model = self._model() + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + out = model( + { + "codes": { + "value": torch.zeros(1, 2, 3, dtype=torch.long), + "time": torch.tensor([[0.0, 5.0]]), + } + } + ) + self.assertEqual(out["sequence"].shape, (1, 6, 8)) + self.assertEqual(out["time"].shape, (1, 6)) + # Each visit time repeats along its codes after the time sort. + self.assertTrue( + torch.equal( + out["time"], torch.tensor([[0.0, 0.0, 0.0, 5.0, 5.0, 5.0]]) + ) + ) + + def test_warns_once_about_flattening(self): + model = self._model() + inputs = { + "codes": { + "value": torch.zeros(1, 1, 2, dtype=torch.long), + "time": torch.zeros(1, 1), + } + } + with warnings.catch_warnings(record=True) as seen: + warnings.simplefilter("always") + model(inputs) + model(inputs) + flatten = [w for w in seen if "Flattening" in str(w.message)] + self.assertEqual(len(flatten), 1) + + def test_token_emb_is_content_before_time_and_type(self): + model = self._model() + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + out = model( + { + "codes": { + "value": torch.zeros(1, 2, dtype=torch.long), + "time": torch.zeros(1, 2), + } + } + ) + self.assertEqual(out["token_emb"].shape, out["sequence"].shape) + # token_emb differs from sequence: time/type terms are added on top. + self.assertFalse(torch.equal(out["token_emb"], out["sequence"])) + + def test_unsupported_code_rank_raises(self): + model = self._model() + with self.assertRaises(ValueError): + model( + { + "codes": { + "value": torch.zeros(1, 1, 1, 1, dtype=torch.long), + "time": torch.zeros(1, 1), + } + } + ) + + +if __name__ == "__main__": + unittest.main() From 50e0e60de39d839318c00ad82a27964cb3b6e469 Mon Sep 17 00:00:00 2001 From: Rian Date: Tue, 3 Nov 2026 03:31:19 -0500 Subject: [PATCH 04/17] Standardize numerics before projection and bound the content scale. NUMERIC fields accept standardizer modules fed by the sibling {field}_mask observation flags. A {field}_mask input is skipped as a modality ONLY when {field} has a registered entry in numeric_standardizers; a field merely named x_mask with no standardizer stays a normal modality. Content passes through parameter-free layer norm so raw feature magnitude cannot decide the sum, and padded slots are zeroed for mask-ignoring consumers. normalize_content defaults to True, which CHANGES outputs versus the previous unnormalized sum (content + time + type): the content term is rescaled to unit variance per event before the additive terms. The default is on because raw feature magnitude is an accident of feature scaling, not a modelling decision. Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95 --- pyhealth/models/unified_embedding.py | 90 ++++++++++++++-- tests/core/test_unified_standardize.py | 139 +++++++++++++++++++++++++ 2 files changed, 222 insertions(+), 7 deletions(-) create mode 100644 tests/core/test_unified_standardize.py diff --git a/pyhealth/models/unified_embedding.py b/pyhealth/models/unified_embedding.py index d61800ca67..2e47c6fba3 100644 --- a/pyhealth/models/unified_embedding.py +++ b/pyhealth/models/unified_embedding.py @@ -27,6 +27,7 @@ from typing import Any import torch +import torch.nn.functional as F import torch.nn as nn from pyhealth.processors.base_processor import ModalityType, TemporalFeatureProcessor @@ -164,6 +165,21 @@ class UnifiedMultimodalEmbeddingModel(nn.Module): freeze_text_encoder: If True, freeze TEXT encoder weights (``requires_grad=False``) so notes encode deterministically. Defaults to False. + normalize_content: If True, apply parameter-free layer norm to the + content term so one modality's raw magnitude cannot drown out the + time/type terms. Defaults to True. This CHANGES outputs versus the + previous unnormalized sum (content + time + type): the content + term is rescaled to unit variance per event before the time and + type terms are added. The default is True because raw feature + magnitude is an accident of feature scaling, not a modelling + decision. + numeric_standardizers: Optional mapping of NUMERIC/SIGNAL field names + to modules called as ``standardizer(value, observed)`` BEFORE the + projection, where ``observed`` comes from the sibling + ``{field}_mask`` field. Defaults to None. A ``{field}_mask`` input + is skipped as a modality ONLY when ``field`` has a registered + entry here; a field merely named ``x_mask`` with no standardizer + stays a normal modality. Example:: @@ -206,6 +222,8 @@ def __init__( image_pool: str = "mean", field_embeddings: dict[str, Any] | None = None, freeze_text_encoder: bool = False, + normalize_content: bool = True, + numeric_standardizers: dict[str, Any] | None = None, ): super().__init__() if image_pool != "mean": @@ -216,6 +234,10 @@ def __init__( self._freeze_text_encoder = freeze_text_encoder self._frozen_text_fields: set[str] = set() self.image_pool = image_pool + self.normalize_content = normalize_content + # Statistics live in buffers, so they travel in state_dict. A checkpoint + # therefore applies at inference the same transform it trained under. + self.numeric_standardizers = nn.ModuleDict(numeric_standardizers or {}) _field_embeddings = field_embeddings or {} self.encoders: nn.ModuleDict = nn.ModuleDict() @@ -455,9 +477,23 @@ def forward( all_types: list[torch.Tensor] = [] for field_name, feat_dict in inputs.items(): - value = feat_dict["value"] # (B, N_i, ...) or (B, S, F) - time = feat_dict["time"] # (B, N_i) - mask = feat_dict.get("mask") + if field_name.endswith("_mask") and field_name[: -len("_mask")] in self.numeric_standardizers: + # Observation-flag sibling consumed by the standardiser; not a + # modality of its own. Encoding it would duplicate every lab + # timestamp with a 0/1 vector. Skipped ONLY when the base + # field registered a standardiser: a field merely named + # ``x_mask`` with no standardiser stays a normal modality. + continue + value = feat_dict["value"] # (B, N_i, ...) or (B, S, F) + time = feat_dict["time"] # (B, N_i) + # Three different masks meet here and must not be conflated. + # mask token level, from the processor schema; this is the + # attention mask a text encoder needs. + # pad_mask event level, from the collator; which slots are real + # events rather than batch padding. + # {field}_mask a separate FIELD meaning "was this value + # observed", consumed by the standardiser below. + mask = feat_dict.get("mask") if time is None: # Fallback: treat every event as occurring at t=0 @@ -531,7 +567,37 @@ def forward( emb = img_emb.view(b, n, -1) else: # NUMERIC / SIGNAL - emb = encoder(value) # (B, T, E') + # Standardise BEFORE the projection. The projection mixes the + # features, so a transform after it cannot correct a feature + # whose physical unit gives it 300 times the magnitude of + # another. + # nn.ModuleDict has no .get(), so the ternary stays. + standardizer = ( + self.numeric_standardizers[field_name] # noqa: SIM401 + if field_name in self.numeric_standardizers + else None + ) + if standardizer is not None: + # Observation flags live in the sibling ``{field}_mask`` + # FIELD, not in this field's dict. Reading the padding mask + # here would tell the standardiser that every real event + # was measured, which is exactly the distinction the + # standardiser exists to preserve. + sibling = inputs.get(f"{field_name}_mask") + obs = sibling["value"] if isinstance(sibling, dict) else None + if obs is None: + raise ValueError( + f"The standardiser for {field_name!r} needs a paired " + f"{field_name}_mask field in the batch." + ) + if obs.shape != value.shape: + raise ValueError( + f"{field_name}_mask has shape {tuple(obs.shape)}, " + f"which does not match {field_name} " + f"{tuple(value.shape)}." + ) + value = standardizer(value, obs.bool()) + emb = encoder(value) # (B, T, E') # ── Build event-level validity mask ─────────────────────────── if mask is None: @@ -570,9 +636,19 @@ def forward( cat_types = cat_types.gather(1, sort_idx) # ── Add time + type embeddings ──────────────────────────────────── - time_emb = self.time_embed(cat_time) # (B, S_total, E') - type_emb = self.type_embedding(cat_types) # (B, S_total, E') - final = cat_emb + time_emb + type_emb # (B, S_total, E') + time_emb = self.time_embed(cat_time) # (B, S_total, E') + type_emb = self.type_embedding(cat_types) # (B, S_total, E') + if self.normalize_content: + # Put the content term on the scale of the additive terms. Without + # this the sum is decided by whichever modality has the larger + # magnitude, which is an accident of feature scaling and not a + # modelling decision. F.layer_norm without weight or bias adds NO + # parameters, so an existing checkpoint still loads. + cat_emb = F.layer_norm(cat_emb, (cat_emb.shape[-1],)) + final = cat_emb + time_emb + type_emb + # Zero the padded slots so a consumer that ignores the mask, such as a + # mean pool, still cannot pick them up. + final = final * cat_mask.unsqueeze(-1).to(final.dtype) # (B, S_total, E') return { "sequence": final, # (B, S_total, E') diff --git a/tests/core/test_unified_standardize.py b/tests/core/test_unified_standardize.py new file mode 100644 index 0000000000..d277fde4ea --- /dev/null +++ b/tests/core/test_unified_standardize.py @@ -0,0 +1,139 @@ +"""Content norm, mask zeroing, and numeric standardizers for the unified model.""" + +import unittest + +import torch +import torch.nn as nn + +from pyhealth.processors import StageNetTensorProcessor +from pyhealth.models.unified_embedding import UnifiedMultimodalEmbeddingModel + + +class _Double(nn.Module): + """Test standardizer: records its inputs, doubles unobserved-safe values.""" + + def __init__(self): + super().__init__() + self.calls = [] + + def forward(self, value, observed): + self.calls.append((value.shape, observed.dtype)) + return value * 2.0 + + +def _labs_processor(): + proc = StageNetTensorProcessor() + proc.fit([{"labs": ([0.0], [[1.0, 2.0]])}], "labs") + return proc + + +class TestContentAssembly(unittest.TestCase): + def test_padded_slots_are_zeroed(self): + model = UnifiedMultimodalEmbeddingModel( + {"labs": _labs_processor()}, embedding_dim=8 + ) + out = model( + { + "labs": { + "value": torch.zeros(1, 2, 2), + "time": torch.zeros(1, 2), + "mask": torch.tensor([[1.0, 0.0]]), + } + } + ) + self.assertTrue(torch.equal(out["mask"], torch.tensor([[1.0, 0.0]]))) + self.assertTrue(bool((out["sequence"][0, 1] == 0).all())) + + def test_normalize_content_bounds_large_magnitudes(self): + proc = _labs_processor() + loud = UnifiedMultimodalEmbeddingModel( + {"labs": proc}, embedding_dim=8, normalize_content=True + ) + quiet = UnifiedMultimodalEmbeddingModel( + {"labs": proc}, embedding_dim=8, normalize_content=False + ) + quiet.load_state_dict(loud.state_dict()) + big = torch.full((1, 2, 2), 1000.0) + times = torch.zeros(1, 2) + seq_norm = loud({"labs": {"value": big, "time": times}})["sequence"] + seq_raw = quiet({"labs": {"value": big, "time": times}})["sequence"] + self.assertLess( + seq_norm.abs().max().item(), seq_raw.abs().max().item() / 100 + ) + + def test_standardizer_runs_before_projection(self): + std = _Double() + model = UnifiedMultimodalEmbeddingModel( + {"labs": _labs_processor()}, + embedding_dim=8, + numeric_standardizers={"labs": std}, + ) + out = model( + { + "labs": { + "value": torch.ones(1, 2, 2), + "time": torch.zeros(1, 2), + }, + "labs_mask": { + "value": torch.ones(1, 2, 2), + "time": torch.zeros(1, 2), + }, + } + ) + # The mask sibling is not a modality: only the 2 lab events surface. + self.assertEqual(out["sequence"].shape, (1, 2, 8)) + self.assertEqual(std.calls, [((1, 2, 2), torch.bool)]) + + def test_standardizer_without_sibling_raises(self): + model = UnifiedMultimodalEmbeddingModel( + {"labs": _labs_processor()}, + embedding_dim=8, + numeric_standardizers={"labs": _Double()}, + ) + with self.assertRaises(ValueError): + model( + {"labs": {"value": torch.ones(1, 1, 2), "time": torch.zeros(1, 1)}} + ) + + def test_standardizer_shape_mismatch_raises(self): + model = UnifiedMultimodalEmbeddingModel( + {"labs": _labs_processor()}, + embedding_dim=8, + numeric_standardizers={"labs": _Double()}, + ) + with self.assertRaises(ValueError): + model( + { + "labs": {"value": torch.ones(1, 2, 2), "time": torch.zeros(1, 2)}, + "labs_mask": { + "value": torch.ones(1, 3, 2), + "time": torch.zeros(1, 3), + }, + } + ) + + + def test_mask_field_without_standardizer_stays_a_modality(self): + model = UnifiedMultimodalEmbeddingModel( + {"labs": _labs_processor(), "labs_mask": _labs_processor()}, + embedding_dim=8, + ) + out = model( + { + "labs": { + "value": torch.ones(1, 2, 2), + "time": torch.zeros(1, 2), + }, + "labs_mask": { + "value": torch.zeros(1, 1, 2), + "time": torch.ones(1, 1), + }, + } + ) + # No standardizer registered for "labs": the "labs_mask" field is not + # consumed by anyone, so both fields encode (2 + 1 events). + self.assertEqual(out["sequence"].shape, (1, 3, 8)) + + +if __name__ == "__main__": + unittest.main() From b2e67cb5d144a47e099f2c600fb72bc11709b402 Mon Sep 17 00:00:00 2001 From: Rian Date: Tue, 3 Nov 2026 02:51:36 -0500 Subject: [PATCH 05/17] Keep frozen text encoders in eval when Trainer calls train(). nn.Module.train() re-enables dropout inside a frozen encoder even when every weight has requires_grad=False. Pin frozen fields back to eval so a frozen note embedding is deterministic across steps. Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95 --- pyhealth/models/unified_embedding.py | 13 ++++++ tests/core/test_unified_frozen_eval.py | 58 ++++++++++++++++++++++++++ 2 files changed, 71 insertions(+) create mode 100644 tests/core/test_unified_frozen_eval.py diff --git a/pyhealth/models/unified_embedding.py b/pyhealth/models/unified_embedding.py index 2e47c6fba3..06a42f69d9 100644 --- a/pyhealth/models/unified_embedding.py +++ b/pyhealth/models/unified_embedding.py @@ -447,6 +447,19 @@ def _build_numeric_encoder( def embedding_dim(self) -> int: return self._embedding_dim + def train(self, mode: bool = True) -> UnifiedMultimodalEmbeddingModel: + """Keep a frozen text encoder in eval mode. + + ``nn.Module.train()`` would enable dropout inside the encoder. Its + output would then change between passes even though every weight has + ``requires_grad=False``. That makes cached embeddings incorrect, and + it also makes a frozen encoder give a different answer to the same input. + """ + super().train(mode) + for field_name in self._frozen_text_fields: + self.encoders[field_name].eval() + return self + # ── Forward ─────────────────────────────────────────────────────────────── def forward( diff --git a/tests/core/test_unified_frozen_eval.py b/tests/core/test_unified_frozen_eval.py new file mode 100644 index 0000000000..baf4bbadf9 --- /dev/null +++ b/tests/core/test_unified_frozen_eval.py @@ -0,0 +1,58 @@ +"""Frozen text encoders stay in eval when Trainer calls train().""" + +from __future__ import annotations + +import unittest + +import torch +import torch.nn as nn + +from pyhealth.models.unified_embedding import UnifiedMultimodalEmbeddingModel +from pyhealth.processors.stagenet_processor import StageNetTensorProcessor + + +def _numeric_model(**kwargs) -> UnifiedMultimodalEmbeddingModel: + proc = StageNetTensorProcessor() + proc.fit([{"labs": ([0.0], [[1.0] * 10])}], "labs") + return UnifiedMultimodalEmbeddingModel( + {"labs": proc}, embedding_dim=8, freeze_text_encoder=True, **kwargs + ) + + +class TinyEnc(nn.Module): + def __init__(self): + super().__init__() + self.drop = nn.Dropout(p=0.9) + self.lin = nn.Linear(1, 8) + self.config = type("C", (), {"hidden_size": 8})() + + def forward(self, input_ids, attention_mask=None): + b, l = input_ids.shape + h = self.drop(torch.ones(b, l, 8)) + return type("O", (), {"last_hidden_state": h})() + + +class TestFrozenEncoderEval(unittest.TestCase): + def test_train_keeps_frozen_text_encoder_in_eval(self): + model = _numeric_model() + enc = TinyEnc() + model.encoders["notes"] = enc + model._frozen_text_fields.add("notes") + model.train() + self.assertTrue(model.training) + self.assertFalse(enc.training) + model.eval() + self.assertFalse(enc.training) + model.train() + self.assertFalse(enc.training) + + def test_unfrozen_fields_follow_train_mode(self): + model = _numeric_model() + enc = TinyEnc() + model.encoders["notes"] = enc + model.train() + self.assertTrue(enc.training) + + +if __name__ == "__main__": + unittest.main() From ad3c39c5f5c9623893893d143036e3b32503553b Mon Sep 17 00:00:00 2001 From: Rian Date: Tue, 3 Nov 2026 02:52:06 -0500 Subject: [PATCH 06/17] Avoid ambiguous -1 reshapes on batches with no note or image slots. Use the known embedding width instead of -1 when restoring the batch shape, and skip the image encoder entirely when a batch has zero image slots, since torch cannot infer -1 for a 0-element tensor. Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95 --- pyhealth/models/unified_embedding.py | 15 +++++-- tests/core/test_unified_empty_batch.py | 60 ++++++++++++++++++++++++++ 2 files changed, 72 insertions(+), 3 deletions(-) create mode 100644 tests/core/test_unified_empty_batch.py diff --git a/pyhealth/models/unified_embedding.py b/pyhealth/models/unified_embedding.py index 06a42f69d9..ca7b492757 100644 --- a/pyhealth/models/unified_embedding.py +++ b/pyhealth/models/unified_embedding.py @@ -571,13 +571,22 @@ def forward( cls_emb = out.last_hidden_state[:, 0, :] # (B*N, H) if field_name in self.projections: cls_emb = self.projections[field_name](cls_emb) - emb = cls_emb.view(b, n, -1) # (B, N, E') + # cls_emb.shape[-1] instead of -1: when b*n == 0 (no note + # slots in this batch), the -1 is ambiguous for a 0-element + # tensor and torch raises. + emb = cls_emb.view(b, n, cls_emb.shape[-1]) # (B, N, E') elif modality == ModalityType.IMAGE: b, n, c, h, w = value.shape flat_imgs = value.view(b * n, c, h, w) - img_emb = encoder(flat_imgs) # (B*N, E') - emb = img_emb.view(b, n, -1) + if b * n == 0: + # No image slots in this batch. reshape(0, -1) is + # ambiguous since -1 can be any value for 0 elements. + img_emb = value.new_zeros((0, self._embedding_dim)) + else: + img_emb = encoder(flat_imgs) # (B*N, E') + # Explicit dim instead of -1: same 0-element ambiguity. + emb = img_emb.view(b, n, img_emb.shape[-1]) else: # NUMERIC / SIGNAL # Standardise BEFORE the projection. The projection mixes the diff --git a/tests/core/test_unified_empty_batch.py b/tests/core/test_unified_empty_batch.py new file mode 100644 index 0000000000..826cc77cb3 --- /dev/null +++ b/tests/core/test_unified_empty_batch.py @@ -0,0 +1,60 @@ +"""Zero-slot text/image batches must not hit the ambiguous -1 reshape.""" + +import unittest + +import torch +import torch.nn as nn +from types import SimpleNamespace + +from pyhealth.processors import TimeImageProcessor, TupleTimeTextProcessor +from pyhealth.models.unified_embedding import UnifiedMultimodalEmbeddingModel + + +class TinyEnc(nn.Module): + def __init__(self): + super().__init__() + self.config = type("C", (), {"hidden_size": 8})() + + def forward(self, input_ids, attention_mask=None): + return type( + "O", (), {"last_hidden_state": torch.zeros(input_ids.shape[0], 4, 8)} + )() + + +class TestEmptyBatchReshape(unittest.TestCase): + def test_empty_note_slots_return_zero_length(self): + proc = TupleTimeTextProcessor() + pre = SimpleNamespace( + transformer=TinyEnc(), fc=nn.Identity(), embedding_dim=8 + ) + model = UnifiedMultimodalEmbeddingModel( + {"notes": proc}, embedding_dim=8, field_embeddings={"notes": pre} + ) + out = model( + { + "notes": { + "value": torch.zeros(1, 0, 4, dtype=torch.long), + "time": torch.zeros(1, 0), + } + } + ) + self.assertEqual(out["sequence"].shape, (1, 0, 8)) + + def test_empty_image_slots_return_zero_length(self): + proc = TimeImageProcessor(image_size=16) + model = UnifiedMultimodalEmbeddingModel( + {"cxr": proc}, embedding_dim=8, image_size=16, patch_size=8 + ) + out = model( + { + "cxr": { + "value": torch.zeros(1, 0, 3, 16, 16), + "time": torch.zeros(1, 0), + } + } + ) + self.assertEqual(out["sequence"].shape, (1, 0, 8)) + + +if __name__ == "__main__": + unittest.main() From 81964b0ceb5cb77271b9340e07e452fd16c81a79 Mon Sep 17 00:00:00 2001 From: Rian Date: Tue, 3 Nov 2026 03:31:56 -0500 Subject: [PATCH 07/17] Cache frozen [CLS] embeddings keyed on real tokens, not padded rows. A frozen encoder repeats the identical forward every epoch while batch padding width changes each shuffle, so keys hash only the attended tokens. Keys are (hash, real-token length): the length is a cheap guard so a hash collision alone cannot silently return the wrong embedding. cache_frozen_text is the on/off switch; the cache never drops notes, recalculating rows past the cap. Empty note batches return zero-length vectors even for parameter-free encoders (dtype falls back to the default when the encoder has no parameters). Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95 --- pyhealth/models/unified_embedding.py | 117 ++++++++++++++++++++++++++- tests/core/test_unified_cache.py | 116 ++++++++++++++++++++++++++ 2 files changed, 230 insertions(+), 3 deletions(-) create mode 100644 tests/core/test_unified_cache.py diff --git a/pyhealth/models/unified_embedding.py b/pyhealth/models/unified_embedding.py index ca7b492757..dd7983866c 100644 --- a/pyhealth/models/unified_embedding.py +++ b/pyhealth/models/unified_embedding.py @@ -24,6 +24,7 @@ import math import warnings +from contextlib import nullcontext from typing import Any import torch @@ -173,6 +174,11 @@ class UnifiedMultimodalEmbeddingModel(nn.Module): type terms are added. The default is True because raw feature magnitude is an accident of feature scaling, not a modelling decision. + cache_frozen_text: If True, reuse frozen ``[CLS]`` vectors across + forwards instead of re-running the text encoder. Defaults to True. + max_frozen_text_cache: Maximum cached ``[CLS]`` vectors. Rows past the + cap are re-encoded each forward; notes are never dropped. + Defaults to 200000. numeric_standardizers: Optional mapping of NUMERIC/SIGNAL field names to modules called as ``standardizer(value, observed)`` BEFORE the projection, where ``observed`` comes from the sibling @@ -223,6 +229,8 @@ def __init__( field_embeddings: dict[str, Any] | None = None, freeze_text_encoder: bool = False, normalize_content: bool = True, + cache_frozen_text: bool = True, + max_frozen_text_cache: int = 200_000, numeric_standardizers: dict[str, Any] | None = None, ): super().__init__() @@ -233,6 +241,9 @@ def __init__( self._embedding_dim = embedding_dim self._freeze_text_encoder = freeze_text_encoder self._frozen_text_fields: set[str] = set() + self.cache_frozen_text = cache_frozen_text + self.max_frozen_text_cache = max_frozen_text_cache + self._frozen_text_cache: dict[str, dict[tuple[int, int], torch.Tensor]] = {} self.image_pool = image_pool self.normalize_content = normalize_content # Statistics live in buffers, so they travel in state_dict. A checkpoint @@ -447,6 +458,105 @@ def _build_numeric_encoder( def embedding_dim(self) -> int: return self._embedding_dim + def _encode_text_cls( + self, + field_name: str, + encoder: nn.Module, + flat_ids: torch.Tensor, + flat_mask: torch.Tensor | None, + ) -> torch.Tensor: + """Return the ``[CLS]`` vector for each row, from a cache when possible. + + A frozen encoder gives the same output for the same tokens, so a run of + 50 epochs would otherwise repeat the identical 110M-parameter forward + pass 50 times. + + The cache has three conditions. It is used only for a field in + ``_frozen_text_fields``, so a trainable encoder can never read it. The + key is ``(hash, real-token length)`` over the token identifiers under + the attention mask, so a change of tokenizer or truncation budget + gives a different key; the length is a cheap guard so a hash + collision alone cannot silently return the wrong embedding. The cache has a + maximum size, and it recalculates a row when the cache is full. + + Key on the REAL tokens only. The collator pads each row to the widest + note in its batch, and batch composition changes every epoch because + the loader shuffles, so a key over the padded row gives the same note + a different key each epoch and the cache never hits. Measured on the + full-scale notes run: epoch time did not fall after epoch 1 + (3458s, 3936s, 4048s, 3835s) because every lookup missed. + """ + if flat_ids.shape[0] == 0: + hidden = encoder.config.hidden_size + first_param = next(encoder.parameters(), None) + dtype = ( + first_param.dtype if first_param is not None + else torch.get_default_dtype() + ) + return flat_ids.new_zeros((0, hidden), dtype=dtype) + + if not (self.cache_frozen_text and field_name in self._frozen_text_fields): + ctx = torch.no_grad() if field_name in self._frozen_text_fields else nullcontext() + with ctx: + out = encoder(input_ids=flat_ids, attention_mask=flat_mask) + return out.last_hidden_state[:, 0, :] + + cache = self._frozen_text_cache.setdefault(field_name, {}) + ids_cpu = flat_ids.detach().cpu() + mask_cpu = ( + flat_mask.detach().cpu().to(torch.int8) + if flat_mask is not None + else torch.ones_like(ids_cpu, dtype=torch.int8) + ) + # Key on (hash, real-token length): hash() alone could silently + # return a wrong [CLS] on collision. Storing the length is a cheap + # guard — a collision then needs the same hash AND the same length. + keys: list[tuple[int, int]] = [] + for i, m in zip(ids_cpu, mask_cpu): + n_real = int(m.sum()) + if m.any(): + h = hash(tuple(i[m.bool()].tolist())) + else: + h = hash(tuple(i.tolist())) + keys.append((h, n_real)) + + first_row_of_key: dict[tuple[int, int], int] = {} + for k, key in enumerate(keys): + if key not in cache and key not in first_row_of_key: + first_row_of_key[key] = k + missing = list(first_row_of_key.values()) + if missing: + index = torch.tensor(missing, device=flat_ids.device) + with torch.no_grad(): + out = encoder( + input_ids=flat_ids.index_select(0, index), + attention_mask=( + flat_mask.index_select(0, index) + if flat_mask is not None + else None + ), + ) + fresh = out.last_hidden_state[:, 0, :].detach() + for slot, row in zip(missing, fresh): + if len(cache) < self.max_frozen_text_cache: + cache[keys[slot]] = row.cpu() + + rows = [] + for k, key in enumerate(keys): + hit = cache.get(key) + if hit is None: + with torch.no_grad(): + out = encoder( + input_ids=flat_ids[k : k + 1], + attention_mask=( + flat_mask[k : k + 1] if flat_mask is not None else None + ), + ) + rows.append(out.last_hidden_state[0, 0, :].detach()) + else: + rows.append(hit.to(flat_ids.device)) + return torch.stack(rows).to(dtype=self.type_embedding.weight.dtype) + def train(self, mode: bool = True) -> UnifiedMultimodalEmbeddingModel: """Keep a frozen text encoder in eval mode. @@ -565,10 +675,11 @@ def forward( elif modality == ModalityType.TEXT: b, n, l = value.shape - flat_ids = value.view(b * n, l) + flat_ids = value.view(b * n, l) flat_mask = mask.view(b * n, l) if mask is not None else None - out = encoder(input_ids=flat_ids, attention_mask=flat_mask) - cls_emb = out.last_hidden_state[:, 0, :] # (B*N, H) + cls_emb = self._encode_text_cls( + field_name, encoder, flat_ids, flat_mask + ) # (B*N, H) if field_name in self.projections: cls_emb = self.projections[field_name](cls_emb) # cls_emb.shape[-1] instead of -1: when b*n == 0 (no note diff --git a/tests/core/test_unified_cache.py b/tests/core/test_unified_cache.py new file mode 100644 index 0000000000..4b379c9a2c --- /dev/null +++ b/tests/core/test_unified_cache.py @@ -0,0 +1,116 @@ +"""Frozen [CLS] cache keyed on real tokens, with an on/off switch.""" + +from __future__ import annotations + +import builtins +import unittest +from unittest import mock + +import torch +import torch.nn as nn + +from pyhealth.models.unified_embedding import UnifiedMultimodalEmbeddingModel +from pyhealth.processors.stagenet_processor import StageNetTensorProcessor + + +def _numeric_model(**kwargs) -> UnifiedMultimodalEmbeddingModel: + proc = StageNetTensorProcessor() + proc.fit([{"labs": ([0.0], [[1.0] * 10])}], "labs") + kwargs.setdefault("cache_frozen_text", True) + return UnifiedMultimodalEmbeddingModel( + {"labs": proc}, embedding_dim=8, freeze_text_encoder=True, **kwargs + ) + + +class CountingEnc(nn.Module): + def __init__(self): + super().__init__() + self.calls = 0 + self.lin = nn.Linear(1, 8) + self.config = type("C", (), {"hidden_size": 8})() + + def forward(self, input_ids, attention_mask=None): + self.calls += 1 + b, l = input_ids.shape + scale = input_ids[:, :1, None].float() + h = torch.ones(b, l, 8) * scale + return type("O", (), {"last_hidden_state": h})() + + +class TestFrozenTextCache(unittest.TestCase): + def _cached(self, **kwargs): + model = _numeric_model(**kwargs) + enc = CountingEnc() + model.encoders["notes"] = enc + model._frozen_text_fields.add("notes") + return model, enc + + def test_cache_keys_ignore_padding_tokens(self): + model, enc = self._cached() + ids_a = torch.tensor([[1, 2, 3, 0, 0], [1, 2, 3, 9, 9]]) + mask_a = torch.tensor([[1, 1, 1, 0, 0], [1, 1, 1, 0, 0]]) + h1 = model._encode_text_cls("notes", enc, ids_a, mask_a) + self.assertEqual(enc.calls, 1) + h2 = model._encode_text_cls("notes", enc, ids_a, mask_a) + self.assertEqual(enc.calls, 1) + self.assertTrue(torch.equal(h1, h2)) + # Same real tokens under a wider pad width still hits. + ids_b = torch.tensor([[1, 2, 3, 7, 7, 7]]) + mask_b = torch.tensor([[1, 1, 1, 0, 0, 0]]) + h3 = model._encode_text_cls("notes", enc, ids_b, mask_b) + self.assertEqual(enc.calls, 1) + self.assertEqual(h1.shape[0], 2) + self.assertEqual(h3.shape[0], 1) + self.assertTrue(torch.equal(h3[0], h1[0])) + + def test_switch_off_runs_encoder_every_forward(self): + model, enc = self._cached(cache_frozen_text=False) + ids_a = torch.tensor([[1, 2, 3, 0, 0], [1, 2, 3, 9, 9]]) + mask_a = torch.tensor([[1, 1, 1, 0, 0], [1, 1, 1, 0, 0]]) + model._encode_text_cls("notes", enc, ids_a, mask_a) + model._encode_text_cls("notes", enc, ids_a, mask_a) + self.assertEqual(enc.calls, 2) + self.assertEqual(model._frozen_text_cache, {}) + + def test_unfrozen_field_never_caches(self): + model = _numeric_model() + enc = CountingEnc() + model.encoders["notes"] = enc + # Deliberately NOT added to _frozen_text_fields: trainable encoder. + ids_a = torch.tensor([[1, 2, 3]]) + h1 = model._encode_text_cls("notes", enc, ids_a, None) + h2 = model._encode_text_cls("notes", enc, ids_a, None) + self.assertEqual(enc.calls, 2) + self.assertTrue(torch.equal(h1, h2)) + + def test_empty_rows_return_zeros_without_encoding(self): + model, enc = self._cached() + out = model._encode_text_cls( + "notes", enc, torch.zeros(0, 4, dtype=torch.long), None + ) + self.assertEqual(out.shape, (0, 8)) + self.assertEqual(enc.calls, 0) + + def test_hash_collision_does_not_return_wrong_embedding(self): + # Keys use Python hash(); a collision must not silently return the + # wrong [CLS]. The key carries the real-token length as a cheap + # guard, so two sequences with the same hash but different lengths + # still miss. Simulate a total collision by forcing hash() to 42. + model, enc = self._cached() + ids1 = torch.tensor([[1, 2, 3]]) + mask1 = torch.tensor([[1, 1, 1]]) + ids2 = torch.tensor([[9, 8]]) + mask2 = torch.tensor([[1, 1]]) + with mock.patch.object(builtins, "hash", return_value=42): + h1 = model._encode_text_cls("notes", enc, ids1, mask1) + h2 = model._encode_text_cls("notes", enc, ids2, mask2) + # Different first tokens -> different [CLS]; a collision would + # have returned h1 for both rows. + self.assertFalse(torch.equal(h1, h2)) + self.assertEqual( + sum(len(c) for c in model._frozen_text_cache.values()), 2 + ) + + +if __name__ == "__main__": + unittest.main() From f382bd724e0c6c42a8064fa29c88daf9bd3591bb Mon Sep 17 00:00:00 2001 From: Rian Date: Tue, 3 Nov 2026 02:53:07 -0500 Subject: [PATCH 08/17] Encode a frozen-cache miss once per forward, even when the cache is full. Misses share one batched encoder call and assembly serves overflow rows from that result instead of re-encoding them one by one, so a full cache costs one batch per new note per forward. Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95 --- pyhealth/models/unified_embedding.py | 15 ++++++--------- tests/core/test_unified_cache.py | 15 +++++++++++++++ 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/pyhealth/models/unified_embedding.py b/pyhealth/models/unified_embedding.py index dd7983866c..301f59d8ee 100644 --- a/pyhealth/models/unified_embedding.py +++ b/pyhealth/models/unified_embedding.py @@ -525,6 +525,9 @@ def _encode_text_cls( if key not in cache and key not in first_row_of_key: first_row_of_key[key] = k missing = list(first_row_of_key.values()) + # Rows encoded in this forward, kept even when the cache is full so a + # miss is never encoded twice in one call. + fresh_rows: dict[int, torch.Tensor] = {} if missing: index = torch.tensor(missing, device=flat_ids.device) with torch.no_grad(): @@ -538,21 +541,15 @@ def _encode_text_cls( ) fresh = out.last_hidden_state[:, 0, :].detach() for slot, row in zip(missing, fresh): + fresh_rows[keys[slot]] = row if len(cache) < self.max_frozen_text_cache: cache[keys[slot]] = row.cpu() rows = [] - for k, key in enumerate(keys): + for key in keys: hit = cache.get(key) if hit is None: - with torch.no_grad(): - out = encoder( - input_ids=flat_ids[k : k + 1], - attention_mask=( - flat_mask[k : k + 1] if flat_mask is not None else None - ), - ) - rows.append(out.last_hidden_state[0, 0, :].detach()) + rows.append(fresh_rows[key]) else: rows.append(hit.to(flat_ids.device)) return torch.stack(rows).to(dtype=self.type_embedding.weight.dtype) diff --git a/tests/core/test_unified_cache.py b/tests/core/test_unified_cache.py index 4b379c9a2c..051410a2b9 100644 --- a/tests/core/test_unified_cache.py +++ b/tests/core/test_unified_cache.py @@ -83,6 +83,21 @@ def test_unfrozen_field_never_caches(self): self.assertEqual(enc.calls, 2) self.assertTrue(torch.equal(h1, h2)) + def test_full_cache_encodes_each_miss_once(self): + model, enc = self._cached(max_frozen_text_cache=1) + ids = torch.tensor([[1, 2, 3], [4, 5, 6]]) + h1 = model._encode_text_cls("notes", enc, ids, None) + # One batched encoder call serves both misses; only the first fits. + self.assertEqual(enc.calls, 1) + self.assertEqual(h1.shape, (2, 8)) + self.assertEqual( + sum(len(c) for c in model._frozen_text_cache.values()), 1 + ) + h2 = model._encode_text_cls("notes", enc, ids, None) + # The cached row hits; the overflow row re-encodes exactly once. + self.assertEqual(enc.calls, 2) + self.assertTrue(torch.equal(h1, h2)) + def test_empty_rows_return_zeros_without_encoding(self): model, enc = self._cached() out = model._encode_text_cls( From 61a301990929a75de245e9c2de43f3d2a75a0be7 Mon Sep 17 00:00:00 2001 From: Rian Date: Tue, 3 Nov 2026 02:53:58 -0500 Subject: [PATCH 09/17] Cap the frozen text cache and expose hit/miss counters. The cap defaults to 1M entries since 200k is too small for full MIMIC; None or <=0 means uncapped, growth is logged, and frozen_text_cache_size plus frozen_text_cache_stats with a reset method feed the cache on/off A/B. Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95 --- pyhealth/models/unified_embedding.py | 86 ++++++++++++++++++++++++---- tests/core/test_unified_cache.py | 49 +++++++++++++++- 2 files changed, 121 insertions(+), 14 deletions(-) diff --git a/pyhealth/models/unified_embedding.py b/pyhealth/models/unified_embedding.py index 301f59d8ee..379af74592 100644 --- a/pyhealth/models/unified_embedding.py +++ b/pyhealth/models/unified_embedding.py @@ -22,6 +22,7 @@ """ from __future__ import annotations +import logging import math import warnings from contextlib import nullcontext @@ -34,6 +35,13 @@ from pyhealth.processors.base_processor import ModalityType, TemporalFeatureProcessor from pyhealth.models.vision_embedding import PatchEmbedding +logger = logging.getLogger(__name__) + +# Frozen [CLS] is 768-d float32 on CPU. Python tensor objects add overhead; +# treat 8 KB/entry as a conservative host-RAM estimate when logging. +_CLS_BYTES = 768 * 4 +_CACHE_LOG_SIZES = {1, 10_000, 50_000, 100_000, 200_000, 500_000, 1_000_000, 2_000_000} + # ── Helpers ─────────────────────────────────────────────────────────────────── @@ -176,9 +184,11 @@ class UnifiedMultimodalEmbeddingModel(nn.Module): decision. cache_frozen_text: If True, reuse frozen ``[CLS]`` vectors across forwards instead of re-running the text encoder. Defaults to True. - max_frozen_text_cache: Maximum cached ``[CLS]`` vectors. Rows past the - cap are re-encoded each forward; notes are never dropped. - Defaults to 200000. + max_frozen_text_cache: Maximum cached ``[CLS]`` vectors + (``None`` or ``<= 0`` means no cap). Rows past the cap are + re-encoded each forward; notes are never dropped. The cap is a + RAM fuse, not a speedup knob: speedup needs cap >= unique notes. + Defaults to 1000000. numeric_standardizers: Optional mapping of NUMERIC/SIGNAL field names to modules called as ``standardizer(value, observed)`` BEFORE the projection, where ``observed`` comes from the sibling @@ -230,7 +240,7 @@ def __init__( freeze_text_encoder: bool = False, normalize_content: bool = True, cache_frozen_text: bool = True, - max_frozen_text_cache: int = 200_000, + max_frozen_text_cache: int | None = 1_000_000, numeric_standardizers: dict[str, Any] | None = None, ): super().__init__() @@ -244,6 +254,8 @@ def __init__( self.cache_frozen_text = cache_frozen_text self.max_frozen_text_cache = max_frozen_text_cache self._frozen_text_cache: dict[str, dict[tuple[int, int], torch.Tensor]] = {} + self._frozen_text_cache_hits = 0 + self._frozen_text_cache_misses = 0 self.image_pool = image_pool self.normalize_content = normalize_content # Statistics live in buffers, so they travel in state_dict. A checkpoint @@ -458,6 +470,39 @@ def _build_numeric_encoder( def embedding_dim(self) -> int: return self._embedding_dim + @property + def frozen_text_cache_size(self) -> int: + """Number of cached frozen ``[CLS]`` vectors across fields. + + Example: + >>> model.frozen_text_cache_size + 0 + """ + return sum(len(c) for c in self._frozen_text_cache.values()) + + @property + def frozen_text_cache_stats(self) -> dict[str, int]: + """Cache ``hits``, ``misses``, and ``size`` for the A/B timing run. + + Misses count rows not cached before this forward (including + duplicates and overflow rows served from the current forward); + hits count rows served from the cache. + + Example: + >>> sorted(model.frozen_text_cache_stats) + ['hits', 'misses', 'size'] + """ + return { + "hits": self._frozen_text_cache_hits, + "misses": self._frozen_text_cache_misses, + "size": self.frozen_text_cache_size, + } + + def reset_frozen_text_cache_stats(self) -> None: + """Zero the ``hits``/``misses`` counters (cache entries are kept).""" + self._frozen_text_cache_hits = 0 + self._frozen_text_cache_misses = 0 + def _encode_text_cls( self, field_name: str, @@ -476,8 +521,11 @@ def _encode_text_cls( key is ``(hash, real-token length)`` over the token identifiers under the attention mask, so a change of tokenizer or truncation budget gives a different key; the length is a cheap guard so a hash - collision alone cannot silently return the wrong embedding. The cache has a - maximum size, and it recalculates a row when the cache is full. + collision alone cannot silently return the wrong embedding. ``None`` or + ``<= 0`` means no size cap. Default is 1_000_000 (~3 GB of fp32 + ``[CLS]`` vectors): a RAM fuse, not a speedup knob. A smaller cap + than the unique-note count makes overflow notes re-run BERT every + epoch. Notes are never dropped from the sequence. Key on the REAL tokens only. The collator pads each row to the widest note in its batch, and batch composition changes every epoch because @@ -502,6 +550,7 @@ def _encode_text_cls( return out.last_hidden_state[:, 0, :] cache = self._frozen_text_cache.setdefault(field_name, {}) + pre_cached = set(cache) ids_cpu = flat_ids.detach().cpu() mask_cpu = ( flat_mask.detach().cpu().to(torch.int8) @@ -527,7 +576,7 @@ def _encode_text_cls( missing = list(first_row_of_key.values()) # Rows encoded in this forward, kept even when the cache is full so a # miss is never encoded twice in one call. - fresh_rows: dict[int, torch.Tensor] = {} + fresh_rows: dict[tuple[int, int], torch.Tensor] = {} if missing: index = torch.tensor(missing, device=flat_ids.device) with torch.no_grad(): @@ -542,16 +591,31 @@ def _encode_text_cls( fresh = out.last_hidden_state[:, 0, :].detach() for slot, row in zip(missing, fresh): fresh_rows[keys[slot]] = row - if len(cache) < self.max_frozen_text_cache: + cap = self.max_frozen_text_cache + if cap is None or cap <= 0 or len(cache) < cap: cache[keys[slot]] = row.cpu() + n = len(cache) + if n in _CACHE_LOG_SIZES or (n > 0 and n % 250_000 == 0): + logger.info( + "frozen text cache field=%s size=%d " + "(~%.2f GB fp32 [CLS] tensors, ~%.2f GB with " + "Python overhead). Overflow is re-encoded next " + "forward; notes are never dropped.", + field_name, + n, + n * _CLS_BYTES / 1e9, + n * 8e3 / 1e9, + ) rows = [] for key in keys: hit = cache.get(key) - if hit is None: - rows.append(fresh_rows[key]) - else: + if key in pre_cached and hit is not None: + self._frozen_text_cache_hits += 1 rows.append(hit.to(flat_ids.device)) + else: + self._frozen_text_cache_misses += 1 + rows.append(fresh_rows[key]) return torch.stack(rows).to(dtype=self.type_embedding.weight.dtype) def train(self, mode: bool = True) -> UnifiedMultimodalEmbeddingModel: diff --git a/tests/core/test_unified_cache.py b/tests/core/test_unified_cache.py index 051410a2b9..7c03a15b90 100644 --- a/tests/core/test_unified_cache.py +++ b/tests/core/test_unified_cache.py @@ -98,6 +98,51 @@ def test_full_cache_encodes_each_miss_once(self): self.assertEqual(enc.calls, 2) self.assertTrue(torch.equal(h1, h2)) + def test_counters_track_hits_and_misses(self): + model, enc = self._cached() + ids = torch.tensor([[1, 2, 3], [4, 5, 6]]) + model._encode_text_cls("notes", enc, ids, None) + self.assertEqual( + model.frozen_text_cache_stats, + {"hits": 0, "misses": 2, "size": 2}, + ) + model._encode_text_cls("notes", enc, ids, None) + self.assertEqual( + model.frozen_text_cache_stats, + {"hits": 2, "misses": 2, "size": 2}, + ) + model.reset_frozen_text_cache_stats() + self.assertEqual( + model.frozen_text_cache_stats, + {"hits": 0, "misses": 0, "size": 2}, + ) + + def test_shuffled_row_order_still_hits(self): + model, enc = self._cached() + ids = torch.tensor([[1, 2, 3], [4, 5, 6]]) + h1 = model._encode_text_cls("notes", enc, ids, None) + calls_after_first = enc.calls + h2 = model._encode_text_cls("notes", enc, ids.flip(0), None) + self.assertEqual(enc.calls, calls_after_first) + self.assertTrue(torch.equal(h2[0], h1[1])) + self.assertTrue(torch.equal(h2[1], h1[0])) + + def test_none_cap_is_uncapped(self): + model, enc = self._cached(max_frozen_text_cache=None) + ids = torch.tensor([[1], [2], [3]]) + model._encode_text_cls("notes", enc, ids, None) + self.assertEqual(model.frozen_text_cache_size, 3) + + def test_zero_cap_is_uncapped(self): + model, enc = self._cached(max_frozen_text_cache=0) + ids = torch.tensor([[1], [2]]) + model._encode_text_cls("notes", enc, ids, None) + self.assertEqual(model.frozen_text_cache_size, 2) + + def test_default_cap_is_one_million(self): + model, _ = self._cached() + self.assertEqual(model.max_frozen_text_cache, 1_000_000) + def test_empty_rows_return_zeros_without_encoding(self): model, enc = self._cached() out = model._encode_text_cls( @@ -122,9 +167,7 @@ def test_hash_collision_does_not_return_wrong_embedding(self): # Different first tokens -> different [CLS]; a collision would # have returned h1 for both rows. self.assertFalse(torch.equal(h1, h2)) - self.assertEqual( - sum(len(c) for c in model._frozen_text_cache.values()), 2 - ) + self.assertEqual(model.frozen_text_cache_size, 2) if __name__ == "__main__": From e9a3e5f026fbcea5d0f9fb068bfcf518b9d6e769 Mon Sep 17 00:00:00 2001 From: Rian Date: Tue, 3 Nov 2026 02:56:06 -0500 Subject: [PATCH 10/17] Add unified-embedding mode to the Transformer. With unified_embedding given, codes, labs, and notes share one time-sorted sequence through a single TransformerLayer for full cross-modal attention. Per-field mode is unchanged; the padded path runs alongside sequence_v2, which has no text encoders yet. Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95 --- pyhealth/models/transformer.py | 98 +++++++++++++++++++++++--- tests/core/test_transformer_unified.py | 69 ++++++++++++++++++ 2 files changed, 159 insertions(+), 8 deletions(-) create mode 100644 tests/core/test_transformer_unified.py diff --git a/pyhealth/models/transformer.py b/pyhealth/models/transformer.py index 5336061f9f..1c62d295e3 100644 --- a/pyhealth/models/transformer.py +++ b/pyhealth/models/transformer.py @@ -13,6 +13,7 @@ from pyhealth.datasets import SampleDataset from pyhealth.models import BaseModel from pyhealth.models.embedding import EmbeddingModel +from pyhealth.models.unified_embedding import UnifiedMultimodalEmbeddingModel from pyhealth.interpret.api import CheferInterpretable # VALID_OPERATION_LEVEL = ["visit", "event"] @@ -377,12 +378,21 @@ class Transformer(BaseModel, CheferInterpretable): an independent :class:`TransformerLayer`. The resulting [CLS]-style embeddings are concatenated and passed to a classification head. + When ``unified_embedding`` is supplied the model switches to **unified + mode**: all temporal fields are jointly embedded and time-sorted by + :class:`UnifiedMultimodalEmbeddingModel`, then processed by a *single* + :class:`TransformerLayer` rather than one layer per field. This allows + full cross-modal attention over the interleaved event sequence. + Args: dataset (SampleDataset): dataset providing processed inputs. embedding_dim (int): shared embedding dimension. heads (int): number of attention heads per transformer block. dropout (float): dropout rate applied inside transformer blocks. num_layers (int): number of transformer blocks per feature stream. + unified_embedding (UnifiedMultimodalEmbeddingModel, optional): when + provided, the model uses a single backbone over the unified + multi-modal sequence instead of per-field transformers. Examples: >>> from pyhealth.datasets import create_sample_dataset, get_dataloader @@ -426,6 +436,7 @@ def __init__( dropout: float = 0.5, num_layers: int = 1, max_seq_len: int = 1024, + unified_embedding: UnifiedMultimodalEmbeddingModel | None = None, ): super().__init__(dataset=dataset) self.embedding_dim = embedding_dim @@ -434,25 +445,35 @@ def __init__( self.num_layers = num_layers self.max_seq_len = max_seq_len self._attention_hooks_enabled = False + self._use_unified = unified_embedding is not None assert ( len(self.label_keys) == 1 ), "Only one label key is supported if Transformer is initialized" self.label_key = self.label_keys[0] - self.embedding_model = EmbeddingModel(dataset, embedding_dim) + output_size = self.label_processor.output_size() - self.transformer: nn.ModuleDict = nn.ModuleDict() - for feature_key in self.feature_keys: - self.transformer[feature_key] = TransformerLayer( + if self._use_unified: + self.embedding_model = unified_embedding + self._unified_backbone = TransformerLayer( feature_size=embedding_dim, heads=heads, dropout=dropout, num_layers=num_layers, ) - - output_size = self.label_processor.output_size() - self.fc = nn.Linear(len(self.feature_keys) * embedding_dim, output_size) + self.fc = nn.Linear(embedding_dim, output_size) + else: + self.embedding_model = EmbeddingModel(dataset, embedding_dim) + self.transformer: nn.ModuleDict = nn.ModuleDict() + for feature_key in self.feature_keys: + self.transformer[feature_key] = TransformerLayer( + feature_size=embedding_dim, + heads=heads, + dropout=dropout, + num_layers=num_layers, + ) + self.fc = nn.Linear(len(self.feature_keys) * embedding_dim, output_size) def _pool_embedding(self, x: torch.Tensor) -> torch.Tensor: """Pool nested embeddings to ``[batch, seq_len, hidden]`` format. @@ -491,6 +512,59 @@ def _mask_from_embeddings(x: torch.Tensor) -> torch.Tensor: mask[invalid_rows, 0] = True return mask.bool() + def _build_unified_inputs( + self, kwargs: dict[str, Any] + ) -> dict[str, dict[str, torch.Tensor]]: + """Build inputs expected by UnifiedMultimodalEmbeddingModel.""" + inputs: dict[str, dict[str, torch.Tensor]] = {} + for field_name in self.feature_keys: + feature = kwargs[field_name] + if isinstance(feature, torch.Tensor): + feature = (feature,) + + schema = self.dataset.input_processors[field_name].schema() + field_dict: dict[str, torch.Tensor] = {} + if "value" in schema: + field_dict["value"] = feature[schema.index("value")].to(self.device) + if "time" in schema: + field_dict["time"] = feature[schema.index("time")].to(self.device) + if "mask" in schema: + field_dict["mask"] = feature[schema.index("mask")].to(self.device) + inputs[field_name] = field_dict + + return inputs + + def _forward_unified( + self, + **kwargs: torch.Tensor | tuple[torch.Tensor, ...], + ) -> dict[str, torch.Tensor]: + """Forward pass in unified-embedding mode.""" + register_hook = self._attention_hooks_enabled + inputs = self._build_unified_inputs(cast(dict[str, Any], kwargs)) + out = self.embedding_model(inputs) + sequence = cast(torch.Tensor, out["sequence"]) + event_mask = cast(torch.Tensor, out["mask"]).bool() + + _, patient_emb = self._unified_backbone(sequence, event_mask, register_hook) + + logits = self.fc(patient_emb) + y_prob = self.label_processor.activation(logits) + + results: dict[str, torch.Tensor] = { + "logit": logits, + "y_prob": y_prob, + } + + if self.label_key in kwargs: + y_true = cast(torch.Tensor, kwargs[self.label_key]).to(self.device) + loss = self.label_processor.loss(logits, y_true) + results["loss"] = loss + results["y_true"] = y_true + + if kwargs.get("embed", False): + results["embed"] = patient_emb + return results + def forward_from_embedding( self, **kwargs: torch.Tensor | tuple[torch.Tensor, ...], @@ -590,9 +664,14 @@ def forward_from_embedding( def forward( self, **kwargs: torch.Tensor | tuple[torch.Tensor, ...], - ) -> Dict[str, torch.Tensor]: + ) -> dict[str, torch.Tensor]: """Forward propagation. + In **unified mode** (when ``unified_embedding`` was supplied at init) + the model jointly embeds all temporal fields and processes them with a + single transformer backbone. Otherwise each field is embedded and + encoded independently. + Args: **kwargs: keyword arguments for the model. @@ -610,6 +689,9 @@ def forward( logit: the raw logits before activation. embed: (if embed=True in kwargs) the patient embedding. """ + if self._use_unified: + return self._forward_unified(**kwargs) + for feature_key in self.feature_keys: feature = kwargs[feature_key] diff --git a/tests/core/test_transformer_unified.py b/tests/core/test_transformer_unified.py new file mode 100644 index 0000000000..be4ef3a210 --- /dev/null +++ b/tests/core/test_transformer_unified.py @@ -0,0 +1,69 @@ +"""Transformer unified mode over a tiny two-field temporal dataset.""" + +import unittest + +import torch + +from pyhealth.datasets import create_sample_dataset, get_dataloader +from pyhealth.models import Transformer +from pyhealth.models.unified_embedding import UnifiedMultimodalEmbeddingModel + + +def _dataset(): + samples = [ + { + "patient_id": "patient-0", + "visit_id": "visit-0", + "codes": ([0.0, 2.0], ["A", "B"]), + "labs": ([0.0, 2.0], [[1.0, 2.0], [3.0, 4.0]]), + "label": 1, + }, + { + "patient_id": "patient-1", + "visit_id": "visit-0", + "codes": ([0.0], ["C"]), + "labs": ([0.0], [[5.0, 6.0]]), + "label": 0, + }, + ] + return create_sample_dataset( + samples=samples, + input_schema={"codes": "stagenet", "labs": "stagenet_tensor"}, + output_schema={"label": "binary"}, + dataset_name="test_transformer_unified", + ) + + +class TestTransformerUnified(unittest.TestCase): + def test_unified_forward_backward_loss_finite(self): + dataset = _dataset() + unified = UnifiedMultimodalEmbeddingModel( + dataset.input_processors, embedding_dim=8 + ) + model = Transformer( + dataset=dataset, embedding_dim=8, heads=1, num_layers=1, + unified_embedding=unified, + ) + batch = next(iter(get_dataloader(dataset, batch_size=2, shuffle=False))) + out = model(**batch) + self.assertTrue(torch.isfinite(out["loss"])) + out["loss"].backward() + self.assertTrue( + any( + p.grad is not None + for p in model.parameters() + if p.requires_grad + ) + ) + + def test_per_field_mode_unchanged(self): + dataset = _dataset() + model = Transformer(dataset=dataset, embedding_dim=8, heads=1, num_layers=1) + self.assertFalse(model._use_unified) + batch = next(iter(get_dataloader(dataset, batch_size=2, shuffle=False))) + out = model(**batch) + self.assertTrue(torch.isfinite(out["loss"])) + + +if __name__ == "__main__": + unittest.main() From 88e5c4ca9047dc00b24b6591cf71910a5a8dc463 Mon Sep 17 00:00:00 2001 From: Rian Date: Tue, 3 Nov 2026 02:56:29 -0500 Subject: [PATCH 11/17] Add unified-embedding mode to EHRMamba. With unified_embedding given, all temporal fields share one time-sorted sequence through a single MambaBlock stack pooled to the last valid event. Per-field mode is unchanged; the padded path runs alongside sequence_v2, which has no text encoders yet. Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95 --- pyhealth/models/ehrmamba.py | 96 +++++++++++++++++++++++++---- tests/core/test_ehrmamba_unified.py | 69 +++++++++++++++++++++ 2 files changed, 154 insertions(+), 11 deletions(-) create mode 100644 tests/core/test_ehrmamba_unified.py diff --git a/pyhealth/models/ehrmamba.py b/pyhealth/models/ehrmamba.py index a81a4b81e6..30d22782a4 100644 --- a/pyhealth/models/ehrmamba.py +++ b/pyhealth/models/ehrmamba.py @@ -6,6 +6,7 @@ from pyhealth.datasets import SampleDataset from pyhealth.models import BaseModel from pyhealth.models.embedding import EmbeddingModel +from pyhealth.models.unified_embedding import UnifiedMultimodalEmbeddingModel from pyhealth.models.utils import get_last_visit from pyhealth.processors import ( MultiHotProcessor, @@ -111,6 +112,11 @@ class EHRMamba(BaseModel): Electronic Health Records (arxiv 2405.14567). Uses Mamba (SSM) for linear complexity in sequence length; supports long EHR sequences. + When ``unified_embedding`` is supplied the model switches to **unified + mode**: all temporal fields are jointly embedded and time-sorted by + :class:`UnifiedMultimodalEmbeddingModel`, then processed by a *single* + stack of :class:`MambaBlock` layers rather than one stack per field. + Args: dataset: SampleDataset for token/embedding setup. embedding_dim: Embedding and hidden dimension. Default 128. @@ -118,6 +124,8 @@ class EHRMamba(BaseModel): state_size: SSM state size per channel. Default 16. conv_kernel: Causal conv kernel size in block. Default 4. dropout: Dropout before classification head. Default 0.1. + unified_embedding: Optional pre-built UnifiedMultimodalEmbeddingModel. + When provided, enables unified multi-modal mode. Examples: >>> from pyhealth.datasets import create_sample_dataset, get_dataloader @@ -140,6 +148,7 @@ def __init__( state_size: int = 16, conv_kernel: int = 4, dropout: float = 0.1, + unified_embedding: UnifiedMultimodalEmbeddingModel | None = None, ): super().__init__(dataset=dataset) self.embedding_dim = embedding_dim @@ -147,18 +156,17 @@ def __init__( self.state_size = state_size self.conv_kernel = conv_kernel self.dropout_rate = dropout + self._use_unified = unified_embedding is not None assert len(self.label_keys) == 1, "EHRMamba supports single label key only" self.label_key = self.label_keys[0] - self.embedding_model = EmbeddingModel(dataset, embedding_dim) - self.feature_processors = { - k: self.dataset.input_processors[k] for k in self.feature_keys - } + output_size = self.label_processor.output_size() + self.dropout = nn.Dropout(dropout) - self.blocks = nn.ModuleDict() - for feature_key in self.feature_keys: - self.blocks[feature_key] = nn.ModuleList( + if self._use_unified: + self.embedding_model = unified_embedding + self._unified_blocks = nn.ModuleList( [ MambaBlock( d_model=embedding_dim, @@ -168,10 +176,73 @@ def __init__( for _ in range(num_layers) ] ) - - output_size = self.label_processor.output_size() - self.dropout = nn.Dropout(dropout) - self.fc = nn.Linear(len(self.feature_keys) * embedding_dim, output_size) + self.fc = nn.Linear(embedding_dim, output_size) + else: + self.embedding_model = EmbeddingModel(dataset, embedding_dim) + self.feature_processors = { + k: self.dataset.input_processors[k] for k in self.feature_keys + } + self.blocks = nn.ModuleDict() + for feature_key in self.feature_keys: + self.blocks[feature_key] = nn.ModuleList( + [ + MambaBlock( + d_model=embedding_dim, + state_size=state_size, + conv_kernel=conv_kernel, + ) + for _ in range(num_layers) + ] + ) + self.fc = nn.Linear(len(self.feature_keys) * embedding_dim, output_size) + + def _build_unified_inputs( + self, kwargs: dict[str, Any] + ) -> dict[str, dict[str, torch.Tensor]]: + """Build the inputs dict required by UnifiedMultimodalEmbeddingModel.""" + inputs: dict[str, dict[str, torch.Tensor]] = {} + for field_name in self.feature_keys: + feature = kwargs[field_name] + if isinstance(feature, torch.Tensor): + feature = (feature,) + schema = self.dataset.input_processors[field_name].schema() + field_dict: dict[str, torch.Tensor] = {} + if "value" in schema: + field_dict["value"] = feature[schema.index("value")].to(self.device) + if "time" in schema: + field_dict["time"] = feature[schema.index("time")].to(self.device) + if "mask" in schema: + field_dict["mask"] = feature[schema.index("mask")].to(self.device) + inputs[field_name] = field_dict + return inputs + + def _forward_unified(self, **kwargs) -> dict[str, torch.Tensor]: + """Forward pass in unified-embedding mode. + + Calls UnifiedMultimodalEmbeddingModel to produce a single + temporally-sorted event sequence, then encodes it with one shared + MambaBlock stack and pools to the last valid event. + """ + inputs = self._build_unified_inputs(kwargs) + out = self.embedding_model(inputs) + x = out["sequence"] # (B, S_total, E) + mask = out["mask"].bool() # (B, S_total) + + for blk in self._unified_blocks: + x = blk(x) + + last_h = get_last_visit(x, mask) + logits = self.fc(self.dropout(last_h)) + y_prob = self.label_processor.activation(logits) + results: dict[str, torch.Tensor] = {"y_prob": y_prob, "logit": logits} + # The label is optional, so the model can predict without it. + if self.label_key in kwargs: + y_true = kwargs[self.label_key].to(self.device) + results["loss"] = self.label_processor.loss(logits, y_true) + results["y_true"] = y_true + if kwargs.get("embed", False): + results["embed"] = last_h + return results @staticmethod def _split_temporal(feature: Any) -> Tuple[Optional[torch.Tensor], Any]: @@ -222,6 +293,9 @@ def _pool_embedding(x: torch.Tensor) -> torch.Tensor: return x def forward(self, **kwargs) -> Dict[str, torch.Tensor]: + if self._use_unified: + return self._forward_unified(**kwargs) + patient_emb = [] embedding_inputs: Dict[str, torch.Tensor] = {} masks: Dict[str, torch.Tensor] = {} diff --git a/tests/core/test_ehrmamba_unified.py b/tests/core/test_ehrmamba_unified.py new file mode 100644 index 0000000000..78152b4670 --- /dev/null +++ b/tests/core/test_ehrmamba_unified.py @@ -0,0 +1,69 @@ +"""EHRMamba unified mode over a tiny two-field temporal dataset.""" + +import unittest + +import torch + +from pyhealth.datasets import create_sample_dataset, get_dataloader +from pyhealth.models import EHRMamba +from pyhealth.models.unified_embedding import UnifiedMultimodalEmbeddingModel + + +def _dataset(): + samples = [ + { + "patient_id": "patient-0", + "visit_id": "visit-0", + "codes": ([0.0, 2.0], ["A", "B"]), + "labs": ([0.0, 2.0], [[1.0, 2.0], [3.0, 4.0]]), + "label": 1, + }, + { + "patient_id": "patient-1", + "visit_id": "visit-0", + "codes": ([0.0], ["C"]), + "labs": ([0.0], [[5.0, 6.0]]), + "label": 0, + }, + ] + return create_sample_dataset( + samples=samples, + input_schema={"codes": "stagenet", "labs": "stagenet_tensor"}, + output_schema={"label": "binary"}, + dataset_name="test_ehrmamba_unified", + ) + + +class TestEHRMambaUnified(unittest.TestCase): + def test_unified_forward_backward_loss_finite(self): + dataset = _dataset() + unified = UnifiedMultimodalEmbeddingModel( + dataset.input_processors, embedding_dim=8 + ) + model = EHRMamba( + dataset=dataset, embedding_dim=8, num_layers=1, + unified_embedding=unified, + ) + batch = next(iter(get_dataloader(dataset, batch_size=2, shuffle=False))) + out = model(**batch) + self.assertTrue(torch.isfinite(out["loss"])) + out["loss"].backward() + self.assertTrue( + any( + p.grad is not None + for p in model.parameters() + if p.requires_grad + ) + ) + + def test_per_field_mode_unchanged(self): + dataset = _dataset() + model = EHRMamba(dataset=dataset, embedding_dim=8, num_layers=1) + self.assertFalse(model._use_unified) + batch = next(iter(get_dataloader(dataset, batch_size=2, shuffle=False))) + out = model(**batch) + self.assertTrue(torch.isfinite(out["loss"])) + + +if __name__ == "__main__": + unittest.main() From 3f1703db8d693581581112af0e99029a0d7c6a01 Mon Sep 17 00:00:00 2001 From: Rian Date: Tue, 3 Nov 2026 02:57:31 -0500 Subject: [PATCH 12/17] Add unified-embedding mode to JambaEHR. With unified_embedding given, all temporal fields share one time-sorted sequence through a single JambaLayer pooled to the last valid event. Per-field mode is unchanged; the padded path runs alongside sequence_v2, which has no text encoders yet. Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95 --- pyhealth/models/jamba_ehr.py | 85 +++++++++++++++++++++++++++----- tests/core/test_jamba_unified.py | 73 +++++++++++++++++++++++++++ 2 files changed, 147 insertions(+), 11 deletions(-) create mode 100644 tests/core/test_jamba_unified.py diff --git a/pyhealth/models/jamba_ehr.py b/pyhealth/models/jamba_ehr.py index c392dd0ed6..0d76038de2 100644 --- a/pyhealth/models/jamba_ehr.py +++ b/pyhealth/models/jamba_ehr.py @@ -15,6 +15,7 @@ from pyhealth.datasets import SampleDataset from pyhealth.models import BaseModel from pyhealth.models.embedding import EmbeddingModel +from pyhealth.models.unified_embedding import UnifiedMultimodalEmbeddingModel from pyhealth.models.transformer import TransformerBlock from pyhealth.models.ehrmamba import MambaBlock from pyhealth.models.utils import get_last_visit @@ -177,6 +178,11 @@ class JambaEHR(BaseModel): by an independent :class:`JambaLayer`. The resulting patient embeddings are concatenated and projected through a classification head. + When ``unified_embedding`` is supplied the model switches to **unified + mode**: all temporal fields are jointly embedded and time-sorted by + :class:`UnifiedMultimodalEmbeddingModel`, then processed by a *single* + :class:`JambaLayer` rather than one layer per field. + Args: dataset (SampleDataset): Dataset providing processed inputs. embedding_dim (int): Embedding and hidden dimension. Default 128. @@ -186,6 +192,8 @@ class JambaEHR(BaseModel): dropout (float): Dropout rate. Default 0.3. state_size (int): SSM state size in Mamba blocks. Default 16. conv_kernel (int): Causal conv kernel in Mamba blocks. Default 4. + unified_embedding (UnifiedMultimodalEmbeddingModel, optional): when + provided, enables unified multi-modal mode with a single JambaLayer. Examples: >>> from pyhealth.datasets import create_sample_dataset, get_dataloader @@ -234,6 +242,7 @@ def __init__( dropout: float = 0.3, state_size: int = 16, conv_kernel: int = 4, + unified_embedding: UnifiedMultimodalEmbeddingModel | None = None, ): super(JambaEHR, self).__init__(dataset=dataset) self.embedding_dim = embedding_dim @@ -243,17 +252,19 @@ def __init__( self.dropout_rate = dropout self.state_size = state_size self.conv_kernel = conv_kernel + self._use_unified = unified_embedding is not None assert ( len(self.label_keys) == 1 ), "Only one label key is supported if JambaEHR is initialized" self.label_key = self.label_keys[0] - self.embedding_model = EmbeddingModel(dataset, embedding_dim) + output_size = self.label_processor.output_size() + self.dropout = nn.Dropout(dropout) - self.jamba: nn.ModuleDict = nn.ModuleDict() - for feature_key in self.feature_keys: - self.jamba[feature_key] = JambaLayer( + if self._use_unified: + self.embedding_model = unified_embedding + self._unified_jamba = JambaLayer( feature_size=embedding_dim, num_transformer_layers=num_transformer_layers, num_mamba_layers=num_mamba_layers, @@ -262,12 +273,59 @@ def __init__( state_size=state_size, conv_kernel=conv_kernel, ) + self.fc = nn.Linear(embedding_dim, output_size) + else: + self.embedding_model = EmbeddingModel(dataset, embedding_dim) + self.jamba: nn.ModuleDict = nn.ModuleDict() + for feature_key in self.feature_keys: + self.jamba[feature_key] = JambaLayer( + feature_size=embedding_dim, + num_transformer_layers=num_transformer_layers, + num_mamba_layers=num_mamba_layers, + heads=heads, + dropout=dropout, + state_size=state_size, + conv_kernel=conv_kernel, + ) + self.fc = nn.Linear(len(self.feature_keys) * embedding_dim, output_size) + + def _build_unified_inputs( + self, kwargs: dict[str, Any] + ) -> dict[str, dict[str, torch.Tensor]]: + inputs: dict[str, dict[str, torch.Tensor]] = {} + for field_name in self.feature_keys: + feature = kwargs[field_name] + if isinstance(feature, torch.Tensor): + feature = (feature,) + schema = self.dataset.input_processors[field_name].schema() + field_dict: dict[str, torch.Tensor] = {} + if "value" in schema: + field_dict["value"] = feature[schema.index("value")].to(self.device) + if "time" in schema: + field_dict["time"] = feature[schema.index("time")].to(self.device) + if "mask" in schema: + field_dict["mask"] = feature[schema.index("mask")].to(self.device) + inputs[field_name] = field_dict + return inputs + + def _forward_unified(self, **kwargs: Any) -> dict[str, torch.Tensor]: + inputs = self._build_unified_inputs(kwargs) + out = self.embedding_model(inputs) + sequence = out["sequence"] + mask = out["mask"] + + _, cls_emb = self._unified_jamba(sequence, mask) + logits = self.fc(self.dropout(cls_emb)) + y_prob = self.label_processor.activation(logits) - output_size = self.label_processor.output_size() - self.dropout = nn.Dropout(dropout) - self.fc = nn.Linear( - len(self.feature_keys) * embedding_dim, output_size - ) + results: dict[str, torch.Tensor] = {"logit": logits, "y_prob": y_prob} + if self.label_key in kwargs: + y_true = cast(torch.Tensor, kwargs[self.label_key]).to(self.device) + results["loss"] = self.label_processor.loss(logits, y_true) + results["y_true"] = y_true + if kwargs.get("embed", False): + results["embed"] = cls_emb + return results @staticmethod def _pool_embedding(x: torch.Tensor) -> torch.Tensor: @@ -318,7 +376,9 @@ def forward( Embeds each feature stream, encodes through the hybrid Transformer-Mamba stack, concatenates per-stream patient - representations, and projects to label space. + representations, and projects to label space. In **unified mode** + (when ``unified_embedding`` was supplied at init) all temporal + fields share one time-sorted sequence through a single backbone. Args: **kwargs: Must include all feature keys (tensors or tuples @@ -329,6 +389,9 @@ def forward( ``y_prob``, ``y_true``, ``logit``, and optionally ``embed`` if ``kwargs["embed"] is True``. """ + if self._use_unified: + return self._forward_unified(**kwargs) + patient_emb = [] for feature_key in self.feature_keys: @@ -477,4 +540,4 @@ def forward( out = model_m(**batch) print("keys:", sorted(out.keys())) out["loss"].backward() - print("backward OK") \ No newline at end of file + print("backward OK") diff --git a/tests/core/test_jamba_unified.py b/tests/core/test_jamba_unified.py new file mode 100644 index 0000000000..5e1fc09754 --- /dev/null +++ b/tests/core/test_jamba_unified.py @@ -0,0 +1,73 @@ +"""JambaEHR unified mode over a tiny two-field temporal dataset.""" + +import unittest + +import torch + +from pyhealth.datasets import create_sample_dataset, get_dataloader +from pyhealth.models import JambaEHR +from pyhealth.models.unified_embedding import UnifiedMultimodalEmbeddingModel + + +def _dataset(): + samples = [ + { + "patient_id": "patient-0", + "visit_id": "visit-0", + "codes": ([0.0, 2.0], ["A", "B"]), + "labs": ([0.0, 2.0], [[1.0, 2.0], [3.0, 4.0]]), + "label": 1, + }, + { + "patient_id": "patient-1", + "visit_id": "visit-0", + "codes": ([0.0], ["C"]), + "labs": ([0.0], [[5.0, 6.0]]), + "label": 0, + }, + ] + return create_sample_dataset( + samples=samples, + input_schema={"codes": "stagenet", "labs": "stagenet_tensor"}, + output_schema={"label": "binary"}, + dataset_name="test_jamba_unified", + ) + + +class TestJambaUnified(unittest.TestCase): + def test_unified_forward_backward_loss_finite(self): + dataset = _dataset() + unified = UnifiedMultimodalEmbeddingModel( + dataset.input_processors, embedding_dim=8 + ) + model = JambaEHR( + dataset=dataset, embedding_dim=8, + num_transformer_layers=1, num_mamba_layers=1, heads=1, + unified_embedding=unified, + ) + batch = next(iter(get_dataloader(dataset, batch_size=2, shuffle=False))) + out = model(**batch) + self.assertTrue(torch.isfinite(out["loss"])) + out["loss"].backward() + self.assertTrue( + any( + p.grad is not None + for p in model.parameters() + if p.requires_grad + ) + ) + + def test_per_field_mode_unchanged(self): + dataset = _dataset() + model = JambaEHR( + dataset=dataset, embedding_dim=8, + num_transformer_layers=1, num_mamba_layers=1, heads=1, + ) + self.assertFalse(model._use_unified) + batch = next(iter(get_dataloader(dataset, batch_size=2, shuffle=False))) + out = model(**batch) + self.assertTrue(torch.isfinite(out["loss"])) + + +if __name__ == "__main__": + unittest.main() From 774833620f684950eed2aab2473fa63c6f99e611 Mon Sep 17 00:00:00 2001 From: Rian Date: Tue, 3 Nov 2026 02:57:59 -0500 Subject: [PATCH 13/17] Add unified-embedding mode to the RNN. With unified_embedding given, the existing RNN class jointly embeds all temporal fields as one time-sorted sequence through a single RNNLayer. RNN_V2 is untouched and the packed-lengths clamp stays as upstream has it. The padded path runs alongside sequence_v2, which owns per-step labels. Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95 --- pyhealth/models/rnn.py | 76 ++++++++++++++++++++++++++++++---- tests/core/test_rnn_unified.py | 75 +++++++++++++++++++++++++++++++++ 2 files changed, 143 insertions(+), 8 deletions(-) create mode 100644 tests/core/test_rnn_unified.py diff --git a/pyhealth/models/rnn.py b/pyhealth/models/rnn.py index 7c29708697..251f1d7ff2 100644 --- a/pyhealth/models/rnn.py +++ b/pyhealth/models/rnn.py @@ -24,6 +24,7 @@ ) from .embedding import EmbeddingModel +from .unified_embedding import UnifiedMultimodalEmbeddingModel from .utils import mask_lengths from .sequence_embedding import ( LevelEmbedding, @@ -174,6 +175,10 @@ class RNN(BaseModel): embedding_dim (int): the embedding dimension. Default is 128. hidden_dim (int): the hidden dimension. Default is 128. **kwargs: other parameters for the RNN layer (e.g., rnn_type, num_layers, dropout, bidirectional). + unified_embedding (UnifiedMultimodalEmbeddingModel, optional): when + provided, the model jointly embeds all temporal fields as a single + time-sorted sequence through one RNN. Defaults to None + (per-field mode). Examples: >>> from pyhealth.datasets import create_sample_dataset @@ -222,6 +227,7 @@ def __init__( dataset: SampleDataset, embedding_dim: int = 128, hidden_dim: int = 128, + unified_embedding: UnifiedMultimodalEmbeddingModel | None = None, **kwargs ): super(RNN, self).__init__( @@ -229,6 +235,7 @@ def __init__( ) self.embedding_dim = embedding_dim self.hidden_dim = hidden_dim + self._use_unified = unified_embedding is not None # validate kwargs for RNN layer if "input_size" in kwargs: raise ValueError("input_size is determined by embedding_dim") @@ -243,21 +250,71 @@ def __init__( "RNN_V2 with jagged inputs." ) - self.embedding_model = EmbeddingModel(dataset, embedding_dim) - - self.rnn = nn.ModuleDict() - for feature_key in self.dataset.input_processors.keys(): - self.rnn[feature_key] = RNNLayer( - input_size=embedding_dim, hidden_size=hidden_dim, **kwargs - ) output_size = self.label_processor.output_size() - self.fc = nn.Linear(len(self.feature_keys) * self.hidden_dim, output_size) + + if self._use_unified: + self.embedding_model = unified_embedding + self.rnn = nn.ModuleDict({ + "unified": RNNLayer(input_size=embedding_dim, hidden_size=hidden_dim, **kwargs) + }) + self.fc = nn.Linear(hidden_dim, output_size) + else: + self.embedding_model = EmbeddingModel(dataset, embedding_dim) + self.rnn = nn.ModuleDict() + for feature_key in self.dataset.input_processors: + self.rnn[feature_key] = RNNLayer( + input_size=embedding_dim, hidden_size=hidden_dim, **kwargs + ) + self.fc = nn.Linear(len(self.feature_keys) * self.hidden_dim, output_size) + + def _build_unified_inputs( + self, kwargs: dict[str, Any] + ) -> dict[str, dict[str, torch.Tensor]]: + inputs: dict[str, dict[str, torch.Tensor]] = {} + for field_name in self.feature_keys: + feature = kwargs[field_name] + if isinstance(feature, torch.Tensor): + feature = (feature,) + schema = self.dataset.input_processors[field_name].schema() + field_dict: dict[str, torch.Tensor] = {} + if "value" in schema: + field_dict["value"] = feature[schema.index("value")].to(self.device) + if "time" in schema: + field_dict["time"] = feature[schema.index("time")].to(self.device) + if "mask" in schema: + field_dict["mask"] = feature[schema.index("mask")].to(self.device) + inputs[field_name] = field_dict + return inputs + + def _forward_unified(self, **kwargs: Any) -> dict[str, torch.Tensor]: + inputs = self._build_unified_inputs(kwargs) + out = self.embedding_model(inputs) + sequence = out["sequence"] + mask = out["mask"].int() + + _, last_hidden = self.rnn["unified"](sequence, mask) + logits = self.fc(last_hidden) + y_prob = self.label_processor.activation(logits) + results = {"y_prob": y_prob, "logit": logits} + # The label is optional, so the model can predict without it. + if self.label_key in kwargs: + y_true = kwargs[self.label_key].to(self.device) + results["loss"] = self.label_processor.loss(logits, y_true) + results["y_true"] = y_true + if kwargs.get("embed", False): + results["embed"] = last_hidden + return results def forward(self, **kwargs) -> dict[str, torch.Tensor]: """Forward propagation. The label `kwargs[self.label_key]` is a list of labels for each patient. + In **unified mode** (when ``unified_embedding`` was supplied at init) + the model jointly embeds all temporal fields as a single time-sorted + sequence and processes it with one RNN. Otherwise each field is + embedded and encoded independently. + Args: **kwargs: keyword arguments for the model. The keys must contain all the feature keys and the label key. @@ -270,6 +327,9 @@ def forward(self, **kwargs) -> dict[str, torch.Tensor]: - logit: a tensor representing the logits. - embed (optional): a tensor representing the patient embeddings if requested. """ + if self._use_unified: + return self._forward_unified(**kwargs) + patient_emb = [] # We need to preprocess kwargs to extract values and masks for EmbeddingModel diff --git a/tests/core/test_rnn_unified.py b/tests/core/test_rnn_unified.py new file mode 100644 index 0000000000..5a7ce25d5e --- /dev/null +++ b/tests/core/test_rnn_unified.py @@ -0,0 +1,75 @@ +"""RNN unified mode over a tiny two-field temporal dataset.""" + +import unittest + +import torch + +from pyhealth.datasets import create_sample_dataset, get_dataloader +from pyhealth.models import RNN +from pyhealth.models.unified_embedding import UnifiedMultimodalEmbeddingModel + + +def _dataset(): + samples = [ + { + "patient_id": "patient-0", + "visit_id": "visit-0", + "codes": ([0.0, 2.0], ["A", "B"]), + "labs": ([0.0, 2.0], [[1.0, 2.0], [3.0, 4.0]]), + "label": 1, + }, + { + "patient_id": "patient-1", + "visit_id": "visit-0", + "codes": ([0.0], ["C"]), + "labs": ([0.0], [[5.0, 6.0]]), + "label": 0, + }, + ] + return create_sample_dataset( + samples=samples, + input_schema={"codes": "stagenet", "labs": "stagenet_tensor"}, + output_schema={"label": "binary"}, + dataset_name="test_rnn_unified", + ) + + +class TestRNNUnified(unittest.TestCase): + def test_unified_forward_backward_loss_finite(self): + dataset = _dataset() + unified = UnifiedMultimodalEmbeddingModel( + dataset.input_processors, embedding_dim=8 + ) + model = RNN( + dataset=dataset, embedding_dim=8, hidden_dim=8, + unified_embedding=unified, + ) + batch = next(iter(get_dataloader(dataset, batch_size=2, shuffle=False))) + out = model(**batch) + self.assertTrue(torch.isfinite(out["loss"])) + out["loss"].backward() + self.assertTrue( + any( + p.grad is not None + for p in model.parameters() + if p.requires_grad + ) + ) + + def test_per_field_mode_unchanged(self): + dataset = _dataset() + model = RNN(dataset=dataset, embedding_dim=8, hidden_dim=8) + self.assertFalse(model._use_unified) + batch = next(iter(get_dataloader(dataset, batch_size=2, shuffle=False))) + out = model(**batch) + self.assertTrue(torch.isfinite(out["loss"])) + + def test_rnn_v2_untouched(self): + from pyhealth.models.rnn import RNN_V2 + import inspect + + self.assertNotIn("unified_embedding", inspect.signature(RNN_V2.__init__).parameters) + + +if __name__ == "__main__": + unittest.main() From 441306ce6ce4846dbe94f75c986b00c76a2b34c9 Mon Sep 17 00:00:00 2001 From: Rian Date: Tue, 3 Nov 2026 12:35:14 -0500 Subject: [PATCH 14/17] Skip collate padding in the unified sequence. The collator mask is authoritative for event validity: text/image encoders run only on valid slots, padded slots sort past every real event with a stable order, and the four unified heads thread pad_mask through. Padding no longer looks like admission-time data. Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95 --- pyhealth/models/ehrmamba.py | 4 + pyhealth/models/jamba_ehr.py | 4 + pyhealth/models/rnn.py | 4 + pyhealth/models/transformer.py | 4 + pyhealth/models/unified_embedding.py | 89 ++++++++++++--- tests/core/test_p1_pad_masks.py | 160 ++++++++++++++++++++++++++- 6 files changed, 247 insertions(+), 18 deletions(-) diff --git a/pyhealth/models/ehrmamba.py b/pyhealth/models/ehrmamba.py index 30d22782a4..67fa4ba52c 100644 --- a/pyhealth/models/ehrmamba.py +++ b/pyhealth/models/ehrmamba.py @@ -6,6 +6,7 @@ from pyhealth.datasets import SampleDataset from pyhealth.models import BaseModel from pyhealth.models.embedding import EmbeddingModel +from pyhealth.datasets.utils import PAD_MASK_SUFFIX from pyhealth.models.unified_embedding import UnifiedMultimodalEmbeddingModel from pyhealth.models.utils import get_last_visit from pyhealth.processors import ( @@ -213,6 +214,9 @@ def _build_unified_inputs( field_dict["time"] = feature[schema.index("time")].to(self.device) if "mask" in schema: field_dict["mask"] = feature[schema.index("mask")].to(self.device) + pad_mask = kwargs.get(f"{field_name}{PAD_MASK_SUFFIX}") + if pad_mask is not None: + field_dict["pad_mask"] = pad_mask.to(self.device) inputs[field_name] = field_dict return inputs diff --git a/pyhealth/models/jamba_ehr.py b/pyhealth/models/jamba_ehr.py index 0d76038de2..1c212c8e07 100644 --- a/pyhealth/models/jamba_ehr.py +++ b/pyhealth/models/jamba_ehr.py @@ -15,6 +15,7 @@ from pyhealth.datasets import SampleDataset from pyhealth.models import BaseModel from pyhealth.models.embedding import EmbeddingModel +from pyhealth.datasets.utils import PAD_MASK_SUFFIX from pyhealth.models.unified_embedding import UnifiedMultimodalEmbeddingModel from pyhealth.models.transformer import TransformerBlock from pyhealth.models.ehrmamba import MambaBlock @@ -305,6 +306,9 @@ def _build_unified_inputs( field_dict["time"] = feature[schema.index("time")].to(self.device) if "mask" in schema: field_dict["mask"] = feature[schema.index("mask")].to(self.device) + pad_mask = kwargs.get(f"{field_name}{PAD_MASK_SUFFIX}") + if pad_mask is not None: + field_dict["pad_mask"] = pad_mask.to(self.device) inputs[field_name] = field_dict return inputs diff --git a/pyhealth/models/rnn.py b/pyhealth/models/rnn.py index 251f1d7ff2..6d08a80c03 100644 --- a/pyhealth/models/rnn.py +++ b/pyhealth/models/rnn.py @@ -24,6 +24,7 @@ ) from .embedding import EmbeddingModel +from pyhealth.datasets.utils import PAD_MASK_SUFFIX from .unified_embedding import UnifiedMultimodalEmbeddingModel from .utils import mask_lengths from .sequence_embedding import ( @@ -283,6 +284,9 @@ def _build_unified_inputs( field_dict["time"] = feature[schema.index("time")].to(self.device) if "mask" in schema: field_dict["mask"] = feature[schema.index("mask")].to(self.device) + pad_mask = kwargs.get(f"{field_name}{PAD_MASK_SUFFIX}") + if pad_mask is not None: + field_dict["pad_mask"] = pad_mask.to(self.device) inputs[field_name] = field_dict return inputs diff --git a/pyhealth/models/transformer.py b/pyhealth/models/transformer.py index 1c62d295e3..685ac114a6 100644 --- a/pyhealth/models/transformer.py +++ b/pyhealth/models/transformer.py @@ -13,6 +13,7 @@ from pyhealth.datasets import SampleDataset from pyhealth.models import BaseModel from pyhealth.models.embedding import EmbeddingModel +from pyhealth.datasets.utils import PAD_MASK_SUFFIX from pyhealth.models.unified_embedding import UnifiedMultimodalEmbeddingModel from pyhealth.interpret.api import CheferInterpretable @@ -530,6 +531,9 @@ def _build_unified_inputs( field_dict["time"] = feature[schema.index("time")].to(self.device) if "mask" in schema: field_dict["mask"] = feature[schema.index("mask")].to(self.device) + pad_mask = kwargs.get(f"{field_name}{PAD_MASK_SUFFIX}") + if pad_mask is not None: + field_dict["pad_mask"] = pad_mask.to(self.device) inputs[field_name] = field_dict return inputs diff --git a/pyhealth/models/unified_embedding.py b/pyhealth/models/unified_embedding.py index 379af74592..623013fbd5 100644 --- a/pyhealth/models/unified_embedding.py +++ b/pyhealth/models/unified_embedding.py @@ -678,6 +678,7 @@ def forward( # {field}_mask a separate FIELD meaning "was this value # observed", consumed by the standardiser below. mask = feat_dict.get("mask") + pad_mask = feat_dict.get("pad_mask") if time is None: # Fallback: treat every event as occurring at t=0 @@ -735,12 +736,36 @@ def forward( ) elif modality == ModalityType.TEXT: + # Collate pads note slots to the longest sample in the batch. + # Running BERT on those empty rows is what OOM'd batch-32 + # notes_labs on a 48 GB GPU (~B*N=full pad width, L=512). b, n, l = value.shape - flat_ids = value.view(b * n, l) - flat_mask = mask.view(b * n, l) if mask is not None else None - cls_emb = self._encode_text_cls( - field_name, encoder, flat_ids, flat_mask - ) # (B*N, H) + flat_ids = value.reshape(b * n, l) + flat_attn = mask.reshape(b * n, l) if mask is not None else None + if pad_mask is not None: + valid = pad_mask.reshape(b * n).bool() + elif flat_attn is not None: + valid = flat_attn.any(dim=-1) + else: + valid = torch.ones( + b * n, dtype=torch.bool, device=value.device + ) + hidden = encoder.config.hidden_size + first_param = next(encoder.parameters(), None) + param_dtype = ( + first_param.dtype if first_param is not None + else torch.get_default_dtype() + ) + cls_emb = value.new_zeros((b * n, hidden), dtype=param_dtype) + if valid.any(): + h = self._encode_text_cls( + field_name, + encoder, + flat_ids[valid], + flat_attn[valid] if flat_attn is not None else None, + ) + cls_emb = cls_emb.to(dtype=h.dtype) + cls_emb[valid] = h if field_name in self.projections: cls_emb = self.projections[field_name](cls_emb) # cls_emb.shape[-1] instead of -1: when b*n == 0 (no note @@ -749,16 +774,27 @@ def forward( emb = cls_emb.view(b, n, cls_emb.shape[-1]) # (B, N, E') elif modality == ModalityType.IMAGE: + # encoder = Sequential(PatchEmbedding, _MeanPool) -> (B*N, E') b, n, c, h, w = value.shape - flat_imgs = value.view(b * n, c, h, w) + flat_imgs = value.reshape(b * n, c, h, w) if b * n == 0: # No image slots in this batch. reshape(0, -1) is # ambiguous since -1 can be any value for 0 elements. - img_emb = value.new_zeros((0, self._embedding_dim)) + valid = torch.zeros(b * n, dtype=torch.bool, device=value.device) + elif pad_mask is not None: + valid = pad_mask.reshape(b * n).bool() else: - img_emb = encoder(flat_imgs) # (B*N, E') + valid = flat_imgs.reshape(b * n, -1).abs().sum(dim=-1) > 0 + if valid.any(): + img_valid = encoder(flat_imgs[valid]) + emb_dim = img_valid.shape[-1] + img_emb = img_valid.new_zeros((b * n, emb_dim)) + img_emb[valid] = img_valid + else: + emb_dim = self._embedding_dim + img_emb = value.new_zeros((b * n, emb_dim)) # Explicit dim instead of -1: same 0-element ambiguity. - emb = img_emb.view(b, n, img_emb.shape[-1]) + emb = img_emb.view(b, n, emb_dim) # (B, N, E') else: # NUMERIC / SIGNAL # Standardise BEFORE the projection. The projection mixes the @@ -794,7 +830,19 @@ def forward( emb = encoder(value) # (B, T, E') # ── Build event-level validity mask ─────────────────────────── - if mask is None: + if pad_mask is not None: + # The collator is authoritative about batch padding. + event_mask = pad_mask.to(emb.device).float() + if event_mask.shape[1] != emb.shape[1]: + # A nested CODE field was flattened to (B, S*C); repeat the + # event flags along the same axis. + repeat = emb.shape[1] // event_mask.shape[1] + event_mask = ( + event_mask.unsqueeze(-1) + .expand(-1, -1, repeat) + .reshape(emb.shape[0], -1) + ) + elif mask is None: event_mask = torch.ones(emb.shape[:2], device=emb.device) else: if mask.dim() > time.dim(): @@ -821,13 +869,20 @@ def forward( cat_types = torch.cat(all_types, dim=1) # (B, S_total) # ── Sort by time ────────────────────────────────────────────────── - sort_idx = cat_time.argsort(dim=1) - cat_emb = cat_emb.gather( - 1, sort_idx.unsqueeze(-1).expand_as(cat_emb) - ) - cat_time = cat_time.gather(1, sort_idx) - cat_mask = cat_mask.gather(1, sort_idx) - cat_types = cat_types.gather(1, sort_idx) + # Padding carries time 0.0, so a plain ascending sort places it BEFORE + # every real event. Push invalid slots past every real one to keep the + # sequence left-aligned, which is what all consumers assume. + # + # Stable, because the key is heavily tied: all padding shares time 0.0 + # and events from one admission share offsets. An unstable sort makes + # event order differ between torch builds and between CPU and CUDA, + # silently changing RNN and Mamba outputs. + sort_key = cat_time.masked_fill(~cat_mask.bool(), float("inf")) + sort_idx = sort_key.argsort(dim=1, stable=True) + cat_emb = cat_emb.gather(1, sort_idx.unsqueeze(-1).expand_as(cat_emb)) + cat_time = cat_time.gather(1, sort_idx) + cat_mask = cat_mask.gather(1, sort_idx) + cat_types = cat_types.gather(1, sort_idx) # ── Add time + type embeddings ──────────────────────────────────── time_emb = self.time_embed(cat_time) # (B, S_total, E') diff --git a/tests/core/test_p1_pad_masks.py b/tests/core/test_p1_pad_masks.py index 584e2aaa3d..33a8973c9b 100644 --- a/tests/core/test_p1_pad_masks.py +++ b/tests/core/test_p1_pad_masks.py @@ -1,10 +1,119 @@ -"""Ragged text tuples collate positionally like (time, values) pairs.""" +"""Batch padding is recorded and skipped by the unified path. + +The collator padded short samples with 0.0 and nothing recorded that padding, +so padded slots looked like real measurements at admission time. +""" from __future__ import annotations import unittest import torch +import torch.nn as nn + + +class TestP1RnnClamp(unittest.TestCase): + def test_all_pad_mask_forward_is_finite(self): + from pyhealth.models.rnn import RNNLayer + + layer = RNNLayer(input_size=4, hidden_size=8, dropout=0.0).eval() + x = torch.zeros(2, 5, 4) + mask = torch.zeros(2, 5) + with torch.no_grad(): + outputs, last = layer(x, mask) + self.assertEqual(outputs.shape[0], 2) + self.assertEqual(tuple(last.shape), (2, 8)) + self.assertTrue(torch.isfinite(last).all()) + + +class TestP1BertPadSkip(unittest.TestCase): + def test_collate_emits_false_pad_mask_on_empty_note_slots(self): + from pyhealth.datasets.utils import PAD_MASK_SUFFIX, collate_fn_dict_with_padding + + batch = [ + {"notes": (torch.ones(3, 4, dtype=torch.long), torch.ones(3, 4))}, + {"notes": (torch.ones(1, 4, dtype=torch.long), torch.ones(1, 4))}, + ] + collated = collate_fn_dict_with_padding(batch) + ids = collated["notes"][1] + pad = collated[f"notes{PAD_MASK_SUFFIX}"] + self.assertEqual(tuple(ids.shape), (2, 3, 4)) + self.assertEqual(pad.tolist(), [[True, True, True], [True, False, False]]) + + def test_padded_events_sort_last_and_are_zeroed(self): + from pyhealth.models.unified_embedding import UnifiedMultimodalEmbeddingModel + from pyhealth.processors.stagenet_processor import StageNetTensorProcessor + + proc = StageNetTensorProcessor() + proc.fit([{"labs": ([0.0], [[1.0, 2.0]])}], "labs") + model = UnifiedMultimodalEmbeddingModel( + processors={"labs": proc}, + embedding_dim=8, + normalize_content=True, + ) + model.eval() + value = torch.tensor([[[3.0, 4.0], [0.0, 0.0]]]) + time = torch.tensor([[6.0, 0.0]]) + pad_mask = torch.tensor([[True, False]]) + with torch.no_grad(): + out = model({"labs": {"value": value, "time": time, "pad_mask": pad_mask}}) + self.assertEqual(out["mask"].tolist(), [[1.0, 0.0]]) + self.assertAlmostEqual(out["time"][0, 0].item(), 6.0) + self.assertTrue(torch.allclose(out["sequence"][0, 1], torch.zeros(8), atol=1e-6)) + + def test_text_encoder_skips_padded_note_slots(self): + from types import SimpleNamespace + + from pyhealth.models.unified_embedding import UnifiedMultimodalEmbeddingModel + from pyhealth.processors import TupleTimeTextProcessor + + class CountingEnc(nn.Module): + def __init__(self): + super().__init__() + self.calls = 0 + self.lin = nn.Linear(4, 8) + self.config = type("C", (), {"hidden_size": 8})() + + def forward(self, input_ids, attention_mask=None): + self.calls += 1 + h = self.lin(input_ids.float()) + return type("O", (), {"last_hidden_state": h.unsqueeze(1)})() + + proc = TupleTimeTextProcessor() + enc = CountingEnc() + pre = SimpleNamespace(transformer=enc, fc=nn.Identity(), embedding_dim=8) + model = UnifiedMultimodalEmbeddingModel( + {"notes": proc}, embedding_dim=8, field_embeddings={"notes": pre} + ) + model.eval() + with torch.no_grad(): + out = model( + { + "notes": { + "value": torch.ones(1, 3, 4, dtype=torch.long), + "time": torch.tensor([[2.0, 0.0, 1.0]]), + "pad_mask": torch.tensor([[True, False, True]]), + } + } + ) + # One batched call over the 2 valid rows; the padded slot sorts last. + self.assertEqual(enc.calls, 1) + self.assertEqual(out["sequence"].shape, (1, 3, 8)) + self.assertEqual(out["mask"].tolist(), [[1.0, 1.0, 0.0]]) + self.assertEqual(out["time"].tolist(), [[1.0, 2.0, 0.0]]) + + def test_unified_heads_thread_pad_mask(self): + import inspect + + from pyhealth.models.ehrmamba import EHRMamba + from pyhealth.models.jamba_ehr import JambaEHR + from pyhealth.models.rnn import RNN + from pyhealth.models.transformer import Transformer + + for cls in (RNN, Transformer, EHRMamba, JambaEHR): + src = inspect.getsource(cls._build_unified_inputs) + self.assertIn("PAD_MASK_SUFFIX", src, msg=cls.__name__) + self.assertIn("pad_mask", src, msg=cls.__name__) class TestP1TextTupleCollate(unittest.TestCase): @@ -69,6 +178,55 @@ def test_text_tuples_stay_a_list_without_the_processor_collate(self): collated = collate_fn_dict_with_padding(batch, collators={"notes": untokenized}) self.assertIsInstance(collated["notes"], list) + def test_build_unified_inputs_consumes_stacked_text(self): + from types import SimpleNamespace + + from pyhealth.datasets.utils import collate_fn_dict_with_padding + from pyhealth.models.rnn import RNN + from pyhealth.processors import StageNetTensorProcessor, TupleTimeTextProcessor + + notes_proc = TupleTimeTextProcessor( + tokenizer_model="emilyalsentzer/Bio_ClinicalBERT", + type_tag="note", + max_length=8, + ) + labs_proc = StageNetTensorProcessor() + labs_proc.fit([{"labs": ([0.0], [[1.0, 2.0]])}], "labs") + dataset = SimpleNamespace( + input_processors={"notes": notes_proc, "labs": labs_proc} + ) + batch = collate_fn_dict_with_padding( + [ + { + "notes": notes_proc.process( + (["note one", "second note"], [0.0, 1.0]) + ), + "labs": labs_proc.process(([0.0], [[1.0, 2.0]])), + }, + { + "notes": notes_proc.process(([], [])), + "labs": labs_proc.process(([0.0, 1.0], [[3.0, 4.0], [5.0, 6.0]])), + }, + ], + collators={"notes": notes_proc.collate}, + ) + stub = SimpleNamespace( + feature_keys=["notes", "labs"], dataset=dataset, device="cpu" + ) + inputs = RNN._build_unified_inputs(stub, batch) + # Tokenizer pads to the longest note in the batch (4 tokens here). + self.assertEqual(tuple(inputs["notes"]["value"].shape), (2, 2, 4)) + self.assertEqual(tuple(inputs["notes"]["mask"].shape), (2, 2, 4)) + self.assertEqual(tuple(inputs["notes"]["time"].shape), (2, 2)) + # Text is stacked by its processor, which emits no pad mask: a + # padded note slot is the one with an all-zero attention mask. + self.assertNotIn("pad_mask", inputs["notes"]) + self.assertEqual( + inputs["notes"]["mask"].any(dim=-1).tolist(), + [[True, True], [False, False]], + ) + self.assertEqual(tuple(inputs["labs"]["value"].shape), (2, 2, 2)) + def test_two_tuple_contract_unchanged(self): from pyhealth.datasets.utils import PAD_MASK_SUFFIX, collate_fn_dict_with_padding From a66e17ff3fe44504ac4f88de4766851cb276cb34 Mon Sep 17 00:00:00 2001 From: Rian Date: Tue, 3 Nov 2026 03:00:32 -0500 Subject: [PATCH 15/17] Thread collate pad_mask through the unified MLP path. MLP gains unified mode with masked mean-pooling over the joint event sequence, threading pad_mask like the other heads so padded slots score nothing. Per-field mode is unchanged. Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95 --- pyhealth/models/mlp.py | 103 ++++++++++++++++++++++++----- tests/core/test_p2_mlp_pad_mask.py | 85 ++++++++++++++++++++++++ 2 files changed, 170 insertions(+), 18 deletions(-) create mode 100644 tests/core/test_p2_mlp_pad_mask.py diff --git a/pyhealth/models/mlp.py b/pyhealth/models/mlp.py index 4b86a5b939..09303685bf 100644 --- a/pyhealth/models/mlp.py +++ b/pyhealth/models/mlp.py @@ -1,13 +1,15 @@ -from typing import Dict, cast +from typing import Any, cast import torch import torch.nn as nn from pyhealth.datasets import SampleDataset -from pyhealth.models import BaseModel +from pyhealth.datasets.utils import PAD_MASK_SUFFIX from pyhealth.interpret.api import Interpretable +from pyhealth.models import BaseModel from .embedding import EmbeddingModel +from .unified_embedding import UnifiedMultimodalEmbeddingModel from .utils import get_step_mask, masked_mean_pooling @@ -61,6 +63,9 @@ class MLP(BaseModel, Interpretable): hidden_dim: the hidden dimension. Default is 128. n_layers: the number of layers. Default is 2. activation: the activation function. Default is "relu". + unified_embedding (UnifiedMultimodalEmbeddingModel, optional): when + provided, the model mean-pools one unified event sequence through + a single MLP instead of per-field MLPs. **kwargs: other parameters for the MLP layer. Examples: @@ -118,12 +123,14 @@ def __init__( hidden_dim: int = 128, n_layers: int = 2, activation: str = "relu", + unified_embedding: UnifiedMultimodalEmbeddingModel | None = None, **kwargs, ): super(MLP, self).__init__(dataset) self.embedding_dim = embedding_dim self.hidden_dim = hidden_dim self.n_layers = n_layers + self._use_unified = unified_embedding is not None # validate kwargs for MLP layer if "input_size" in kwargs: @@ -134,9 +141,6 @@ def __init__( assert len(self.label_keys) == 1, "Only one label key is supported" self.label_key = self.label_keys[0] - # Use the EmbeddingModel to handle embedding logic - self.embedding_model = EmbeddingModel(dataset, embedding_dim) - # Set up activation function if activation == "relu": self.activation = nn.ReLU() @@ -151,18 +155,73 @@ def __init__( else: raise ValueError(f"Unsupported activation function {activation}") - # Create MLP layers for each feature - self.mlp = nn.ModuleDict() - for feature_key in self.feature_keys: - Modules = [] - Modules.append(nn.Linear(self.embedding_dim, self.hidden_dim)) - for _ in range(self.n_layers - 1): - Modules.append(self.activation) - Modules.append(nn.Linear(self.hidden_dim, self.hidden_dim)) - self.mlp[feature_key] = nn.Sequential(*Modules) - output_size = self.label_processor.output_size() - self.fc = nn.Linear(len(self.feature_keys) * self.hidden_dim, output_size) + + if self._use_unified: + self.embedding_model = unified_embedding + modules = [nn.Linear(embedding_dim, hidden_dim)] + for _ in range(n_layers - 1): + modules.extend([self.activation, nn.Linear(hidden_dim, hidden_dim)]) + self.mlp = nn.ModuleDict({"unified": nn.Sequential(*modules)}) + self.fc = nn.Linear(hidden_dim, output_size) + else: + # Use the EmbeddingModel to handle embedding logic + self.embedding_model = EmbeddingModel(dataset, embedding_dim) + # Create MLP layers for each feature + self.mlp = nn.ModuleDict() + for feature_key in self.feature_keys: + Modules = [] + Modules.append(nn.Linear(self.embedding_dim, self.hidden_dim)) + for _ in range(self.n_layers - 1): + Modules.append(self.activation) + Modules.append(nn.Linear(self.hidden_dim, self.hidden_dim)) + self.mlp[feature_key] = nn.Sequential(*Modules) + self.fc = nn.Linear(len(self.feature_keys) * self.hidden_dim, output_size) + + def _build_unified_inputs( + self, kwargs: dict[str, Any] + ) -> dict[str, dict[str, torch.Tensor]]: + inputs: dict[str, dict[str, torch.Tensor]] = {} + for field_name in self.feature_keys: + feature = kwargs[field_name] + if isinstance(feature, torch.Tensor): + feature = (feature,) + schema = self.dataset.input_processors[field_name].schema() + field_dict: dict[str, torch.Tensor] = {} + if "value" in schema: + field_dict["value"] = feature[schema.index("value")].to(self.device) + if "time" in schema: + field_dict["time"] = feature[schema.index("time")].to(self.device) + if "mask" in schema: + field_dict["mask"] = feature[schema.index("mask")].to(self.device) + pad_mask = kwargs.get(f"{field_name}{PAD_MASK_SUFFIX}") + if pad_mask is not None: + field_dict["pad_mask"] = pad_mask.to(self.device) + inputs[field_name] = field_dict + return inputs + + def _forward_unified(self, **kwargs: Any) -> dict[str, torch.Tensor]: + inputs = self._build_unified_inputs(kwargs) + out = self.embedding_model(inputs) + sequence = out["sequence"] + mask = out["mask"].float() + + # Masked mean-pool over the event sequence + x = (sequence * mask.unsqueeze(-1)).sum(dim=1) + x = x / mask.sum(dim=1, keepdim=True).clamp(min=1) + + x = self.mlp["unified"](x) + logits = self.fc(x) + y_prob = self.label_processor.activation(logits) + + results: dict[str, torch.Tensor] = {"logit": logits, "y_prob": y_prob} + if self.label_key in kwargs: + y_true = cast(torch.Tensor, kwargs[self.label_key]).to(self.device) + results["loss"] = self.label_processor.loss(logits, y_true) + results["y_true"] = y_true + if kwargs.get("embed", False): + results["embed"] = x + return results @staticmethod def mean_pooling(x, mask): @@ -208,7 +267,7 @@ def sum_pooling(x): def forward_from_embedding( self, **kwargs: torch.Tensor | tuple[torch.Tensor, ...], - ) -> Dict[str, torch.Tensor]: + ) -> dict[str, torch.Tensor]: """Forward pass starting from feature embeddings. This method bypasses the embedding layers and processes @@ -327,9 +386,14 @@ def forward_from_embedding( def forward( self, **kwargs: torch.Tensor | tuple[torch.Tensor, ...] - ) -> Dict[str, torch.Tensor]: + ) -> dict[str, torch.Tensor]: """Forward propagation. + In **unified mode** (when ``unified_embedding`` was supplied at init) + the model jointly embeds all temporal fields, mean-pools the event + sequence, and processes it with a single MLP. Otherwise each field + is embedded and encoded independently. + Args: **kwargs: keyword arguments for the model. @@ -347,6 +411,9 @@ def forward( logit: the raw logits before activation. embed: (if embed=True in kwargs) the patient embedding. """ + if self._use_unified: + return self._forward_unified(**kwargs) + for feature_key in self.feature_keys: feature = kwargs[feature_key] diff --git a/tests/core/test_p2_mlp_pad_mask.py b/tests/core/test_p2_mlp_pad_mask.py new file mode 100644 index 0000000000..6f96a97ab1 --- /dev/null +++ b/tests/core/test_p2_mlp_pad_mask.py @@ -0,0 +1,85 @@ +"""Unified MLP threads collate pad_mask like the other heads.""" + +from __future__ import annotations + +import unittest +from types import SimpleNamespace + +import torch + + +class TestP2MlpPadMask(unittest.TestCase): + def test_mlp_threads_pad_mask_into_unified_inputs(self): + from pyhealth.datasets.utils import PAD_MASK_SUFFIX, collate_fn_dict_with_padding + from pyhealth.models.mlp import MLP + from pyhealth.processors.stagenet_processor import StageNetTensorProcessor + + batch = [ + {"labs": (torch.tensor([6.0, 12.0, 24.0]), torch.ones(3, 2))}, + {"labs": (torch.tensor([6.0]), torch.ones(1, 2))}, + ] + collated = collate_fn_dict_with_padding(batch) + self.assertIn(f"labs{PAD_MASK_SUFFIX}", collated) + + host = SimpleNamespace( + feature_keys=["labs"], + device="cpu", + dataset=SimpleNamespace( + input_processors={"labs": StageNetTensorProcessor()} + ), + ) + inputs = MLP._build_unified_inputs(host, collated) + self.assertEqual( + inputs["labs"]["pad_mask"].tolist(), + [[True, True, True], [True, False, False]], + ) + + def test_unified_forward_ignores_padded_slots(self): + from pyhealth.datasets import create_sample_dataset, get_dataloader + from pyhealth.models.mlp import MLP + from pyhealth.models.unified_embedding import UnifiedMultimodalEmbeddingModel + + samples = [ + { + "patient_id": "patient-0", + "visit_id": "visit-0", + "codes": ([0.0, 2.0], ["A", "B"]), + "labs": ([0.0, 2.0], [[1.0, 2.0], [3.0, 4.0]]), + "label": 1, + }, + { + "patient_id": "patient-1", + "visit_id": "visit-0", + "codes": ([0.0], ["C"]), + "labs": ([0.0], [[5.0, 6.0]]), + "label": 0, + }, + ] + dataset = create_sample_dataset( + samples=samples, + input_schema={"codes": "stagenet", "labs": "stagenet_tensor"}, + output_schema={"label": "binary"}, + dataset_name="test_mlp_unified", + ) + unified = UnifiedMultimodalEmbeddingModel( + dataset.input_processors, embedding_dim=8 + ) + model = MLP( + dataset=dataset, embedding_dim=8, hidden_dim=8, + unified_embedding=unified, + ) + batch = next(iter(get_dataloader(dataset, batch_size=2, shuffle=False))) + out = model(**batch) + self.assertTrue(torch.isfinite(out["loss"])) + out["loss"].backward() + self.assertTrue( + any( + p.grad is not None + for p in model.parameters() + if p.requires_grad + ) + ) + + +if __name__ == "__main__": + unittest.main() From 73608f074dfbff368d6fd5e5f172a99f406b8b5e Mon Sep 17 00:00:00 2001 From: Rian Date: Tue, 3 Nov 2026 04:04:25 -0500 Subject: [PATCH 16/17] Add BottleneckTransformer model with unified-embedding mode. Per-field mode embeds each feature stream, prefixes a learnable [CLS] per modality, and fuses via shared bottleneck tokens; unified mode runs the same encoder with n_modality=1 over the time-sorted cross-modal sequence (with the collate pad_mask threaded through, as in the other unified heads). New synthetic tests cover per-field and unified forward + backward, finite outputs. Adds the model docs page per the model checklist. Sources: #1185 a92c25a5 (model) + 7c4c0561 (pad-skip hunk); imports adapted from the embedding/ package to the flat unified_embedding module. Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95 --- docs/api/models.rst | 1 + .../pyhealth.models.BottleneckTransformer.rst | 15 + pyhealth/models/__init__.py | 1 + pyhealth/models/bottleneck_transformer.py | 541 ++++++++++++++++++ tests/core/test_bottleneck_transformer.py | 89 +++ 5 files changed, 647 insertions(+) create mode 100644 docs/api/models/pyhealth.models.BottleneckTransformer.rst create mode 100644 pyhealth/models/bottleneck_transformer.py create mode 100644 tests/core/test_bottleneck_transformer.py diff --git a/docs/api/models.rst b/docs/api/models.rst index ea3f7c3b81..1837668521 100644 --- a/docs/api/models.rst +++ b/docs/api/models.rst @@ -301,6 +301,7 @@ API Reference models/pyhealth.models.Transformer models/pyhealth.models.BEHRT models/pyhealth.models.BiteNet + models/pyhealth.models.BottleneckTransformer models/pyhealth.models.TransformersModel models/pyhealth.models.LLMEHREncoder models/pyhealth.models.HFEHRFoundationModel diff --git a/docs/api/models/pyhealth.models.BottleneckTransformer.rst b/docs/api/models/pyhealth.models.BottleneckTransformer.rst new file mode 100644 index 0000000000..470563c303 --- /dev/null +++ b/docs/api/models/pyhealth.models.BottleneckTransformer.rst @@ -0,0 +1,15 @@ +pyhealth.models.BottleneckTransformer +====================================== + + +The shared bottleneck encoder and the complete Bottleneck Transformer model. + +.. autoclass:: pyhealth.models.MultimodalBottleneckTransformerEncoder + :members: + :undoc-members: + :show-inheritance: + +.. autoclass:: pyhealth.models.BottleneckTransformer + :members: + :undoc-members: + :show-inheritance: diff --git a/pyhealth/models/__init__.py b/pyhealth/models/__init__.py index 2406b8eb53..d609ebb10c 100644 --- a/pyhealth/models/__init__.py +++ b/pyhealth/models/__init__.py @@ -30,6 +30,7 @@ ) from .transformer_deid import TransformerDeID from .biot import BIOT +from .bottleneck_transformer import BottleneckTransformer as BottleneckTransformer from .cnn import CNN, CNNLayer from .concare import ConCare, ConCareLayer from .contrawr import ContraWR, ResBlock2D diff --git a/pyhealth/models/bottleneck_transformer.py b/pyhealth/models/bottleneck_transformer.py new file mode 100644 index 0000000000..2d81c02c30 --- /dev/null +++ b/pyhealth/models/bottleneck_transformer.py @@ -0,0 +1,541 @@ +from typing import Any, cast + +import torch +from torch import nn + +from pyhealth.datasets import SampleDataset +from pyhealth.datasets.utils import PAD_MASK_SUFFIX +from pyhealth.models import BaseModel +from pyhealth.models.embedding import EmbeddingModel +from pyhealth.models.unified_embedding import UnifiedMultimodalEmbeddingModel + + +class MultimodalBottleneckTransformerEncoder(nn.Module): + """ + Generalized Bottleneck Transformer Encoder for N modalities. + Based on "Attention Bottlenecks for Multimodal Fusion" (Nagrani et al., NeurIPS 2021). + + Example: + >>> import torch + >>> from pyhealth.models.bottleneck_transformer import ( + ... MultimodalBottleneckTransformerEncoder, + ... ) + >>> encoder = MultimodalBottleneckTransformerEncoder( + ... n_modality=2, bottlenecks_n=2, fusion_startidx=1, + ... n_layers=2, n_head=2, d_model=8, d_ff=16, + ... ) + >>> masks = [ + ... torch.ones(1, 3, dtype=torch.bool), + ... torch.ones(1, 2, dtype=torch.bool), + ... ] + >>> out = encoder([torch.zeros(1, 3, 8), torch.zeros(1, 2, 8)], masks) + >>> [o.shape for o in out] + [torch.Size([1, 3, 8]), torch.Size([1, 2, 8])] + """ + + def __init__( + self, + n_modality: int, + bottlenecks_n: int, + fusion_startidx: int, + n_layers: int, + n_head: int, + d_model: int, + d_ff: int, + dropout: float = 0.1, + ): + super().__init__() + + self.n_modality = n_modality + self.fusion_startidx = fusion_startidx + self.n_layers = n_layers + self.n_fusion_layers = n_layers - fusion_startidx + self.n_prefusion = fusion_startidx + self.d_model = d_model + self.n_bottlenecks = bottlenecks_n + + # Shared Bottleneck Tokens — small init to avoid early gradient explosion + self.bottlenecks = nn.Parameter(torch.randn(1, bottlenecks_n, d_model) * 0.02) + + # Prefusion Stacks: independent layers per modality + self.prefusion_stacks = nn.ModuleList([ + nn.ModuleList([ + nn.TransformerEncoderLayer( + d_model=d_model, + nhead=n_head, + dim_feedforward=d_ff, + dropout=dropout, + batch_first=True + ) for _ in range(n_modality) + ]) for _ in range(self.n_prefusion) + ]) + + # Fusion Stacks: processes [bottleneck_tokens || modality_tokens] + self.fusion_stacks = nn.ModuleList([ + nn.ModuleList([ + nn.TransformerEncoderLayer( + d_model=d_model, + nhead=n_head, + dim_feedforward=d_ff, + dropout=dropout, + batch_first=True + ) for _ in range(n_modality) + ]) for _ in range(self.n_fusion_layers) + ]) + + def forward_prefusion(self, enc_inputs: list[torch.Tensor], masks: list[torch.Tensor]) -> list[torch.Tensor]: + for enc_layers in self.prefusion_stacks: + enc_outputs = [] + for modal_idx, enc_layer in enumerate(enc_layers): + # Apply mask to padding tokens (src_key_padding_mask requires True for ignoring) + # True in mask = invalid/padding + enc_out = enc_layer(enc_inputs[modal_idx], src_key_padding_mask=~masks[modal_idx] if masks[modal_idx] is not None else None) + enc_outputs.append(enc_out) + enc_inputs = enc_outputs + return enc_inputs + + def forward_fusion(self, enc_inputs: list[torch.Tensor], masks: list[torch.Tensor], bottleneck_tokens: torch.Tensor, valid_modalities: list[torch.Tensor]) -> list[torch.Tensor]: + # valid_modalities: [B] list of boolean/float tensors indicating if modality is present + batch_size = enc_inputs[0].size(0) + + for modality_encoders in self.fusion_stacks: + enc_outputs = [] + bottleneck_tokens_modality_sum = torch.zeros_like(bottleneck_tokens) + sum_of_modalities = torch.zeros(batch_size, 1, 1, device=bottleneck_tokens.device) + + for idx, enc_layer in enumerate(modality_encoders): + # Concatenate bottleneck tokens with modality tokens + # bottleneck_tokens: [B, num_bottlenecks, d_model] + # enc_inputs[idx]: [B, seq_len, d_model] + fused_input = torch.cat([bottleneck_tokens, enc_inputs[idx]], dim=1) + + # Padding mask for bottleneck tokens is always False (i.e. valid) + # [B, num_bottlenecks] of False + b_mask = torch.zeros(batch_size, self.n_bottlenecks, dtype=torch.bool, device=fused_input.device) + + # Modality padding mask + m_mask = ~masks[idx] if masks[idx] is not None else torch.zeros(batch_size, enc_inputs[idx].size(1), dtype=torch.bool, device=fused_input.device) + + combined_mask = torch.cat([b_mask, m_mask], dim=1) + + # Pass through the layer + enc_out = enc_layer(fused_input, src_key_padding_mask=combined_mask) + + # The output consists of processed bottleneck tokens and modality tokens + # [B, num_bottlenecks, d_model] and [B, seq_len, d_model] + bottleneck_hidden_tokens = enc_out[:, :self.n_bottlenecks, :] + modality_hidden_tokens = enc_out[:, self.n_bottlenecks:, :] + enc_outputs.append(modality_hidden_tokens) + + # Average updated bottlenecks from valid modalities + modality_is_valid = valid_modalities[idx].view(batch_size, 1, 1) + bottleneck_tokens_modality_sum += bottleneck_hidden_tokens * modality_is_valid + sum_of_modalities += modality_is_valid + + # Prevent division by zero if all modalities are missing + # If sum_of_modalities is 0, just pass zeros (or keep previous bottleneck_tokens) + # sum_of_modalities = torch.clamp(sum_of_modalities, min=1.0) + avg_divisor = sum_of_modalities.clone() + avg_divisor[avg_divisor == 0] = 1.0 + + bottleneck_tokens = bottleneck_tokens_modality_sum / avg_divisor + enc_inputs = enc_outputs + + return enc_inputs + + def forward(self, enc_inputs: list[torch.Tensor], masks: list[torch.Tensor]) -> list[torch.Tensor]: + batch_size = enc_inputs[0].size(0) + + # Determine if a modality is valid for each instance in the batch + # A modality is valid if it has at least one True in its mask + valid_modalities = [] + for mask, inp in zip(masks, enc_inputs): + if mask is not None: + # [B] - True if there's any valid token (1/True) + valid = mask.any(dim=1).float() + else: + valid = torch.ones(batch_size, device=inp.device) + valid_modalities.append(valid) + + bottleneck_tokens = self.bottlenecks.expand(batch_size, -1, -1) + + enc_inputs = self.forward_prefusion(enc_inputs, masks) + enc_inputs = self.forward_fusion(enc_inputs, masks, bottleneck_tokens, valid_modalities) + + return enc_inputs + + +class BottleneckTransformer(BaseModel): + """Bottleneck Transformer model for PyHealth datasets. + + Per-field mode: each feature stream is embedded with :class:`EmbeddingModel`, + prefixed with a learnable per-modality ``[CLS]`` token, processed by + independent prefusion layers, then fused via shared bottleneck tokens. + The per-modality ``[CLS]`` embeddings are averaged and fed to the + classification head. + + Unified mode (``unified_embedding`` supplied): all temporal fields are + jointly embedded and time-sorted by + :class:`~pyhealth.models.embedding.unified.UnifiedMultimodalEmbeddingModel` + into a single interleaved sequence. A single ``[CLS]`` token is prepended + and the encoder runs with ``n_modality=1``, so the bottleneck tokens attend + over the full cross-modal timeline. + + Args: + dataset (SampleDataset): dataset providing processed inputs. + embedding_dim (int): shared embedding dimension. + bottlenecks_n (int): number of shared bottleneck tokens. + fusion_startidx (int): layer index at which bottleneck fusion starts. + Must satisfy ``0 <= fusion_startidx <= num_layers``. + num_layers (int): total transformer layers (prefusion + fusion). + heads (int): number of attention heads per transformer block. + dropout (float): dropout rate inside transformer blocks. + unified_embedding (UnifiedMultimodalEmbeddingModel, optional): when + provided, switches to unified mode. + + Examples: + >>> from pyhealth.datasets import create_sample_dataset, get_dataloader + >>> samples = [ + ... { + ... "patient_id": "patient-0", + ... "visit_id": "visit-0", + ... "conditions": ["A", "B", "C"], + ... "procedures": ["X", "Y"], + ... "label": 1, + ... }, + ... { + ... "patient_id": "patient-1", + ... "visit_id": "visit-0", + ... "conditions": ["D"], + ... "procedures": ["Z", "Y"], + ... "label": 0, + ... }, + ... ] + >>> input_schema = {"conditions": "sequence", "procedures": "sequence"} + >>> output_schema = {"label": "binary"} + >>> dataset = create_sample_dataset( + ... samples, + ... input_schema, + ... output_schema, + ... dataset_name="demo", + ... ) + >>> model = BottleneckTransformer(dataset=dataset, num_layers=3, fusion_startidx=1, bottlenecks_n=4) + >>> loader = get_dataloader(dataset, batch_size=2, shuffle=True) + >>> batch = next(iter(loader)) + >>> output = model(**batch) + >>> sorted(output.keys()) + ['logit', 'loss', 'y_prob', 'y_true'] + """ + + def __init__( + self, + dataset: SampleDataset, + embedding_dim: int = 128, + bottlenecks_n: int = 4, + fusion_startidx: int = 1, + num_layers: int = 3, + heads: int = 4, + dropout: float = 0.5, + unified_embedding: UnifiedMultimodalEmbeddingModel | None = None, + ): + super().__init__(dataset=dataset) + self.embedding_dim = embedding_dim + self.bottlenecks_n = bottlenecks_n + self.fusion_startidx = fusion_startidx + self.num_layers = num_layers + self.heads = heads + self.dropout = dropout + self._use_unified = unified_embedding is not None + + assert ( + len(self.label_keys) == 1 + ), "Only one label key is supported if BottleneckTransformer is initialized" + self.label_key = self.label_keys[0] + self.mode = self.dataset.output_schema[self.label_key] + + assert 0 <= fusion_startidx <= num_layers, ( + f"fusion_startidx must be in [0, num_layers], got {fusion_startidx}" + ) + + output_size = self.label_processor.output_size() + + if self._use_unified: + self.embedding_model = unified_embedding + # Single CLS token for the unified interleaved sequence + self.cls_token = nn.Parameter(torch.randn(1, 1, embedding_dim) * 0.02) + self.encoder = MultimodalBottleneckTransformerEncoder( + n_modality=1, + bottlenecks_n=bottlenecks_n, + fusion_startidx=fusion_startidx, + n_layers=num_layers, + n_head=heads, + d_model=embedding_dim, + d_ff=embedding_dim * 4, + dropout=dropout, + ) + else: + self.embedding_model = EmbeddingModel(dataset, embedding_dim) + self.n_modality = len(self.feature_keys) + # Per-modality CLS tokens + self.cls_token_per_modality = nn.ParameterList([ + nn.Parameter(torch.randn(1, 1, embedding_dim) * 0.02) + for _ in range(self.n_modality) + ]) + self.encoder = MultimodalBottleneckTransformerEncoder( + n_modality=self.n_modality, + bottlenecks_n=bottlenecks_n, + fusion_startidx=fusion_startidx, + n_layers=num_layers, + n_head=heads, + d_model=embedding_dim, + d_ff=embedding_dim * 4, + dropout=dropout, + ) + + # fc input is embedding_dim in both modes (CLS token, not concat) + self.fc = nn.Linear(embedding_dim, output_size) + + def _build_unified_inputs( + self, kwargs: dict[str, Any] + ) -> dict[str, dict[str, torch.Tensor]]: + """Extract value/time/mask tensors for UnifiedMultimodalEmbeddingModel.""" + inputs: dict[str, dict[str, torch.Tensor]] = {} + for field_name in self.feature_keys: + feature = kwargs[field_name] + if isinstance(feature, torch.Tensor): + feature = (feature,) + schema = self.dataset.input_processors[field_name].schema() + field_dict: dict[str, torch.Tensor] = {} + if "value" in schema: + field_dict["value"] = feature[schema.index("value")].to(self.device) + if "time" in schema: + field_dict["time"] = feature[schema.index("time")].to(self.device) + if "mask" in schema: + field_dict["mask"] = feature[schema.index("mask")].to(self.device) + pad_mask = kwargs.get(f"{field_name}{PAD_MASK_SUFFIX}") + if pad_mask is not None: + field_dict["pad_mask"] = pad_mask.to(self.device) + inputs[field_name] = field_dict + return inputs + + def _forward_unified( + self, + **kwargs: torch.Tensor | tuple[torch.Tensor, ...], + ) -> dict[str, torch.Tensor]: + """Forward pass in unified-embedding mode. + + Calls UnifiedMultimodalEmbeddingModel to produce a single time-sorted + sequence, prepends a CLS token, encodes with the bottleneck encoder + (n_modality=1), and classifies from the CLS output. + """ + inputs = self._build_unified_inputs(kwargs) + out = self.embedding_model(inputs) + sequence = out["sequence"] # (B, S, E) + event_mask = out["mask"].bool() # (B, S) + + # Prepend CLS token + batch_size = sequence.size(0) + cls = self.cls_token.expand(batch_size, -1, -1) + sequence = torch.cat([cls, sequence], dim=1) + cls_mask = torch.ones(batch_size, 1, dtype=torch.bool, device=sequence.device) + event_mask = torch.cat([cls_mask, event_mask], dim=1) + + enc_outputs = self.encoder([sequence], [event_mask]) + patient_emb = enc_outputs[0][:, 0, :] # CLS token output + + logits = self.fc(patient_emb) + y_prob = self.label_processor.activation(logits) + results: dict[str, torch.Tensor] = {"logit": logits, "y_prob": y_prob} + if self.label_key in kwargs: + y_true = cast(torch.Tensor, kwargs[self.label_key]).to(self.device) + results["loss"] = self.label_processor.loss(logits, y_true) + results["y_true"] = y_true + return results + + @staticmethod + def _pool_embedding(x: torch.Tensor) -> torch.Tensor: + if x.dim() == 4: + x = x.sum(dim=2) + if x.dim() == 2: + x = x.unsqueeze(1) + return x + + @staticmethod + def _mask_from_embeddings(x: torch.Tensor) -> torch.Tensor: + mask = torch.any(torch.abs(x) > 0, dim=-1) + if mask.dim() == 1: + mask = mask.unsqueeze(1) + invalid_rows = ~mask.any(dim=1) + if invalid_rows.any(): + mask[invalid_rows, 0] = True + return mask.bool() + + def forward( + self, + **kwargs: torch.Tensor | tuple[torch.Tensor, ...], + ) -> dict[str, torch.Tensor]: + """Forward propagation. + + In unified mode dispatches to :meth:`_forward_unified`. Otherwise runs + per-field embedding + bottleneck fusion. + + Args: + **kwargs: keyword arguments for the model. + + Returns: + A dictionary with the following keys: + loss: a scalar tensor representing the final loss. + y_prob: a tensor of predicted probabilities. + y_true: a tensor representing the true labels. + logit: the raw logits before activation. + """ + if self._use_unified: + return self._forward_unified(**kwargs) + + enc_inputs = [] + masks = [] + + for idx, feature_key in enumerate(self.feature_keys): + feature = kwargs[feature_key] + + if isinstance(feature, torch.Tensor): + feature = (feature,) + + schema = self.dataset.input_processors[feature_key].schema() + + value = feature[schema.index("value")] if "value" in schema else None + mask = feature[schema.index("mask")] if "mask" in schema else None + + if len(feature) == len(schema) + 1 and mask is None: + mask = feature[-1] + + if value is None: + raise ValueError( + f"Feature '{feature_key}' must contain 'value' " + f"in the schema." + ) + else: + value = value.to(self.device) + + if mask is not None: + mask = mask.to(self.device) + value = self.embedding_model({feature_key: value}, masks={feature_key: mask})[feature_key] + else: + value = self.embedding_model({feature_key: value})[feature_key] + + value = self._pool_embedding(value) + + if mask is not None: + mask = mask.bool() + if mask.dim() == value.dim(): + mask = mask.any(dim=-1) + else: + mask = self._mask_from_embeddings(value) + + # Prepend Modality CLS token + batch_size = value.size(0) + cls_token = self.cls_token_per_modality[idx].expand(batch_size, -1, -1) + value = torch.cat([cls_token, value], dim=1) + + # Update mask for CLS token (always valid) + cls_mask = torch.ones(batch_size, 1, dtype=torch.bool, device=value.device) + mask = torch.cat([cls_mask, mask], dim=1) + + enc_inputs.append(value) + masks.append(mask) + + # Pass through Bottleneck Transformer Encoder + enc_outputs = self.encoder(enc_inputs, masks) + + # Extract CLS tokens + cls_tokens = [out[:, 0, :].unsqueeze(1) for out in enc_outputs] + cls_tokens = torch.cat(cls_tokens, dim=1) # [B, n_modality, embedding_dim] + + # Average CLS tokens across valid modalities + b_size = cls_tokens.size(0) + valid_modalities = [] + for mask in masks: + # We check if there's any valid token aside from the CLS token (index 0) + if mask.size(1) > 1: + valid = mask[:, 1:].any(dim=1).float() + else: + valid = mask[:, 0].float() # fallback + valid_modalities.append(valid.view(b_size, 1, 1)) + + valid_modality_tensor = torch.cat(valid_modalities, dim=1) # [B, n_modality, 1] + + # Apply valid mask + masked_cls = cls_tokens * valid_modality_tensor + sum_valid = valid_modality_tensor.sum(dim=1) # [B, 1] + + # Avoid division by zero + sum_valid[sum_valid == 0] = 1.0 + patient_emb = masked_cls.sum(dim=1) / sum_valid # [B, embedding_dim] + + logits = self.fc(patient_emb) + y_prob = self.label_processor.activation(logits) + + results = { + "logit": logits, + "y_prob": y_prob, + } + + if self.label_key in kwargs: + y_true = cast(torch.Tensor, kwargs[self.label_key]).to(self.device) + loss = self.label_processor.loss(logits, y_true) + results["loss"] = loss + results["y_true"] = y_true + + return results + +if __name__ == "__main__": + from pyhealth.datasets import create_sample_dataset, get_dataloader + + samples = [ + { + "patient_id": "patient-0", + "visit_id": "visit-0", + "conditions": ["A", "B", "C"], + "procedures": ["X", "Y"], + "label": 1, + }, + { + "patient_id": "patient-1", + "visit_id": "visit-0", + "conditions": ["D"], + "procedures": ["Z", "Y"], + "label": 0, + }, + ] + + input_schema = { + "conditions": "sequence", + "procedures": "sequence", + } + output_schema = {"label": "binary"} + + dataset = create_sample_dataset( + samples=samples, + input_schema=input_schema, + output_schema=output_schema, + dataset_name="test", + ) + + train_loader = get_dataloader(dataset, batch_size=2, shuffle=True) + + model = BottleneckTransformer( + dataset=dataset, + embedding_dim=64, + bottlenecks_n=2, + fusion_startidx=1, + num_layers=3, + heads=2 + ) + + data_batch = next(iter(train_loader)) + + result = model(**data_batch) + print(result) + + result["loss"].backward() + print("Test completed successfully.") \ No newline at end of file diff --git a/tests/core/test_bottleneck_transformer.py b/tests/core/test_bottleneck_transformer.py new file mode 100644 index 0000000000..d98b503d03 --- /dev/null +++ b/tests/core/test_bottleneck_transformer.py @@ -0,0 +1,89 @@ +"""BottleneckTransformer per-field and unified modes on a tiny two-field dataset.""" + +import unittest + +import torch + +from pyhealth.datasets import create_sample_dataset, get_dataloader +from pyhealth.models import BottleneckTransformer +from pyhealth.models.unified_embedding import UnifiedMultimodalEmbeddingModel + + +def _dataset(): + samples = [ + { + "patient_id": "patient-0", + "visit_id": "visit-0", + "codes": ([0.0, 2.0], ["A", "B"]), + "labs": ([0.0, 2.0], [[1.0, 2.0], [3.0, 4.0]]), + "label": 1, + }, + { + "patient_id": "patient-1", + "visit_id": "visit-0", + "codes": ([0.0], ["C"]), + "labs": ([0.0], [[5.0, 6.0]]), + "label": 0, + }, + ] + return create_sample_dataset( + samples=samples, + input_schema={"codes": "stagenet", "labs": "stagenet_tensor"}, + output_schema={"label": "binary"}, + dataset_name="test_bottleneck_transformer", + ) + + +def _batch(dataset): + return next(iter(get_dataloader(dataset, batch_size=2, shuffle=False))) + + +class TestBottleneckTransformer(unittest.TestCase): + def test_per_field_forward_backward_finite(self): + dataset = _dataset() + model = BottleneckTransformer( + dataset=dataset, + embedding_dim=8, + bottlenecks_n=2, + fusion_startidx=1, + num_layers=2, + heads=2, + dropout=0.0, + ) + self.assertFalse(model._use_unified) + out = model(**_batch(dataset)) + self.assertEqual(out["logit"].shape, (2, 1)) + self.assertTrue(torch.isfinite(out["loss"])) + out["loss"].backward() + self.assertTrue( + any(p.grad is not None for p in model.parameters() if p.requires_grad) + ) + + def test_unified_forward_backward_finite(self): + dataset = _dataset() + unified = UnifiedMultimodalEmbeddingModel( + dataset.input_processors, embedding_dim=8 + ) + model = BottleneckTransformer( + dataset=dataset, + embedding_dim=8, + bottlenecks_n=2, + fusion_startidx=1, + num_layers=2, + heads=2, + dropout=0.0, + unified_embedding=unified, + ) + self.assertTrue(model._use_unified) + out = model(**_batch(dataset)) + self.assertEqual(out["logit"].shape, (2, 1)) + self.assertTrue(torch.isfinite(out["loss"])) + self.assertTrue(torch.isfinite(out["y_prob"]).all()) + out["loss"].backward() + self.assertTrue( + any(p.grad is not None for p in model.parameters() if p.requires_grad) + ) + + +if __name__ == "__main__": + unittest.main() From bcb47f994bdc2d0b4a26aef9bdc0c9fd2b13cad3 Mon Sep 17 00:00:00 2001 From: jhnwu3 Date: Mon, 23 Nov 2026 20:52:35 -0500 Subject: [PATCH 17/17] Use BaseModel's mode property and fix a docstring reference in BottleneckTransformer. BaseModel.mode is now a read-only property that reads the label processor, so the constructor no longer assigns it. The unified embedding class lives in pyhealth.models.unified_embedding. Co-Authored-By: Claude Fable 5.2 --- pyhealth/models/bottleneck_transformer.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/pyhealth/models/bottleneck_transformer.py b/pyhealth/models/bottleneck_transformer.py index 2d81c02c30..1bb0bf0656 100644 --- a/pyhealth/models/bottleneck_transformer.py +++ b/pyhealth/models/bottleneck_transformer.py @@ -176,7 +176,7 @@ class BottleneckTransformer(BaseModel): Unified mode (``unified_embedding`` supplied): all temporal fields are jointly embedded and time-sorted by - :class:`~pyhealth.models.embedding.unified.UnifiedMultimodalEmbeddingModel` + :class:`~pyhealth.models.unified_embedding.UnifiedMultimodalEmbeddingModel` into a single interleaved sequence. A single ``[CLS]`` token is prepended and the encoder runs with ``n_modality=1``, so the bottleneck tokens attend over the full cross-modal timeline. @@ -251,7 +251,6 @@ def __init__( len(self.label_keys) == 1 ), "Only one label key is supported if BottleneckTransformer is initialized" self.label_key = self.label_keys[0] - self.mode = self.dataset.output_schema[self.label_key] assert 0 <= fusion_startidx <= num_layers, ( f"fusion_startidx must be in [0, num_layers], got {fusion_startidx}"